Android sqLite Data retrieving [No Error Showing] - java

Trying to retrieve the data from sqLite and show it in Alert Dialog Builder.
But not Showing the data at all. When I click on the View Button nothing happens.
MainActivity.java
package com.example.database;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity{
EditText first,last,age,classc;
Button add,view;
String FirstName;
String LastName;
String Class;
Integer Age;
sqLit myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new sqLit(this);
Link();
addButtonClicked();
viewButtonClicked();
}
public void addButtonClicked()
{
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
xmlToVar();
Integer flag=myDB.insertValue(FirstName, LastName, Class, Age);
if (flag==1)
{
Context context=MainActivity.this;
Toast toast = Toast.makeText(context, "Record Added" , Toast.LENGTH_LONG);
toast.show();
}
else
{
Context context=MainActivity.this;
Toast toast = Toast.makeText(context, "Error Occured" , Toast.LENGTH_LONG);
toast.show();
}
}
});
}
public void viewButtonClicked()
{
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Cursor res = myDB.getData();
if (res.getCount()==0)
{
showMessage("Error" , "No Data Found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext())
{
buffer.append("ID : " + res.getString(0) + "\n");
buffer.append("FirstName : " + res.getString(1) + "\n");
buffer.append("LastName : " + res.getString(2) + "\n");
buffer.append("Class : " + res.getString(3) + "\n");
buffer.append("Age : " + res.getString(4) + "\n");
showMessage("Here is your Data",buffer.toString() );
}
}
});
}
public void showMessage(String title, String message)
{
AlertDialog.Builder Builder = new AlertDialog.Builder(this);
Builder.setCancelable(true);
Builder.setTitle(title);
Builder.setMessage(message);
}
public void Link()
{
first=(EditText) findViewById(R.id.editFirst);
last=(EditText) findViewById(R.id.editLast);
classc=(EditText) findViewById(R.id.editClass);
age=(EditText) findViewById(R.id.editAge);
add=(Button) findViewById(R.id.Add);
view=(Button) findViewById(R.id.ViewAll);
}
public void xmlToVar()
{
FirstName = first.getText().toString();
LastName = last.getText().toString();
Class = classc.getText().toString();
Age = Integer.parseInt(age.getText().toString());
}
}
sqLit.java
package com.example.database;
import org.w3c.dom.Text;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.text.Editable;
public class sqLit extends SQLiteOpenHelper
{
public static final String DB_NAME="student12.db";
public static final String TABLE_NAME="class1";
public static final String COL_1="ROLLNO";
public static final String COL_2="FirstName";
public static final String COL_3="LastName";
public static final String COL_4="Class";
public static final String COL_5="Age";
public sqLit(Context context) {
super(context, DB_NAME, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"+COL_2 + " TEXT,"+COL_3 + " TEXT,"+COL_4 + " TEXT,"+COL_5 + " INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("Drop Table If Exist" + TABLE_NAME );
onCreate(db);
}
public Integer insertValue(String firstName, String lastName, String Class, Integer Age)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentV = new ContentValues();
contentV.put(COL_2, firstName);
contentV.put(COL_3, lastName);
contentV.put(COL_4, Class);
contentV.put(COL_5, Age);
long isInserted = db.insert(TABLE_NAME, null, contentV);
if (isInserted == -1){
return 0;
}
else
{
return 1;
}
}
public Cursor getData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * From "+TABLE_NAME, null);
return res;
}
}
LogCat
06-11 22:02:40.728: D/dalvikvm(1576): Not late-enabling CheckJNI (already on)
06-11 22:02:40.737: E/Trace(1576): error opening trace file: No such file or directory (2)
06-11 22:02:40.817: D/gralloc_goldfish(1576): Emulator without GPU emulation detected.
06-11 22:05:14.779: D/dalvikvm(1576): GC_CONCURRENT freed 197K, 5% free 6176K/6471K, paused 15ms+0ms, total 19ms
06-11 22:08:27.242: E/Trace(2066): error opening trace file: No such file or directory (2)
06-11 22:08:27.322: D/gralloc_goldfish(2066): Emulator without GPU emulation detected.
06-11 22:08:31.472: D/dalvikvm(2066): GC_CONCURRENT freed 225K, 5% free 6148K/6471K, paused 17ms+1ms, total 19ms
06-11 22:10:36.644: D/dalvikvm(2290): GC_CONCURRENT freed 225K, 5% free 6148K/6471K, paused 16ms+0ms, total 19ms
06-11 22:10:52.355: D/AndroidRuntime(2290): Shutting down VM
06-11 22:10:52.355: W/dalvikvm(2290): threadid=1: thread exiting with uncaught exception (group=0xb3f1c288)
06-11 22:10:52.355: E/AndroidRuntime(2290): FATAL EXCEPTION: main
06-11 22:10:52.355: E/AndroidRuntime(2290): java.lang.NumberFormatException: Invalid int: ""
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.Integer.invalidInt(Integer.java:138)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.Integer.parseInt(Integer.java:359)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.Integer.parseInt(Integer.java:332)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.example.database.MainActivity.xmlToVar(MainActivity.java:115)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.example.database.MainActivity$1.onClick(MainActivity.java:46)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.view.View.performClick(View.java:4084)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.view.View$PerformClick.run(View.java:16966)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.os.Handler.handleCallback(Handler.java:615)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.os.Handler.dispatchMessage(Handler.java:92)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.os.Looper.loop(Looper.java:137)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.app.ActivityThread.main(ActivityThread.java:4745)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.reflect.Method.invokeNative(Native Method)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.reflect.Method.invoke(Method.java:511)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-11 22:10:52.355: E/AndroidRuntime(2290): at dalvik.system.NativeStart.main(Native Method)
06-11 22:12:22.676: D/dalvikvm(2455): GC_CONCURRENT freed 201K, 5% free 6172K/6471K, paused 17ms+0ms, total 19ms
06-11 22:14:01.238: D/dalvikvm(2652): Not late-enabling CheckJNI (already on)
06-11 22:14:01.248: E/Trace(2652): error opening trace file: No such file or directory (2)
06-11 22:14:01.338: D/gralloc_goldfish(2652): Emulator without GPU emulation detected.
The Button isn’t working at all.

