Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ContentObserver and DatasetObserver?

What is difference between ContentObserver and 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?

like image 225
pixel Avatar asked Mar 25 '11 09:03

pixel


People also ask

What is ContentObserver?

ContentObserver is an abstract class with no abstract methods. Its two onChange() methods are implemented without any logic. And since these are called whenever a change occurs, you have to override them.

Which of the following receives callback for changes to content in Android?

Receives call backs for changes to content. Must be implemented by objects which are added to a ContentObservable .


2 Answers

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.

like image 170
ptc Avatar answered Sep 21 '22 11:09

ptc


I'm not sure if this question is still on anyone's radar. I have been struggling with the same question for a little while now. What I came up with as my litmus test for deciding whether to use a DataSet Observer or a ContentObserver is pretty straight-forward:

If I need to send a URI in my notification I use a ContentObserver. If I simply need to notify one object that another object has changed -- I use a DataSetObserver.

The delimiting factor, for me at least, is does the object that is sending out the notification expose it's underlying resources (be they objects, records, queries, or cursors) as "Universal Resource Identifiers" to the rest of the application; or does the object hide the source of its data.

like image 35
Charles Thomas Avatar answered Sep 20 '22 11:09

Charles Thomas