Android: Cursor requery when replacing entire database
I have a ListActivity
which uses a SimpleCursorAdapter
to display database content. I am having problems getting the view refreshed when the underlying database changes.
As an experiment, I've added a call to Cursor.requery()
in the activity's onResume()
, for debugging, so all I have to do is flip to a different activity and back and it should force a refresh. I've also overridden onContentChanged()
, for debugging. It transpires that requery()
is being called, but this is not resulting in a call to onContentChanged()
.
I suspect the cursor is using stale cached data. The operation which prompts the change actually involves wiping and replacing the whole database. Rather than simply requerying, I think I need to throw away the cursor and rebuild it from scratch.
I have tried closing and reopening the underlying database, in conjunction with Cursor.requery()
, but the cursor doesn't seem to like having the db p开发者_高级运维ulled from under its feet like this. (The list ends up empty.)
Edit: I've also tried calling adapter.notifyDataSetChanged()
alongside the requery()
in onResume()
, but it makes no difference.
Any advice?
Solved by discarding the cursor, closing and reopening the database, and then recreating the cursor. I use an Observer to inform the activity of the database change, as follows:
@Override
public void update(Observable observable, Object data) {
// database changed
runOnUiThread(new Runnable() {
@Override
public void run() {
stopManagingCursor(cursor);
dbAdapter.close();
dbAdapter.open();
cursor = getAccounts();
startManagingCursor(cursor);
adapter.changeCursor(cursor);
}
});
}
Have you tried calling notifyDataSetChanged() on your SimpleCursorAdapter from within your ListActivity's onResume() method?
精彩评论