The below exception from xmlToVar method is the problem, you are calling this in addButtonClicked method
java.lang.NumberFormatException: Invalid int: ""
If the value in Age field is not entered then this error will happen if you make empty check before calling
Age = Integer.parseInt(age.getText().toString());
should solve the issue

Validate input before you use parseInt in xmlToVar():
String ageStr = age.getText().toString();
if (ageStr != "")
r.age = Integer.parseInt(ageStr);
You can also initialize Integer age, if there can be a default value.

You need to provide information about the following :
i) Did you try to debug ?
ii) If yes, does the cursor get any data ?
Now a different approach to the problem :
Create class of data [makes it easier to handle, i.e store and fetch from database]
example :
Class :
public class NoticeInformation {
private String NoticeType, NoticeHeader, NoticeLink;
private int Important, NoticeId, Read;
public NoticeInformation(int NoticeId,
String NoticeType,
String NoticeHeader,
String NoticeLink,
int Important,
int Read){
this.NoticeId = NoticeId;
this.NoticeType = NoticeType;
this.NoticeHeader = NoticeHeader;
this.NoticeLink = NoticeLink;
this.Important = Important;
this.Read = Read;
}
public int getNoticeId() {
return NoticeId;
}
public void setNoticeId(int noticeId) {
NoticeId = noticeId;
}
public String getNoticeType() {
return NoticeType;
}
public void setNoticeType(String noticeType) {
NoticeType = noticeType;
}
public String getNoticeHeader() {
return NoticeHeader;
}
public void setNoticeHeader(String noticeHeader) {
NoticeHeader = noticeHeader;
}
public String getNoticeLink() {
return NoticeLink;
}
public void setNoticeLink(String noticeLink) {
NoticeLink = noticeLink;
}
public int getImportant() {
return Important;
}
public void setImportant(int important) {
Important = important;
}
public int getRead() {
return Read;
}
public void setRead(int read) {
Read = read;
}
}
Database Read :
public List<NoticeInformation> getScheduleNotice(){
SQLiteDatabase db = this.getReadableDatabase();
List<NoticeInformation> res = new ArrayList<>();
String Query = "SELECT * FROM " + TABLE_NAME1 + " WHERE NoticeType = 'Schedule';";
Cursor cursor = db.rawQuery(Query, null);
if (cursor.moveToFirst()){
cursor.moveToFirst();
do
{
NoticeInformation obj = new NoticeInformation(cursor.getInt(0), cursor.getString(1),
cursor.getString(2), cursor.getString(3), cursor.getInt(5),
cursor.getInt(4));
res.add(obj);
}while(cursor.moveToNext());
return res;
}
return null;
}
Instead of handling cursor in the application end, just have the data in a list. It is easier to handle [in my humble opinion].
Try this approach and let me know the result.

Related

Error: Unused Import Statement - import android.widget.AdapterView.OnItemClickListener; & import android.content.Context;

