cbr*_*lak 3 android android-contentprovider
Vogella 有一篇关于内容提供商的博客文章以及下面的代码片段(在底部):
cursor.setNotificationUri(getContext().getContentResolver(), uri);
我很好奇为什么人们想要通知侦听器有关查询操作的信息。
@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;
}
Run Code Online (Sandbox Code Playgroud)
如果我可以这么大胆的话,一个更简单的解释:
我假设OP想知道为什么查询想要通知侦听器。事实并非如此。它不会立即通知侦听器,它只是进行设置,以便在与游标关联的数据发生更改时触发侦听器。侦听器附加到当前 Context 的 ContentResolver;setNotificationUri 只是告诉听众“观看此 URI”的一种便捷方式。
在像CursorLoader这样的东西中,Loader会自动在其上下文中的ContentResolver上注册一个ContentObserver,然后Loader在执行查询时调用setNotificationUri。如果 Cursor 中的数据发生变化,ContentObserver 就会关闭,这会告诉 Loader 重置并执行新的查询。
| 归档时间: |
|
| 查看次数: |
2708 次 |
| 最近记录: |