ContentObserver not working in android

廉价感情. 提交于 2019-12-12 16:16:30

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/29198375/contentobserver-not-working-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!