I have made a simple app which saves and displays bookmarks.
The view bookmarks activity is called by clicking on a menu item in the main activity.
The problem is that when I click the option to view bookmarks stored in view bookmarks Activity, my app crashes.
The problem, I think, is with the bookmark Activity because I have an unused import statement AdapterView.OnItemClickListener & content.Context.
How do I solve this issue?
PS: when I click the option in the main Activity to save a bookmark by launching the save bookmark Activity, it works perfectly.
Here is my code:
BookmarkPage.class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
public class BookmarkPage extends Activity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bookmark_page);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllBookmarks();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),DisplayBookmarks.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
bookmark_page.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".BookmarkPage">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Bookmarks"
android:textSize="30sp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView">
</ListView>
</RelativeLayout>
Logcat:
OpenGL ES Shader Compiler Version: E031.25.03.00
Build Date: 12/04/14 Thu
Local Branch:
Remote Branch: quic/LA.BF.1.1_rb1.14
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1_RB1.05.00.00.002.030 + NOTHING
10-03 18:10:35.793 18581-18642/com.carsaleindiaofficial.csitestapp W/cr.media﹕ Requires BLUETOOTH permission
10-03 18:10:35.830 18581-18581/com.carsaleindiaofficial.csitestapp E/libEGL﹕ validate_display:255 error 3008 (EGL_BAD_DISPLAY)
10-03 18:10:35.890 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.FloatingSelectActionModeCallback>
10-03 18:10:35.891 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.FloatingSelectActionModeCallback>
10-03 18:10:35.922 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.WebViewContentsClientAdapter$WebResourceErrorImpl>
10-03 18:10:35.922 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.WebViewContentsClientAdapter$WebResourceErrorImpl>
10-03 18:10:36.276 18581-18581/com.carsaleindiaofficial.csitestapp W/art﹕ Attempt to remove local handle scope entry from IRT, ignoring
10-03 18:10:36.318 18581-18581/com.carsaleindiaofficial.csitestapp W/AwContents﹕ onDetachedFromWindow called when already detached. Ignoring
10-03 18:10:36.836 18581-18681/com.carsaleindiaofficial.csitestapp D/OpenGLRenderer﹕ Render dirty regions requested: true
10-03 18:10:36.902 18581-18581/com.carsaleindiaofficial.csitestapp D/Atlas﹕ Validating map...
10-03 18:10:36.944 18581-18639/com.carsaleindiaofficial.csitestapp W/chromium﹕ [WARNING:data_reduction_proxy_config.cc(630)] SPDY proxy OFF at startup
10-03 18:10:37.192 18581-18681/com.carsaleindiaofficial.csitestapp I/OpenGLRenderer﹕ Initialized EGL, version 1.4
10-03 18:10:37.201 18581-18681/com.carsaleindiaofficial.csitestapp D/OpenGLRenderer﹕ Enabling debug mode 0
10-03 18:10:38.109 18581-18581/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 49 frames! The application may be doing too much work on its main thread.
10-03 18:10:38.213 18581-18581/com.carsaleindiaofficial.csitestapp I/progressBar﹕ Visible
10-03 18:10:38.222 18581-18596/com.carsaleindiaofficial.csitestapp I/art﹕ Background sticky concurrent mark sweep GC freed 10653(792KB) AllocSpace objects, 6(92KB) LOS objects, 12% free, 6MB/7MB, paused 1.507ms total 130.800ms
10-03 18:10:38.894 18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581
10-03 18:10:41.925 18581-18596/com.carsaleindiaofficial.csitestapp I/art﹕ Background partial concurrent mark sweep GC freed 12880(607KB) AllocSpace objects, 1(39KB) LOS objects, 40% free, 7MB/11MB, paused 1.053ms total 158.419ms
10-03 18:10:42.812 18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581
10-03 18:10:43.549 18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581
Problem Starts after progressbar:Gone (i.e when I press the view saved bookmarks option)
10-03 21:13:12.096 18489-18489/com.carsaleindiaofficial.csitestapp I/pageFinished﹕ yesss
10-03 21:13:12.353 18489-18489/com.carsaleindiaofficial.csitestapp I/progressBar﹕ Gone
10-03 21:13:26.413 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 64 frames! The application may be doing too much work on its main thread.
10-03 21:13:28.701 18489-18489/com.carsaleindiaofficial.csitestapp W/art﹕ Before Android 4.1, method int android.support.v7.internal.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
10-03 21:13:30.289 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 129 frames! The application may be doing too much work on its main thread.
10-03 21:13:31.604 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 78 frames! The application may be doing too much work on its main thread.
10-03 21:13:33.328 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 80 frames! The application may be doing too much work on its main thread.
10-03 21:13:35.714 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 38 frames! The application may be doing too much work on its main thread.
10-03 21:13:36.532 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 44 frames! The application may be doing too much work on its main thread.
10-03 21:13:37.719 18489-18489/com.carsaleindiaofficial.csitestapp E/CursorWindow﹕ Failed to read row 0, column -1 from a CursorWindow which has 9 rows, 2 columns.
10-03 21:13:37.777 18489-18489/com.carsaleindiaofficial.csitestapp D/AndroidRuntime﹕ Shutting down VM
10-03 21:13:37.892 18489-18489/com.carsaleindiaofficial.csitestapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.carsaleindiaofficial.csitestapp, PID: 18489
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carsaleindiaofficial.csitestapp/com.carsaleindiaofficial.csitestapp.BookmarkPage}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at com.carsaleindiaofficial.csitestapp.DBHelper.getAllBookmarks(DBHelper.java:90)
at com.carsaleindiaofficial.csitestapp.BookmarkPage.onCreate(BookmarkPage.java:32)
at android.app.Activity.performCreate(Activity.java:5953)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
10-03 21:13:43.601 18489-18489/com.carsaleindiaofficial.csitestapp I/Process﹕ Sending signal. PID: 18489 SIG: 9
My database: DBHelper.class
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String BOOKMARKS_TABLE_NAME = "bookmarks";
public static final String BOOKMARKS_COLUMN_ID = "id";
public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table bookmarks " +
"(id integer primary key, bmtitle text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS bookmarks");
onCreate(db);
}
public boolean insertBookmark (String title)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("dbtitle", title);
db.insert("bookmarks", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from bookmarks where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, BOOKMARKS_TABLE_NAME);
return numRows;
}
public boolean updateBookmark (Integer id, String title)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", title);
db.update("bookmarks", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteBookmark (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("bookmarks",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllBookmarks()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from bookmarks", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(BOOKMARKS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
MainActivity.class
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends AppCompatActivity {
private WebView view;
ProgressBar progressBar;
ImageView im;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) this.findViewById(R.id.progressBar1);
im = (ImageView) this.findViewById(R.id.imageView2);
String url = "http://www.carsaleindiaofficial.com/?m=1";
view = (WebView) this.findViewById(R.id.webView);
view.setWebViewClient(new MyWebViewClient());
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setDomStorageEnabled(true);
view.loadUrl(url);
}
public class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.i("pageFinished", "yesss");
progressBar.setVisibility(View.GONE);
im.setVisibility(View.GONE);
Log.i("progressBar", "Gone");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.VISIBLE);
Log.i("progressBar", "Visible");
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("carsaleindiaofficial.com")) {
Log.i("ShldOvrideUrl", "CSI");
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
Log.i("ShldOvrideUrl", "OtherSite");
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.add_bookmark:
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Log.i("addBookmark", "loadingAddBookmark");
Intent intent = new Intent(getApplicationContext(),DisplayBookmarks.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
case R.id.show_bookmark:
Log.i("showBookmark", "loadingShowBookmark");
Intent intent2 = new Intent(getApplicationContext(),BookmarkPage.class);
startActivity(intent2);
return true;
case R.id.action_reload:
Log.i("actionReload", "ReloadingURL");
view.loadUrl(view.getUrl());
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (view.canGoBack()) {
view.goBack();
} else {
super.onBackPressed();
}
}
}
Here's your error:
Failed to read row 0, column -1 from a CursorWindow which has 9 rows, 2 columns. ... Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
This is because you create this table:
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table bookmarks " +
"(id integer primary key, dbtitle text)"
);
}
Then you try to access a non existing column:
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(BOOKMARKS_COLUMN_NAME)));
res.moveToNext();
}
Which is defined as a string constant:
public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";
But it's not created as a table column.
column -1 says that there's no column called bmtitle in your table.
And it's right, because, instead, there is a column named dbtitle.
Quick fix:
Simply change
public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";
to
public static final String BOOKMARKS_COLUMN_NAME = "dbtitle";

Android Database Application going wrong

