之间是什么 ContentObserver
区别和 DatasetObserver
?
在一个或另一个应该使用?
When one or another should be used?
我得到光标
单排。我想收到有关数据的变化 - 例如。当行被更新。
I get Cursor
with single row. I want to be notified about data changes - eg. when row is updated.
我要注册哪一个观察者类?
Which observer class should I register?
如果您使用的是的ContentProvider
(通过 ContentResolver的
或 Activity.managedQuery()
),让您的数据,只需连接一个 ContentObserver
您光标
。在code。在的onChange()
将被称为每当 ContentResolver的
广播通知的乌里
与光标相关。
If you are using a ContentProvider
(via ContentResolver
or Activity.managedQuery()
) to get your data, simply attach a ContentObserver
to your Cursor
. The code in onChange()
will be called whenever the ContentResolver
broadcasts a notification for the Uri
associated with your cursor.
Cursor myCursor = managedQuery(myUri, projection, where, whereArgs, sortBy);
myCursor.registerContentObserver(new ContentObserver() {
@Override
public void onChange(boolean selfChange) {
// This cursor's Uri has been notified of a change
// Call cursor.requery() or run managedQuery() again
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
}
请确保您的的ContentProvider
是一个好公民,并注册了乌里
与查询之后光标:
Make sure your ContentProvider
is a "good citizen" and registers the Uri
with the cursor after a query:
cursor.setNotificationUri(getContentResolver(), uri);
这也应该通知 ContentResolver的
的底层数据(你的SQLite数据库,例如,插入过程中,删除和更新操作)的任何变化:
It should also notify the ContentResolver
of any changes to the underlying data (for instance, during insert, delete, and update operations on your SQLite database):
getContentResolver().notifyChange(uri, null);
此方法是面向对象设计的观察者模式的一个很好的例子。
This approach is a good example of the Observer Pattern of object-oriented design.