Question

The onChange() method of Android's ContentObserver class says, "Includes the changed content Uri when available." In what circumstances is the URI available? In what circumstances is it not available?

The uri parameter was added in API level 16 (Android 4.1) and so I would expect it to be set in Android 4.1 and newer. However I'm seeing a case on Android 4.3 where uri is not set.

Method 1: Works

MyContentObserver.onChange() is called and is passed a valid uri:

contentResolver.registerContentObserver(myUri, true, new MyContentObserver());

Method 2: Doesn't work--why not?

MyContentObserver.onChange() is called but the uri parameter is null:

contentResolver.query();
cursor.registerContentObserver(new MyContentObserver);

Is this expected? Is one of these preferred over the other? I've tested this using "content://com.google.android.gm/me@example.com/labels" and using my own custom ContentProvider.

Was it helpful?

Solution

This is an old question, but still unanswered. So I will add my answer in case people is still curious about it.

When your content provider notifies the registered observer using getContext().getContentResolver().notifyChange(URI, "your_uri");, it asks the ContentResponder for it. The return value from that method is the ContentObserver that you registered with the registerContentObserver() method of the content responder, which is what you did in the first case. However, in the second case, you registered the observer in the Cursor using the registerContentObserver() method of the Cursor, so the ContentResponder doesn't know about it.

OTHER TIPS

If you are setting ContentObserver upon common tables(e.g people, mediaprovider etc) then unfortunately you might not receive any Uri as an argument, it might be blank as it depends upon underneath content provider implementation. To receive an valid Uri upon change, respective ContentProvider has to be modified to notify change along with URI.

e.g getContext().getContentResolver().notifyChange(Uri, "your_uri"); // this notifies all the registered ContentObserver with Uri of modified concerned dataset.

If you are writing your own ContentProvider then use above mentioned line whenever you perform update, delete or insert operation on your database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top