I have created a simple Android application which asks for the users information such as name, blood type, contact number, etc., saves it in a database, and displays it in another screen. This is all suppose to happen when the save button is clicked which invokes the saveMe() method. However, when I click the save button, the app does not crash and close instead it gets stuck and then in the logcat I see something like:
08-08 22:41:23.734: D/dalvikvm(365): GC_FOR_MALLOC freed 321K, 50% free 2984K/5959K, external 716K/1038K, paused 18ms
08-08 22:41:23.754: D/dalvikvm(365): GC_FOR_MALLOC freed 322K, 50% free 2984K/5959K, external 716K/1038K, paused 18ms
08-08 22:41:23.784: D/dalvikvm(365): GC_FOR_MALLOC freed 323K, 50% free 2984K/5959K, external 716K/1038K, paused 21ms
08-08 22:41:23.804: D/dalvikvm(365): GC_FOR_MALLOC freed 324K, 50% free 2984K/5959K, external 716K/1038K, paused 19ms
08-08 22:41:23.824: D/dalvikvm(365): GC_FOR_MALLOC freed 324K, 50% free 2984K/5959K, external 716K/1038K, paused 20ms
08-08 22:41:23.844: D/dalvikvm(365): GC_FOR_MALLOC freed 325K, 50% free 2984K/5959K, external 716K/1038K, paused 20ms
08-08 22:41:23.874: D/dalvikvm(365): GC_FOR_MALLOC freed 326K, 50% free 2984K/5959K, external 716K/1038K, paused 25ms
08-08 22:41:23.894: D/dalvikvm(365): GC_FOR_MALLOC freed 327K, 50% free 2984K/5959K, external 716K/1038K, paused 23ms
08-08 22:41:23.934: D/dalvikvm(365): GC_FOR_MALLOC freed 327K, 50% free
These messages keep appearing in log cat. The only way I can stop them is if I close the emulator. Is the app getting stuck in a infinite loop? No data get saved or displayed.
Database Class
package com.example.androidsimpledbapp1;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
/*
* Class for Working with DB
*/
//Update each time DB structure changes e.g. adding new property
private static final int DATABASE_VERSION =1;
//DB Name
private static final String DATABASE_NAME = "deets.db";
//Table name
public static final String TABLE_PRODUCTS = "products";
//DB Columns
public static final String COLUMN_ID = "_Id";
public static final String COLUMN_PERSONNAME = "firstName";
public static final String COLUMN_PERSONBLOOD = "bloodType";
public static final String COLUMN_PERSONCONTACT = "contactName";
public static final String COLUMN_PERSONNUMBER = "phoneNumber";
public static final String COLUMN_PERSONRELATION = "relationship";
//Constructor
/*
* Passing information to super class in SQL
* Context is background information
* name of db
* Database version
*/
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
/*
* What to do first time when you create DB
* Creates the table the very first time
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
* Remember to use Commas as shown below
*/
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE "+ TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
COLUMN_PERSONNAME + " TEXT, "+
COLUMN_PERSONBLOOD + " TEXT, "+
COLUMN_PERSONCONTACT + " TEXT, "+
COLUMN_PERSONNUMBER + " TEXT, " +
COLUMN_PERSONRELATION + " TEXT " +
");";
//Execute the query
db.execSQL(query);
}
/*
* If ever upgrading DB call this method
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//Delete the current table
db.execSQL("DROP TABLE IF EXISTS" + TABLE_PRODUCTS);
//create new table
onCreate(db);
}
//Add new row to the database
public void addProduct(Details details){
//Built in class - set values for different columns
//Makes inserting rows quick and easy
ContentValues values = new ContentValues();
values.put(COLUMN_PERSONNAME, details.get_firstName());
values.put(COLUMN_PERSONBLOOD, details.get_bloodType());
values.put(COLUMN_PERSONCONTACT, details.get_contactName());
values.put(COLUMN_PERSONNUMBER, details.get_phoneNumber());
values.put(COLUMN_PERSONRELATION, details.get_relationship());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
/*
public void deleteProducts(){
SQLiteDatabase = getWritableDatabase();
db.execSQL("DROP TABLE");
How to delete the database...
}
*/
//Take DB and Convert to String
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
//Every Column and row
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
//First row point here, second row point here
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
//Extracts first name and adds to string
if(c.getString(c.getColumnIndex("firstName"))!=null){
dbString += c.getString(c.getColumnIndex("firstName"));
/*
* Displaying all other columns
*/
}
}
db.close();
return dbString;
}
}
Details Class
package com.example.androidsimpledbapp1;
public class Details {
//primary key
private int _id;
//Properties
private String _firstName;
private String _bloodType;
private String _contactName;
private String _phoneNumber;
private String _relationship;
//Dont Have to Enter Everything each time
public Details(){
}
public Details(String firstName){
this.set_firstName(firstName);
}
//Passing in details
//Setting values from the user
public Details(String firstName, String bloodType,
String contactName, String phoneNumber,
String relationship){
this.set_firstName(firstName);
this.set_bloodType(bloodType);
this.set_contactName(contactName);
this.set_phoneNumber(phoneNumber);
this.set_relationship(relationship);
}
//Retrieve the data
public int get_id() {
return _id;
}
//Setter allows to give property
public void set_id(int _id) {
this._id = _id;
}
public String get_firstName() {
return _firstName;
}
public void set_firstName(String _firstName) {
this._firstName = _firstName;
}
public String get_bloodType() {
return _bloodType;
}
public void set_bloodType(String _bloodType) {
this._bloodType = _bloodType;
}
public String get_contactName() {
return _contactName;
}
public void set_contactName(String _contactName) {
this._contactName = _contactName;
}
public String get_phoneNumber() {
return _phoneNumber;
}
public void set_phoneNumber(String _phoneNumber) {
this._phoneNumber = _phoneNumber;
}
public String get_relationship() {
return _relationship;
}
public void set_relationship(String _relationship) {
this._relationship = _relationship;
}
}
Edit Screen - Where the save button is clicked
public class EditScreen extends Activity {
EditText firstNameInput;
EditText bloodTypeInput;
EditText contacNameInput;
EditText phoneNumberInput;
EditText relationshipInput;
TextView displayName;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_screen);
firstNameInput = (EditText) findViewById(R.id.inputname);
bloodTypeInput = (EditText) findViewById(R.id.inputblood);
contacNameInput = (EditText) findViewById(R.id.inputcontact);
phoneNumberInput = (EditText) findViewById(R.id.inputnum);
relationshipInput = (EditText) findViewById(R.id.inputraltion);
displayName = (TextView) findViewById(R.id.dbname);
dbHandler = new MyDBHandler(this, null, null, 1);
}
/*
* Causing error fix the error
*/
public void saveMe(View v){
Details detail = new Details(firstNameInput.getText().toString(),
bloodTypeInput.getText().toString(),
contacNameInput.getText().toString(),
phoneNumberInput.getText().toString(),
relationshipInput.getText().toString()
);
dbHandler.addProduct(detail);
printDatabase();
}
private void printDatabase() {
//Taking the string
String dbString = dbHandler.databaseToString();
//Display in the textview
displayName.setText(dbString);
}
}
Main Activity
package com.example.androidsimpledbapp1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Changing Activity
public void editBtnPressed(View v){
Intent intent = new Intent(MainActivity.this, EditScreen.class);
startActivity(intent);
}
}
Logcat - Error
08-08 22:41:00.034: D/AndroidRuntime(348): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
08-08 22:41:00.054: D/AndroidRuntime(348): CheckJNI is ON
08-08 22:41:00.273: I/ActivityManager(60): Start proc com.svox.pico for broadcast com.svox.pico/.VoiceDataInstallerReceiver: pid=350 uid=10028 gids={}
08-08 22:41:00.583: I/ActivityThread(350): Pub com.svox.pico.providers.SettingsProvider: com.svox.pico.providers.SettingsProvider
08-08 22:41:00.663: D/GTalkService(185): handlePackageInstalled: re-initialize providers
08-08 22:41:00.663: D/GTalkService(185): [RawStanzaProvidersMgr] ##### searchProvidersFromIntent
08-08 22:41:00.663: D/GTalkService(185): [RawStanzaProvidersMgr] no intent receivers found
08-08 22:41:00.713: D/dalvikvm(335): GC_CONCURRENT freed 211K, 43% free 3575K/6215K, external 716K/1038K, paused 3ms+4ms
08-08 22:41:00.874: D/AndroidRuntime(348): Calling main entry com.android.commands.am.Am
08-08 22:41:00.904: I/ActivityManager(60): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.androidsimpledbapp1/.MainActivity } from pid 348
08-08 22:41:00.974: D/AndroidRuntime(348): Shutting down VM
08-08 22:41:00.984: I/ActivityManager(60): Start proc com.example.androidsimpledbapp1 for activity com.example.androidsimpledbapp1/.MainActivity: pid=365 uid=10045 gids={}
08-08 22:41:00.994: D/dalvikvm(348): GC_CONCURRENT freed 101K, 69% free 318K/1024K, external 0K/0K, paused 1ms+1ms
08-08 22:41:01.004: D/jdwp(348): adbd disconnected
08-08 22:41:01.154: D/dalvikvm(32): GC_EXPLICIT freed 11K, 50% free 2719K/5379K, external 716K/1038K, paused 168ms
08-08 22:41:01.214: D/dalvikvm(32): GC_EXPLICIT freed <1K, 50% free 2719K/5379K, external 716K/1038K, paused 62ms
You're missing c.moveToNext() in your databaseToString() while loop and the loop never terminates.

