Monday, 17 October 2016

Android - Proper way to load data asynchronously from Content Providers


Whenever we have to access data from Content Providers, generally everyone tends to use ContentResolvers and query the appropriate content providers using its URI and get the results. This is how android shows examples of using the COntentResolver as well. However there is a general problem that I have observed across different development teams that people tend to copy android's examples or code from stackoverflow and in doing so, forget a very important thing - ContentResolver runs in the app's main thread! (also called as the UI thread). 
The UI thread is a bad place for lengthy operations like loading data. You never know how long data will take to load, especially if that data is sourced from a content provider or the network. Android 3.0 (Honeycomb) introduced the concept of Loaders and, in particular, the CursorLoader class that offloads the work of loading data on a thread, and keeps the data persistent during short term activity refresh events, such as an orientation change. 

Step 1: Using the Right Class Versions
Normally, we can get away with just using the default import statements of Android Studio. However, for loaders to work, we must ensure that we are using the correct versions of the classes. Here are the relevant import statements:
import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v4.widget.SimpleCursorAdapter;

public class NotificationsListFragment extends ListFragment implements         LoaderManager.LoaderCallbacks<Cursor> { // ... existing code // LoaderManager.LoaderCallbacks<Cursor> methods:     @Override     public Loader<Cursor> onCreateLoader(int id, Bundle args) {         // TBD     }     @Override     public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {         // TBD     }     @Override     public void onLoaderReset(Loader<Cursor> loader) {         // TBD     } }

// NotificationsListFragment class member variables private static final int NOTIFICATIONS_LIST_LOADER = 0; private SimpleCursorAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     String[] uiBindFrom = { TutListDatabase.COL_TITLE };     int[] uiBindTo = { R.id.title };     getLoaderManager().initLoader(NOTIFICATIONS_LIST_LOADER, null, this);     adapter = new SimpleCursorAdapter(             getActivity().getApplicationContext(), R.layout.list_item,             null, uiBindFrom, uiBindTo,             CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);     setListAdapter(adapter); }

As you can see, we've made the three changes. The Cursor object and the resulting query() call have been removed. In it’s place, we call the initLoader() method of the LoaderManager class. Although this method returns the loader object, there is no need for us to keep it around. Instead, the LoaderManager takes care of the details for us. All loaders are uniquely identified so the system knows if one must be newly created or not. We use the NOTIFICATIONS_LIST_LOADER constant to identify the single loader now in use. Finally, we changed the adapter to a class member variable and no cursor is passed to it yet by using a null value.
@Override public Loader<Cursor> onCreateLoader(int id, Bundle args) {     String[] projection = { NotificationsListDatabase.ID, NotificationsListDatabase.COL_TITLE };     CursorLoader cursorLoader = new CursorLoader(getActivity(),             NotificationsListProvider.CONTENT_URI, projection, null, null, null);     return cursorLoader; }
As you can see, it's fairly straightforward and really does look like the call to managedQuery(), but instead of a Cursor, we get a CursorLoader. And speaking of Cursors...
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {     adapter.swapCursor(cursor); }
The new swapCursor() method, introduced in API Level 11 and provided in the compatibility package, assigns the new Cursor but does not close the previous one. This allows the system to keep track of the Cursor and manage it for us, optimizing where appropriate.

@Override public void onLoaderReset(Loader<Cursor> loader) {     adapter.swapCursor(null); }
HINT: It can be achieved with a single functional line of code that will require a try-catch block.

No comments:

Post a Comment