Advertisement
  1. Code
  2. Mobile Development
  3. Android Development

Android Fundamentals: Properly Loading Data

Scroll to top
This post is part of a series called Android Fundamentals.
Android Fundamentals: Working With Content Providers
Android Fundamentals: Downloading Data With Services

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. We'll incorporate the Loader as a new feature in our ongoing tutorial series building a yet-to-be-named tutorial reader application.

If you were paying close attention to our last tutorial, Android Fundamentals: Working With Content Providers, you may have noticed that we took a shortcut. We used the managedQuery() method of the Activity class, which is a newly deprecated method. This method represents the "old" way of letting an activity manage a cursor. Now we'll switch it to the new way, using a CursorLoader, as suggested in the latest SDK documentation. We can do this safely because although the CursorLoader class was included in Android 3.0, it is also part of the new compatibility library we discussed in Android Compatibility: Working with Fragments, and therefore can be used on devices as far back as Android 1.6.

Step 0: Getting Started

This tutorial assumes you will start where our tutorial called Android Fundamentals: Working With Content Providers left off. You can download that code and work from there, though you will have some tasks you'll have to do unassisted, or you can simply download the code for this tutorial and follow along. The choice is yours.

Step 1: Using the Right Class Versions

Normally, we can get away with just using the default import statement that Eclipse gives us. However, for loaders to work, we must ensure that we are using the correct versions of the classes. Here are the relevant import statements:

1
2
import android.support.v4.app.ListFragment;
3
import android.support.v4.app.LoaderManager;
4
import android.support.v4.content.CursorLoader;
5
import android.support.v4.content.Loader;
6
import android.support.v4.widget.CursorAdapter;
7
import android.support.v4.widget.SimpleCursorAdapter;

These imports replace the existing CursorAdapter import statements found in previous tutorial’s TutListFragmet class. This is the only class we'll need to modify. We don't normally talk about import statements, but when building this sample, Eclipse kept referencing the wrong CursorLoader package and we had to make the change manually, so we're calling it out here in our first step.

Step 2: Implementing Callbacks

Next, modify the TutListFragment class so that it now implements LoaderManager.LoaderCallbacks. The resulting TutListFragment class will now have three new methods to override:

1
2
public class TutListFragment extends ListFragment implements
3
        LoaderManager.LoaderCallbacks<Cursor> {
4
// ... existing code

5
// LoaderManager.LoaderCallbacks<Cursor> methods:

6
7
    @Override
8
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
9
        // TBD

10
    }
11
12
    @Override
13
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
14
        // TBD

15
    }
16
17
    @Override
18
    public void onLoaderReset(Loader<Cursor> loader) {
19
        // TBD

20
    }
21
}

Step 3: Initializing the Loader

You need to make several changes to the onCreate() method of the TutListFragment 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:

1
2
// TutListFragment class member variables

3
private static final int TUTORIAL_LIST_LOADER = 0x01;
4
5
private SimpleCursorAdapter adapter;
6
7
@Override
8
public void onCreate(Bundle savedInstanceState) {
9
    super.onCreate(savedInstanceState);
10
11
    String[] uiBindFrom = { TutListDatabase.COL_TITLE };
12
    int[] uiBindTo = { R.id.title };
13
14
    getLoaderManager().initLoader(TUTORIAL_LIST_LOADER, null, this);
15
16
    adapter = new SimpleCursorAdapter(
17
            getActivity().getApplicationContext(), R.layout.list_item,
18
            null, uiBindFrom, uiBindTo,
19
            CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
20
21
    setListAdapter(adapter);
22
}

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 TUTORIAL_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:

1
2
@Override
3
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
4
    String[] projection = { TutListDatabase.ID, TutListDatabase.COL_TITLE };
5
6
    CursorLoader cursorLoader = new CursorLoader(getActivity(),
7
            TutListProvider.CONTENT_URI, projection, null, null, null);
8
    return cursorLoader;
9
}

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:

1
2
@Override
3
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
4
    adapter.swapCursor(cursor);
5
}

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:

1
2
@Override
3
public void onLoaderReset(Loader<Cursor> loader) {
4
    adapter.swapCursor(null);
5
}

Step 7: Testing the Results

At this point, you're finished transitioning the TutListFragment 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.

Conclusion

By moving the loading of data off the main UI thread of the application and into a CursorLoader, you've improved the responsiveness of the application, especially during orientation changes. If the content provider took 10 seconds per query, the user interface would not be negatively affected whereas in its previous implementation, it would have likely caused the dreaded "Force Close" dialog to appear.

About the Authors

Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams Teach Yourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.