Android sqLite.. Application unfortunately has stopped

I am Creating SqLite Application ... the application is launched perfectly but when I fill all EditText Fields And Click On The Add Button.. The Application has stopped.. this message popups..
MainActivity.java
package com.example.database;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity{
EditText first,last,age,classc;
Button add,view;
String FirstName;
String LastName;
String Class;
String Age;
sqLit myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new sqLit(this);
Link();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
xmlToVar();
Integer flag=myDB.insertValue(FirstName, LastName, Class, Age);
if (flag==1)
{
Context context=MainActivity.this;
Toast toast = Toast.makeText(context, "Record Added" , Toast.LENGTH_LONG);
toast.show();
}
else
{
Context context=MainActivity.this;
Toast toast = Toast.makeText(context, "Error Occured" , Toast.LENGTH_LONG);
toast.show();
}
}
});
}
public void Link()
{
first=(EditText) findViewById(R.id.editFirst);
last=(EditText) findViewById(R.id.editLast);
classc=(EditText) findViewById(R.id.editClass);
age=(EditText) findViewById(R.id.editAge);
add=(Button) findViewById(R.id.Add);
view=(Button) findViewById(R.id.ViewAll);
}
public void xmlToVar()
{
FirstName = first.getText().toString();
LastName = last.getText().toString();
Class = classc.getText().toString();
try
{
Age = age.getText().toString();
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
}
}
sqLit.java
package com.example.database;
import org.w3c.dom.Text;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.text.Editable;
public class sqLit extends SQLiteOpenHelper
{
public static final String DB_NAME="student12.db";
public static final String TABLE_NAME="class1";
public static final String COL_1="ROLLNO";
public static final String COL_2="FirstName";
public static final String COL_3="LastName";
public static final String COL_4="Class";
public static final String COL_5="Age";
public sqLit(Context context) {
super(context, DB_NAME, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +COL_1 + " INTEGER AUTOINCREMENT PRIMARY KEY,"+COL_2 + " TEXT,"+COL_3 + " TEXT,"+COL_4 + " TEXT,"+COL_5 + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("Drop Table If Exist" + TABLE_NAME );
onCreate(db);
}
public Integer insertValue(String firstName, String lastName, String Class, String Age)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentV = new ContentValues();
contentV.put(COL_2, firstName);
contentV.put(COL_3, lastName);
contentV.put(COL_4, Class);
contentV.put(COL_5, Age);
long isInserted = db.insert(TABLE_NAME, null, contentV);
if (isInserted == -1){
return 0;
}
else
{
return 1;
}
}
}
Logcat
06-11 20:28:40.925: W/dalvikvm(25232): threadid=1: thread exiting with uncaught exception (group=0xb3f2b288)
06-11 20:28:40.925: E/AndroidRuntime(25232): FATAL EXCEPTION: main
06-11 20:28:40.925: E/AndroidRuntime(25232): android.database.sqlite.SQLiteException: near "AUTOINCREMENT": syntax error (code 1): , while compiling: CREATE TABLE class1(ROLLNO INTEGER AUTOINCREMENT PRIMARY KEY,FirstName TEXT,LastName TEXT,Class TEXT,Age TEXT)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
06-11 20:28:40.925: E/AndroidRuntime(25232): at com.example.database.sqLit.onCreate(sqLit.java:35)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
06-11 20:28:40.925: E/AndroidRuntime(25232): at com.example.database.sqLit.insertValue(sqLit.java:48)
06-11 20:28:40.925: E/AndroidRuntime(25232): at com.example.database.MainActivity$1.onClick(MainActivity.java:44)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.view.View.performClick(View.java:4084)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.view.View$PerformClick.run(View.java:16966)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.os.Handler.handleCallback(Handler.java:615)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.os.Handler.dispatchMessage(Handler.java:92)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.os.Looper.loop(Looper.java:137)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.app.ActivityThread.main(ActivityThread.java:4745)
06-11 20:28:40.925: E/AndroidRuntime(25232): at java.lang.reflect.Method.invokeNative(Native Method)
06-11 20:28:40.925: E/AndroidRuntime(25232): at java.lang.reflect.Method.invoke(Method.java:511)
06-11 20:28:40.925: E/AndroidRuntime(25232): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-11 20:28:40.925: E/AndroidRuntime(25232): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-11 20:28:40.925: E/AndroidRuntime(25232): at dalvik.system.NativeStart.main(Native Method)
06-11 20:28:40.944: D/dalvikvm(25232): GC_CONCURRENT freed 203K, 5% free 6173K/6471K, paused 13ms+0ms, total 16ms
Thanks Guys.. :)
Can you try to re-shuffle the SQL autoincrement location?
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"+COL_2 + " TEXT,"+COL_3 + " TEXT,"+COL_4 + " TEXT,"+COL_5 + " TEXT)");
Edit:
Actually, I may have been over complicating. It appears (according to the SQL Lite documentation at http://www.sqlite.org/faq.html#q1) that:
"If you declare a column of a table to be INTEGER PRIMARY KEY, then
whenever you insert a NULL into that column of the table, the NULL is
automatically converted into an integer which is one greater than the
largest value of that column over all other rows in the table, or 1 if
the table is empty."
So you may be okay to leave out AUTOINCREMENT altogether as long as you insert nulls in there later on.

SQLite Application Crashes during launch

So I am trying out a tutorial for SQLite I have seen in the internet, and after tweaking it a bit I launched it and it crashes. Before modifying the code, it works. I know that some of the functions are deprecated, but that didn't seem to be the issue because as I said it ran before I modified it. I also know that the error is on line 44 on one of my classes (I have put a comment in this line to distinguish it) but I don't see why it gives me an error. Here is my code:
AndroidSQLite.java:
package com.example.sqlite;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class AndroidSQLite extends Activity {
EditText inputContent1, inputContent2, inputContent3;
Button buttonAdd, buttonDeleteAll;
private SQLiteAdapter mySQLiteAdapter;
ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inputContent1 = (EditText)findViewById(R.id.UserID);
inputContent2 = (EditText)findViewById(R.id.Password);
inputContent3 = (EditText)findViewById(R.id.Fname);
buttonAdd = (Button)findViewById(R.id.add);
buttonDeleteAll = (Button)findViewById(R.id.deleteall);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter.KEY_USERS_USERID, SQLiteAdapter.KEY_USERS_PASSWORD, SQLiteAdapter.KEY_USERS_FNAME};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2};
cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
buttonAdd.setOnClickListener(buttonAddOnClickListener);
buttonDeleteAll.setOnClickListener(buttonDeleteAllOnClickListener);
}
Button.OnClickListener buttonAddOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String data1 = inputContent1.getText().toString();
String data2 = inputContent2.getText().toString();
String data3 = inputContent3.getText().toString();
mySQLiteAdapter.insert(data1, data2, data3);
updateList();
}
};
Button.OnClickListener buttonDeleteAllOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mySQLiteAdapter.deleteAll();
updateList();
}
};
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mySQLiteAdapter.close();
}
#SuppressWarnings("deprecation")
private void updateList(){
cursor.requery();
}
}
SQLiteAdapter.java
package com.example.sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String DB_NAME = "adserve";
public static final String DB_TABLE_USERS = "users";
public static final int DB_VERSION = 1;
public static final String KEY_USERS_USERID = "_id";
public static final String KEY_USERS_PASSWORD = "Password";
public static final String KEY_USERS_FNAME = "Fname";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + DB_TABLE_USERS + " ("
+ KEY_USERS_USERID + " integer primary key, "
+ KEY_USERS_PASSWORD + " text not null, "
+ KEY_USERS_FNAME + " text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, DB_NAME, null, DB_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, DB_NAME, null, DB_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String UserID, String Password, String Fname){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_USERS_USERID, UserID);
contentValues.put(KEY_USERS_PASSWORD, Password);
contentValues.put(KEY_USERS_FNAME, Fname);
return sqLiteDatabase.insert(DB_TABLE_USERS, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(DB_TABLE_USERS, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_USERS_USERID, KEY_USERS_PASSWORD, KEY_USERS_FNAME};
Cursor cursor = sqLiteDatabase.query(DB_TABLE_USERS, columns, null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
And my logcat:
02-20 10:04:53.811: E/AndroidRuntime(1940): FATAL EXCEPTION: main
02-20 10:04:53.811: E/AndroidRuntime(1940): Process: com.example.sqlite, PID: 1940
02-20 10:04:53.811: E/AndroidRuntime(1940): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sqlite/com.example.sqlite.AndroidSQLite}: java.lang.IllegalArgumentException: column '_id' does not exist
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.access$700(ActivityThread.java:135)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.os.Handler.dispatchMessage(Handler.java:102)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.os.Looper.loop(Looper.java:137)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.main(ActivityThread.java:4998)
02-20 10:04:53.811: E/AndroidRuntime(1940): at java.lang.reflect.Method.invokeNative(Native Method)
02-20 10:04:53.811: E/AndroidRuntime(1940): at java.lang.reflect.Method.invoke(Method.java:515)
02-20 10:04:53.811: E/AndroidRuntime(1940): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
02-20 10:04:53.811: E/AndroidRuntime(1940): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
02-20 10:04:53.811: E/AndroidRuntime(1940): at dalvik.system.NativeStart.main(Native Method)
02-20 10:04:53.811: E/AndroidRuntime(1940): Caused by: java.lang.IllegalArgumentException: column '_id' does not exist
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.CursorAdapter.init(CursorAdapter.java:172)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.CursorAdapter.<init>(CursorAdapter.java:120)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.ResourceCursorAdapter.<init>(ResourceCursorAdapter.java:52)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:78)
02-20 10:04:53.811: E/AndroidRuntime(1940): at com.example.sqlite.AndroidSQLite.onCreate(AndroidSQLite.java:43)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.Activity.performCreate(Activity.java:5243)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
02-20 10:04:53.811: E/AndroidRuntime(1940): ... 11 more
Quoting the documentation for CursorAdapter:
The Cursor must include a column named "_id" or this class will not work
You do not have such a column in your Cursor, as far as I can tell.
One solution would be to switch from query() to rawQuery(), so you can add ROWID AS _id to your list of columns, to fulfil the CursorAdapter contract.
The SQLite Site says,
In SQLite, table rows normally have a 64-bit signed integer ROWID which is unique among all rows in the same table. (WITHOUT ROWID tables are the exception.)
So if you want to use a column only as an integer primary key, you can directly access the in built one using ROWID.
and the document on Cursor adapter says,
The Cursor must include a column named "_id" or this class will not work. Additionally, using MergeCursor with this class will not work if the merged Cursors have overlapping values in their "_id" columns.
which is the error you are getting.
Also if searched, you could find solution to yours on already answered SO questions like this one.

