Android ListView update with SimpleCursorAdapter

Siggy Petersen picture Siggy Petersen · Nov 21, 2011 · Viewed 11.3k times · Source

Hey i use a listview for demonstrate entries which are stored in a database. I also have a EditText element and a button which adds the content of the EditText into the Database. To bind the view to the database content i use the SimpleCursorAdapter and following populate function:

private void populate() {
    cursor = dbAdapter.getAllItems();
    startManagingCursor(cursor);

    String[] from = new String[] { DBAdapter.KEY_TASK };
    int[] to = new int[] { android.R.id.text1 };

    // Now create an array adapter and set it to display using our row
    cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from, to);
    list.setAdapter(cursorAdapter);
}

If i added a new entry, by clicking on the button i want to refresh the listview but this only works with the populate function and not with the common adapter function notifyDataSetChanged();. Do i have a bug or is this the right way to refresh a listview?

Answer

Jack picture Jack · Nov 21, 2011

Have you seen this, tried the swap cursor method, or tried just simply calling setAdapter() again?

I had a similar issue where I could not get my list to update, and what I did was just create a refreshListView() method. Now you can call this initially from your onCreate(), AND anytime a user adds something to the DB. All it does is re-bind the listview to a cursor. With all the deprecating methods (requery()), and issues with notifyDataSetChanged(), I decided this was the easiest way.