Siggy Petersen
Siggy Petersen

Reputation: 205

Android ListView update with SimpleCursorAdapter

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?

Upvotes: 5

Views: 11676

Answers (3)

maya
maya

Reputation: 11

You need to call swapcursor() before notifyDataSetChanged() on the adapter.

Upvotes: 1

Pranita Patil
Pranita Patil

Reputation: 821

Please refer this link...it works like charm

Update SimpleCursorAdapter while maintaining scroll position in ListView

for dynamic listview on scroll i added new item from database .. I did mistake here .. i was assigning new adapter for each time for same simplecursoradapter . Instead of creating new adapter. just use

adapter.changecursor(newcursorValue);
adapter.notifydatasetChanged();
 lsMedicine1.setSelectionFromTop(lsMedicine1.getLastVisiblePosition()-20, 0);

Upvotes: 3

Jack
Jack

Reputation: 9242

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.

Upvotes: 9

Related Questions