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:
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;
Step 2: Implementing Callbacks
Next, modify the NotificationsListFragment class so that it now implements LoaderManager.LoaderCallbacks. The resulting NotificationsListFragment class will now have three new methods to override:
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
}
}
Step 3: Initializing the Loader
You need to make several changes to the onCreate() method of the NotificationsListFragment class. First, the Cursor will no longer be created here. Second, the loader must be initialized. And third, since the Cursor is no longer available immediately (as it will be loaded up in a separate thread instead), the initialization of the adapter must be modified. The changes to the onCreate() method are encapsulated here:
// 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.
Step 4: Creating the Loader
The loader is not automatically created. That's a job for the LoaderManager.LoaderCallbacks class. The CursorLoader we'll need to create and return from the onCreateLoader() method takes similar parameters to the managedQuery() method we used previously. Here is the entire implementation of the onCreateLoader() method:
@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...
Step 5: Using the Cursor
You might be wondering what happened to the Cursor object? When the system finishes retrieving the Cursor, a call to the onLoadFinished() method takes place. Handling this callback method is quite simple:
@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.
Step 6: Implementing the Reset Callback
The final callback method to implement is the onLoaderReset() method. This method is triggered when the loader is being reset and the loader data is no longer available. Our only use is within the adapter, so we'll simply clear the Cursor we were using with another call to the swapCursor() method:
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
Step 7: Testing the Results
At this point, you're finished transitioning the NotificationsListFragment to a loader-based implementation. When you run the application now, you'll probably notice that it basically behaves the same. So, how do you know this change is doing something? We leave this task as an exercise to the reader. How would you test the effectiveness of this solution?
HINT: It can be achieved with a single functional line of code that will require a try-catch block.
No comments:
Post a Comment