简体   繁体   中英

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 pulled 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); 
        } 
    }); 
} 

您是否尝试过从ListActivity的onResume()方法中调用SimpleCursorAdapter上的notifyDataSetChanged()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM