Reputation: 15639
Vogella has this blog post about content providers and the snippet below (at the bottom) with this line:
cursor.setNotificationUri(getContext().getContentResolver(), uri);
I'm curious as to why one would want to notify listeners about a query operation.
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
// Using SQLiteQueryBuilder instead of query() method
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
// Check if the caller has requested a column which does not exists
checkColumns(projection);
// Set the table
queryBuilder.setTables(TodoTable.TABLE_TODO);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case TODOS:
break;
case TODO_ID:
// Adding the ID to the original query
queryBuilder.appendWhere(TodoTable.COLUMN_ID + "=" + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
SQLiteDatabase db = database.getWritableDatabase();
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
// Make sure that potential listeners are getting notified
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
Upvotes: 3
Views: 2724
Reputation: 8641
If I may be so bold, a more straightforward explanation:
I assume that the OP is wondering why a query wants to notify listeners. It doesn't. It's not immediately notifying listeners, it's just setting up so that listeners will be fired if the data associated with the Cursor changes. Listeners are attached to the ContentResolver for the current Context; setNotificationUri is just a handy way of telling those listeners "Watch this URI."
In something like CursorLoader, the Loader automatically registers a ContentObserver on the ContentResolver in its context, and then the Loader calls setNotificationUri when it does a query. If the data in the Cursor changes, the ContentObserver goes off, which tells the Loader to reset and do a new query.
Upvotes: 5
Reputation: 54702
It tells the cursor what uri to watch, so it knows when its source data changes. When any data is modified, the ContentProvider
notifies ContentResolver
about the changes then the ContentResolver
notifies all registered observers. Then if you have any CursorLoaders
which have registered the observer, can load the new data by this
Upvotes: 0