Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I refresh my ListView after the database changes?

Tags:

android

sqlite

I am trying to manage a simple list in an Android application. The contents of the list are maintained in a SQLite database. When the user selects and holds on a specific row, a context menu appears with a "Delete" option. When they select "Delete", the row is deleted from the database, but the view does not refresh. When I back out of the application and get back in, the appropriate row has been removed. So, I know the row is deleted, it's just the ListView that doesn't refresh.

Here are the relevant bits of code...

In the onCreate method...

SQLiteDatabase db = tasks.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, 
    new String[] { _ID, TITLE, DETAILS, }, 
    null, null, null, null, TITLE + " DESC");
startManagingCursor(cursor);

ListView lv = (ListView) findViewById(R.id.list);
lv.setAdapter(new SimpleCursorAdapter(this, 
    android.R.layout.simple_list_item_1,
    cursor,
    new String[] {TITLE},
    new int[] { android.R.id.text1}
));

In the onContextItemSelected method...

switch(item.getItemId()) {
case 0:
    SQLiteDatabase db = tasks.getWritableDatabase();
    ListView lv = (ListView) findViewById(R.id.list);
    SimpleCursorAdapter adapter = (SimpleCursorAdapter) lv.getAdapter();
    db.delete(TABLE_NAME, "_ID=?", new String[] {adapter.getCursor().getString(0)});
    adapter.notifyDataSetChanged(); // Not working, clears screen and doesn't reload
    return true;
}
return super.onContextItemSelected(item);

What am I missing?

Thanks!

like image 549
Andrew Patzer Avatar asked Feb 21 '11 18:02

Andrew Patzer


People also ask

How can you update a ListView dynamically?

This example demonstrates how do I dynamically update a ListView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do you refresh an ArrayList?

To update or set an element or object at a given index of Java ArrayList, use ArrayList. set() method. ArrayList. set(index, element) method updates the element of ArrayList at specified index with given element.

What is the use of ListView explain list view with example?

Android ListView is a ViewGroup that is used to display the list of items in multiple rows and contains an adapter that automatically inserts the items into the list. The main purpose of the adapter is to fetch data from an array or database and insert each item that placed into the list for the desired result.


1 Answers

Get rid of the notifyDataSetChanged() and call requery() on your Cursor. Here is a sample project demonstrating this.

like image 65
CommonsWare Avatar answered Sep 24 '22 11:09

CommonsWare