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

前端 未结 3 496
隐瞒了意图╮
隐瞒了意图╮ 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:56

    I found the answer for my question. In general, CursorLoader doesn't automatically detect data changes and load them to view. We need to track URI for changes. This can be done by following steps:

    1. Registering an Observer in content resolver through cursor using: (Done in the query method of ContentProvider)
      cursor.setNotificationUri(getContext().getContentResolver(), uri);

    2. Now when there is any change in URI underlying data using insert()/delete()/update(), we notify the ContentResolver about the change using:

      getContext().getContentResolver().notifyChange(insertedId, null);

    3. This is received by the observer, we registered in step-1 and this calls to ContentResolver.query(), which inturn calls ContentProvider's query() method to return a fresh cursor to LoaderManager. LoaderManager calls onLoadFinished() passing this cursor, along with the CursorLoader where we update the View (using Adapter.swapCursor()) with fresh data.

    For Custom AsyncTaskLoaders:

    At times we need our custom loader instead of CursorLoader. Here we can use someother object other than cursor to point to the loaded data (like list etc). In this we won't be having previlige to notify ContentResolver through cursor. The application may also not have a content Provider, to track URI changes. In this scenario we use BroadcastReceiver or explicit ContentObserver to achieve automatic view updation. This is as follows:

    1. We need to define our custom loader which extends AsyncTaskLoader and implements all its abstract methods. Unlike CursorLoader, our Custom Loader may or may not use a content Provider and it's constructor may not call to ContentResolver.query(), when this loader is instatiated. So we use a broadcast receiver to serve the purpose.
    2. We need to instantiate a BroadCastReceiver or ContentObserver in OnStartLoading() method of abstract AsyncTaskLoader class.
    3. This BroadCast receiver should be defined to receive data-changing broadcasts from content provider or any system events(Like new app installed) and it has to call loader's onContentChanged() method, to notify the loader about the data change. Loader automatically does the rest to load the updated data and call onLoadFinished() to update the view.

    For more details refer this: http://developer.android.com/reference/android/content/AsyncTaskLoader.html

    I found this very useful for clear explanation : http://www.androiddesignpatterns.com/2012/08/implementing-loaders.html

提交回复
热议问题