If you want to use a Cursor, Android automatically assumes that your tables have a column called _id
which acts as the row's unique primary identifier, for more details on that see the "Class Overview" section of the CursorAdapter's documentation which says:
Adapter that exposes data from a Cursor to a ListView widget. The Cursor must include a column named "_id" or this class will not work.
Basically all you need to do is replace your CREATE TABLE
call with:
db.execSQL("CREATE TABLE IF NOT EXISTS MyTable (_id INTEGER PRIMARY KEY AUTOINCREMENT, LastName VARCHAR,Phone VARCHAR);");
That should fix your crash. To get it to automatically refresh the list, see my comment regrading notifyDatasetChanged()
.
And as a sidenote: I'd strongly recommend using a SQLiteOpenHelper
instance to handle the opening and creation of your tables, rather than what you are doing now, it's bad form to repeatedly call CREATE TABLE IF NOT EXISTS
where you could only call it the one time you know it'd need to be called. Vogella.com has a great guide on that.
Edit: Based on your last edit of your code: You're still not requesting the _id
field that you made. If you don't have it in your SELECT statement the cursor can't access it!
Replace your rawQuery
in Populate_ListView
with SELECT * FROM MyTable
so that the _id
field is also returned by the cursor.