Nic Townsend
Nic Townsend

Reputation: 63

Android Cursor.registerContentObserver()

I am using a couple of listviews, each using a subclasses SimpleCursorAdapter to deal with results from a db. It's a simple diary viewer, activity 1 = day, activity 2 = week.

I am trying to delete an item in the day listview, and then have both the day and week views to refresh following the change.

If I call cursor.requery() in the activity I have deleted in, it reflects the change. However, the other activity doesn't know of the change.

I think I want to use Cursor.registerContentObserver as the docs claim "Register an observer that is called when changes happen to the content backing this cursor. Typically the data set won't change until requery() is called."

However, I naively wrote a content observer :

private class dbObserver extends ContentObserver {

    public dbObserver(Handler handler) {
        super(handler);
    }

    @Override
    public void onChange(boolean selfChange) {
        lectureCursor.requery();
        super.onChange(selfChange);
    }

}

Then in the onCreate of each activity :

dbObserver test = new dbObserver(new Handler());
    lectureCursor.registerContentObserver(test);

But onChange is never being called when I delete from the database. Am I doing something stupid here?

Upvotes: 4

Views: 7446

Answers (2)

inazaruk
inazaruk

Reputation: 74790

It turns out you need to call:

cursor.setNotificationUri(getContentResolver(), uri);

To make cursor notify your observer about changes.

Upvotes: 4

Noel
Noel

Reputation: 7410

I think the reason why it doesn't work is because you are attempting to call requery() from within the onChange() but onChange() is only after requery() is called.

You may want to consider using the ContentResolver's registerContentObserver(). This way onChange() will get called whenever there is a change on the db for that uri.

Upvotes: 3

Related Questions