Search code examples
javaandroidandroid-contentproviderandroid-listfragmentloader

Android Loader used with SimpleCursorAdapter and ContentProvider not updating


I have a list fragment which loads data from a ContentProvider using a Loader and SimpleCursorAdapter. I think that I have followed correctly the directions given by google examples, but my ListView is not updated when underlying data changes. This is what I'm doing:

ContentProvider

@Override
public synchronized Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    ...
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}

ListFragment

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    String[] dbColumns = new String[] { CheckpointsView.COL_TYPE, CheckpointsView.COL_DESCRIPTION };
    int[] listColumnIds = new int[] { R.id.lci_img_icon, R.id.lci_txt_description };
    adapter = new SimpleCursorAdapter(getActivity(), R.layout.listview_checkpoints_item, null, dbColumns, listColumnIds, 0);
    ...
    setListAdapter(adapter);
    getLoaderManager().initLoader(0, null, this);
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    CursorLoader cursorLoader = new CursorLoader(
        getActivity(),
        CheckpointsView.CONTENT_URI,
        CheckpointsView.LOADER_PROJECTION,
        whereClause,
        null,
        null
    );
    return cursorLoader;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    adapter.swapCursor(data);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    adapter.swapCursor(null);
}

At some point of the code that I know that data was just added, I trie calling adapter.notifyDataSetChanged();, but it didn't work either.

The only way to make the list refresh is either by exiting the activity and relaunching it, or by recreating the loader manually by writing

getLoaderManager().destroyLoader(0);
getLoaderManager().initLoader(0, null, GreenScanFragment.this);

Am I missing something?


Solution

  • I am stupid! After spending so much time, I had to post a question in order to find the answer myself. The problem is solved if I call context.getContentResolver().notifyChange(CheckpointsView.CONTENT_URI, null, false); where I am updating the data.