2011-04-09

How CursorAdapter works

For people who are new to Android development, sometimes, they are wondering why CursorAdapter know when to refresh your UI and how the connection between your model and view is set?

I looked into the Android source code and learned that two key method calls will establish this connection. This following diagram was drawn in order to understand how your model (Database) and View (AdapterView) are bound together. From this diagram, we can see
  1. Cursor.setNotificationUri(ContentResolver, Uri)
  2. ContentResolver.notifyChange(...) 
The first call will insert an hash entry (Uri, Cursor) into the hash map hold by ContentResolver (ContentService) so that whenever the data pointed by this Uri object is changed, it will requery the Cursor object.

But the question is how ContentResolver knows your data is changed? It's your responsibility to tell it. In your implementation of ContentProvider or internal database, when you insert, delete, update the data successfully, you need to call ContentResolver.notifyChange(Uri, ...) to let ContentResolver know it should requery the hosted Cursor object keyed by the passed Uri.

As for the internal database, if it is SQLiteDatabase, I prefer using non-exported ContentProvider because its well-established interface.