Null Pointer Exception : coudnt find solution

I am getting error in my code which is not understandable.. please help me find out what issue is it.
i have database class and main activity.. it shows in log but when it comes to appear at my emulator's screen it gives me error.
my database class:
package com.example.nearby_places;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Database extends SQLiteOpenHelper {
//database name & version number
private static final String db_name = "nearby_places";
private static final int db_version = 1;
//tables
private static final String table_placetypes = "placetypes";
private static final String table_places = "table_places";
//column names
private static final String type_id = "type_id";
private static final String type_name = "type_name";
private static final String place_id = "place_id";
private static final String place_name = "place_name";
private static final String place_address = "place_address";
private static final String place_contact = "place_contact";
public Database(Context context) {
super(context, db_name, null, db_version);
// TODO Auto-generated constructor stub
}
// create table queries
String create_table_placetypes = "CREATE TABLE IF NOT EXISTS " + table_placetypes + "("
+ type_id + " INTEGER PRIMARY KEY NOT NULL," + type_name + " TEXT" + ")";
String create_table_places = "CREATE TABLE IF NOT EXISTS table_places (place_id INTEGER PRIMARY KEY NOT NULL, place_name TEXT, place_address TEXT, place_contact TEXT, type_id INTEGER, FOREIGN KEY (type_id) REFERENCES table_placetypes(type_id))";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(create_table_placetypes);
Log.d("creating", "placetypes created");
db.execSQL(create_table_places);
Log.d("creating", "places created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + table_placetypes);
db.execSQL("DROP TABLE IF EXISTS " + table_places);
onCreate(db);
}
// add placetypes
void addplacetypes (placetypes pt) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(type_name, pt.getTypename());
db.insert(table_placetypes, null, values);
db.close();
}
// Getting single placetypes
placetypes getPlacetypes(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table_placetypes, new String[] {type_id,
type_name }, type_id + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
placetypes pt = new placetypes(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return contact
return pt;
}
// Getting All placetypes
public List<placetypes> getAllPlacetypes() {
List<placetypes> placetypesList = new ArrayList<placetypes>();
// Select All Query
String selectQuery = "SELECT * FROM " + table_placetypes;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
placetypes pt = new placetypes();
pt.setTypeid(Integer.parseInt(cursor.getString(0)));
pt.setTypename(cursor.getString(1));
//String name = cursor.getString(1);
//MainActivity.ArrayofName.add(name);
// Adding contact to list
placetypesList.add(pt);
} while (cursor.moveToNext());
}
// return placetype list
return placetypesList;
}
// Getting placetypes Count
public int getPlacetypesCount() {
String countQuery = "SELECT * FROM " + table_placetypes;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
public void addplaces(places p) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(place_name, p.getPlace_name());
values.put(place_address, p.getPlace_address());
values.put(place_contact, p.getPlace_contact());
values.put(type_id, p.getT_id());
Log.d("Type ID", String.valueOf(p.getT_id()));
db.insert(table_places, null, values);
db.close();
}
places getPlaces(int pid) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(table_places, new String[] {place_id, place_name, place_address, place_contact,type_id}, place_id + "=?", new String[] { String.valueOf(pid) } , null, null, null, null);
if(cursor != null)
cursor.moveToFirst();
places p = new places(Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4)
);
cursor.close();
return p;
}
public List<places> getAllPlaces(String typeName) {
List<places> placeList = new ArrayList<places>();
//String selectQuery = "SELECT * FROM table_places INNER JOIN placetypes ON placetypes.type_id=table_places.type_id ";
//String selectQuery = "SELECT * FROM table_places WHERE table_places.type_id="+Integer.toString(typeid);
String selectQuery ="SELECT * FROM table_places WHERE placetypes.place_name="+typeName+" INNER JOIN placetypes ON placetypes.type_id=table_places.type_id";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst() )
{
do{
places p = new places();
/*p.setT_id(cursor.getColumnIndex(type_id));
p.setPlace_id(cursor.getColumnIndex(place_id));
p.setPlace_name(cursor.getColumnIndex(place_name));
*/
p.setT_id(cursor.getInt(0));
p.setPlace_id(cursor.getInt(1));
p.setPlace_name(cursor.getString(2));
p.setPlace_address(cursor.getString(3));
p.setPlace_contact(cursor.getString(4));
/*String t_id = cursor.getString(4);
String p_name = cursor.getString(2);
String p_address = cursor.getString(3);
String p_contact = cursor.getString(1);*/
placeList.add(p);
}while(cursor.moveToNext());
}
cursor.close();
return placeList;
}
public int getPlaceCount () {
String selectQuery = "SELECT * FROM " +table_places;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(create_table_places, null);
cursor.close();
return cursor.getCount();
}
}
MainActivity
package com.example.nearby_places;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private ListView listView;
public static ArrayList<String> ArrayofName = new ArrayList<String>();
public static final String PLACETYPE = "com.example";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Database db = new Database(this);
if(db.getAllPlacetypes().isEmpty())
{
/**
* CRUD Operations
* */
// Inserting Places
Log.d("Insert: ", "Inserting ..");
db.addplacetypes(new placetypes("RESTURAUNTS"));
db.addplacetypes(new placetypes("MALLS"));
db.addplacetypes(new placetypes("GAS STATIONS"));
db.addplacetypes(new placetypes("HOTELS"));
db.addplacetypes(new placetypes("MOTELS"));
}
// Reading all Places
Log.d("Reading: ", "Reading all placetypes..");
if(ArrayofName.isEmpty())
{
List<placetypes> placetypes = db.getAllPlacetypes();
for (placetypes pt : placetypes)
{
String log = "Id: "+pt.getTypeid()+" ,Name: " + pt.getTypename();
// Writing Places to log
Log.d("Name: ", log);
System.out.println(log);
ArrayofName.add(pt.getTypename());
}
}
listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
int pos = listView.getAdapter().getCount() -1;
listView.getAdapter().getItemId(pos);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String type = ((TextView) v).getText().toString();
Toast.makeText(getApplicationContext(), type, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
i.putExtra(PLACETYPE, type);
startActivity(i);
/*Cursor cursor = (Cursor) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "id: " +id+ "position: " +position+ "row id: " +(cursor.getColumnIndex("" +
"")), Toast.LENGTH_LONG).show();
*/
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}
}
);
}
}
Logcat
10-11 17:21:51.871: D/Reading:(4932): Reading all placetypes..
10-11 17:21:51.871: D/Name:(4932): Id: 1 ,Name: RESTURAUNTS
10-11 17:21:51.875: I/System.out(4932): Id: 1 ,Name: RESTURAUNTS
10-11 17:21:51.875: D/Name:(4932): Id: 2 ,Name: MALLS
10-11 17:21:51.875: I/System.out(4932): Id: 2 ,Name: MALLS
10-11 17:21:51.875: D/Name:(4932): Id: 3 ,Name: GAS STATIONS
10-11 17:21:51.875: I/System.out(4932): Id: 3 ,Name: GAS STATIONS
10-11 17:21:51.875: D/Name:(4932): Id: 4 ,Name: HOTELS
10-11 17:21:51.875: I/System.out(4932): Id: 4 ,Name: HOTELS
10-11 17:21:51.875: D/Name:(4932): Id: 5 ,Name: MOTELS
10-11 17:21:51.875: I/System.out(4932): Id: 5 ,Name: MOTELS
10-11 17:21:51.887: D/AndroidRuntime(4932): Shutting down VM
10-11 17:21:51.887: W/dalvikvm(4932): threadid=1: thread exiting with uncaught exception (group=0x41c77300)
10-11 17:21:51.894: E/AndroidRuntime(4932): FATAL EXCEPTION: main
10-11 17:21:51.894: E/AndroidRuntime(4932): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nearby_places/com.example.nearby_places.MainActivity}: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.os.Handler.dispatchMessage(Handler.java:99)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.os.Looper.loop(Looper.java:137)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-11 17:21:51.894: E/AndroidRuntime(4932): at java.lang.reflect.Method.invokeNative(Native Method)
10-11 17:21:51.894: E/AndroidRuntime(4932): at java.lang.reflect.Method.invoke(Method.java:511)
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-11 17:21:51.894: E/AndroidRuntime(4932): at dalvik.system.NativeStart.main(Native Method)
10-11 17:21:51.894: E/AndroidRuntime(4932): Caused by: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.example.nearby_places.MainActivity.onCreate(MainActivity.java:62)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.Activity.performCreate(Activity.java:5008)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-11 17:21:51.894: E/AndroidRuntime(4932): ... 11 more
10-11 17:21:53.695: I/Process(4932): Sending signal. PID: 4932 SIG: 9
Your call to getAdapter is returning null because you're calling it before setAdapter, try this instead :
listView.setAdapter(adapter);
int pos = listView.getAdapter().getCount() -1;
listView.getAdapter().getItemId(pos);
If you have a NULLPOINTER Exception please have a deep look at your LogCat. Especial at the Line where it says Caused by.
Learn how to read and use your LogCat, and try to find the Line where it mentions your class/package name and analyse this line.
Caused by: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.example.nearby_places.MainActivity.onCreate(MainActivity.java:62)
The problem is in
List<placetypes> placetypes = db.getAllPlacetypes();
The query you are using is wrong. It should be
`SELECT * FROM table_places INNER JOIN placetypes ON placetypes.type_id=table_places.type_id WHERE placetypes.place_name="+typeName+`"

Categories

Resources