First of all I take no credit for this blog post. I was looking how to solve this problem and came across this post.
It took me some time to understand what Romain Guy meant. I thought that I would post back to the same thread, but the thread is old now and impossible to post to, so here it is:
Setup your adapter in onCreate() method of your ListActivity:
String[] from = new String[] { "one", "two" }; int[] to = new int[] { R.id.oneTextView, R.id.twoTextView }; SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.your_item_layout, null, from, to); this.setListAdapter(cursorAdapter);
And then in your fillData() method simply requery:
void fillData() { SimpleCursorAdapter cursorAdapter = (SimpleCursorAdapter) this.getListAdapter(); // get old cursor Cursor cursor = cursorAdapter.getCursor(); if (cursor != null) { // if cursor is there simply re-query cursor.requery(); } else { // need for new cursor cursor = getMeNewCursorMethodByYou(); this.startManagingCursor(cursor); cursorAdapter.changeCursor(cursor); } // make the "no items" text visible if (cursor.getCount() == 0) { ((TextView) this.findViewById(R.id.emptyText)) .setVisibility(TextView.VISIBLE); } }
If you really need to change the cursor, you need to stop managing the existing cursor first and close it and then assign new cursor:
void fillData() { SimpleCursorAdapter cursorAdapter = (SimpleCursorAdapter) this.getListAdapter(); // get old cursor Cursor cursor = cursorAdapter.getCursor(); if (cursor != null) { // stop managing this.stopManagingCursor(cursor); cursor.close(); } // need for new cursor cursor = getMeNewCursorMethodByYou(); this.startManagingCursor(cursor); cursorAdapter.changeCursor(cursor); // make the "no items" text visible if (cursor.getCount() == 0) { ((TextView) this.findViewById(R.id.emptyText)) .setVisibility(TextView.VISIBLE); } }
If you don't stop managing the cursor you will get errors in the lines of Activity trying to do something to closed cursor. If you don't close the cursor, well it will remain open for no reason.
All credit goes to Romain Guy.