Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 952
Siggy Petersen Avatar asked Nov 21 '11 14:11

Siggy Petersen


3 Answers

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.

like image 124
Jack Avatar answered Nov 19 '22 13:11

Jack


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);
like image 22
Pranita Patil Avatar answered Nov 19 '22 11:11

Pranita Patil


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

like image 1
maya Avatar answered Nov 19 '22 13:11

maya