Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 309
Nic Townsend Avatar asked Sep 12 '25 07:09

Nic Townsend


1 Answers

It turns out you need to call:

cursor.setNotificationUri(getContentResolver(), uri);

To make cursor notify your observer about changes.

like image 76
inazaruk Avatar answered Sep 14 '25 22:09

inazaruk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!