How do CursorLoader automatically updates the view even if the app is inactive?

前端 未结 3 495
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 21:27

I have been working on a small To-Do list app. I used CursorLoader to update the ToDolistview from a content provider. I have a written a function onNewItemAdded()

3条回答
  •  佛祖请我去吃肉
    2020-11-29 21:45

    get a reference to your loader while initializing as follows

     Loader dayWeatherLoader = getLoaderManager().initLoader(LOADER_DAY_WEATHER, null, this);
    

    then create a class that extends ContentObserver as follows

     class DataObserver extends ContentObserver {
    
        public DataObserver(Handler handler) {
            super(handler);
        }
    
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            dayWeatherLoader.forceLoad();
        }
    }
    

    Then register content observer inside onResume lifecycle method as follows

    @Override
    public void onResume() {
        super.onResume();
        getContext().getContentResolver().registerContentObserver(CONTENTPROVIDERURI,true,new DayWeatherDataObserver(new Handler()));
    }
    

    Whenever there is a change in the underlying data of content provider, the onChange method of contentobserver will be called where you can ask loader to load the data again

提交回复
热议问题