Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SimpleCursorAdapter doesn't update when database changes

I have an Android ListActivity that is backed by a database Cursor through a SimpleCursorAdapter.

When the items are clicked, a flag field in the coresponding row in the database is toggled and the view in the list needs to be updated.

The problem is, when the view that's updated goes off screen and is recycled, the old value is displayed on the view when it returns into view. The same thing happens whenever thr list is redrawb (orientation changes, etc).

I use notifydatasetchanged() to refresh the cursor adapter but it seems ineffective.

How should I be updating the database so the cursor is updated as well?

like image 377
CodeFusionMobile Avatar asked Dec 31 '09 16:12

CodeFusionMobile


1 Answers

Call requery() on the Cursor when you change data in the database that you want reflected in that Cursor (or things the Cursor populates, like a ListView via a CursorAdapter).

A Cursor is akin to an ODBC client-side cursor -- it holds all of the data represented by the query result. Hence, just because you change the data in the database, the Cursor will not know about those changes unless you refresh it via requery().


UPDATE: This whole question and set of answers should be deleted due to old age, but that's apparently impossible. Anyone seeking Android answers should bear in mind that the Android is a swiftly-moving target, and answers from 2009 are typically worse than are newer answers.

The current solution is to obtain a fresh Cursor and use either changeCursor() or swapCursor() on the CursorAdapter to affect a data change.

like image 186
CommonsWare Avatar answered Sep 29 '22 03:09

CommonsWare