3

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

Luciano Rodríguez
  • 2,239
  • 3
  • 19
  • 32
V I J E S H
  • 7,464
  • 10
  • 29
  • 37
  • 2
    Please explain what "is not working" means. Also, do you have the appropriate "notify" calls in `MyContentProvider`? – CommonsWare Mar 22 '15 at 18:49
  • the onchange method is not called here. Sorry I am not aware about the notify calls in contentprovider. Do we really required it? – V I J E S H Mar 23 '15 at 05:40

2 Answers2

10

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Can I user ContentObserver as an alternative of FileObserver as FileObserver is not working in Android 11 and above. Any small example would be appreciated. I want to listen for any files added in selected or subdirectory. – Smeet Jun 09 '21 at 09:24
  • Ok no worries, thank you for your response. Will keep you posted once I try. – Smeet Jun 10 '21 at 09:32
9

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.

Community
  • 1
  • 1
Eric
  • 16,397
  • 8
  • 68
  • 76