androidandroid-contentprovidercontentobserver

In what circumstances is uri passed to Android's ContentObserver.onChange() callback?


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.


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.