V I J E S H
V I J E S H

Reputation: 7594

ContentObserver not working in android

Hi I am trying with the below code.The content resolver is not working with this.Can anyone give an idea

getContentResolver().registerContentObserver(MyContentProvider.CONTENT_URI,true, new ContentObserver(new Handler()){

    @Override public void onChange(    boolean selfChange){

        showDialog();
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {

        // Handle change.
        showDialog();
    }
});

Thanks in advance

Upvotes: 3

Views: 8358

Answers (2)

Eric
Eric

Reputation: 17536

Problem

The problem I experienced was that the ContentObserver.onChange() method never got called because the ContentObserver's Handler's Looper was initialized improperly. I forgot to call Looper.loop() after calling Looper.prepare()...this lead to the Looper not consuming events and invoking ContentObserver.onChange().

Solution

The solution is to properly create and initialize a Handler and Looper for the ContentObserver:

// creates and starts a new thread set up as a looper
HandlerThread thread = new HandlerThread("MyHandlerThread");
thread.start();

// creates the handler using the passed looper
Handler handler = new Handler(thread.getLooper());

// creates the content observer which handles onChange on a worker thread
ContentObserver observer = new MyContentObserver(handler);

useful SO post about controlling which thread ContentObserver.onChange() is executed on.

Upvotes: 9

CommonsWare
CommonsWare

Reputation: 1006614

A ContentObserver only works with a ContentProvider that calls one of the notifyChange() methods on a ContentResolver when the contents of the provider change. If the ContentProvider does not call notifyChange(), the ContentObserver will not be notified about changes.

Upvotes: 10

Related Questions