ContentObserver和DatasetObserver之间的区别? [英] Difference between ContentObserver and DatasetObserver?

查看:263
本文介绍了ContentObserver和DatasetObserver之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之间是什么 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.

这篇关于ContentObserver和DatasetObserver之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