Question

I am trying to use the following approach:

protected void onCreate(Bundle savedInstanceState) {
    ...
    recordsCursor = dbHelper.fetchRecords1();
    startManagingCursor(recordsCursor);
    String[] from = new String[]{DbAdapter.KEY_BL_SENDER, DbAdapter.KEY_BL_READ};
    int[] to = new int[]{R.id.text1, R.id.background};   
    adapter = new SimpleCursorAdapter(this, R.layout.row, recordsCursor, from, to);
    setListAdapter(adapter);
}

public boolean onOptionsItemSelected(MenuItem item) {
...
case R.id.list1:
    recordsCursor = dbHelper.fetchRecords1();
    String[] fromBL = new String[]{DbAdapter.KEY_BL_SENDER, DbAdapter.KEY_BL_READ};
    int[] toBL = new int[]{R.id.text1, R.id.background};   
    Log.i(TAG, "count: "+recordsCursor.getCount()); // returns 475
    adapter = new SimpleCursorAdapter(this, R.layout.row, recordsCursor, fromBL, toBL);
    adapter.changeCursor(recordsCursor);
    adapter.notifyDataSetChanged();
    return true;

case R.id.list2:
    recordsCursor = dbHelper.fetchRecords2();
    String[] from = new String[]{DbAdapter.KEY_W_SENDER};
    int[] to = new int[]{R.id.text1};
    Log.i(TAG, "count: "+recordsCursor.getCount()); // returns 0
    adapter = new SimpleCursorAdapter(this, R.layout.row, recordsCursor, from, to);
    adapter.changeCursor(recordsCursor);
    adapter.notifyDataSetChanged();
    return true;

But it doesn't update the list. Once records from fetchRecords1 are shown, they are not replaced with records from another table. What is wrong in my code?

Was it helpful?

Solution

The quickest change is to take out these lines in your switch:

adapter.changeCursor(recordsCursor);
adapter.notifyDataSetChanged();

and replace them with:

setListAdapter(adapter);

When you set the adapter to a new SimpleCursorAdapter, that doesn't propagate back to the ListView. The ListView still has a reference to the original adapter that was set with setListAdapter, while your new adapter isn't connected to any ListView.

The more elegant change would be to call changeCursorAndColumns:

case R.id.list2:
    recordsCursor = dbHelper.fetchRecords2();
    String[] from = new String[]{DbAdapter.KEY_W_SENDER};
    int[] to = new int[]{R.id.text1};
    Log.i(TAG, "count: "+recordsCursor.getCount()); // returns 0
    adapter.changeCursorAndColumns(recordsCursor, from, to);
    adapter.notifyDataSetChanged();
    return true;

Note also that the constructor you're using has been deprecated since API 11:

This constructor was deprecated in API level 11.
This option is discouraged, as it results in Cursor queries being performed on the application's UI thread and thus can cause poor responsiveness or even Application Not Responding errors. As an alternative, use LoaderManager with a CursorLoader.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top