Difference between ContentObserver and DatasetObserver?

前端 未结 4 2051
你的背包
你的背包 2021-01-30 11:15

What is difference between ContentObserver and DatasetObserver?

When one or another should be used?

I get Cursor with sing

4条回答
  •  一个人的身影
    2021-01-30 11:49

    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;
        }
    }
    

    Make sure your ContentProvider is a "good citizen" and registers the Uri with the cursor after a query:

    cursor.setNotificationUri(getContentResolver(), uri);
    

    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.

提交回复
热议问题