Very Simple Example of a Loader and LoaderManager in Android

Very simple example of a Loader and LoaderManager in Android

Loaders in Android are great, they allow you to asynchronously load data to be used in Adapters. I have found CursorLoaders very useful for getting data from a database to the UI in a way that minimizes blocking calls on the UI thread.

Alex Lockwood has posted a great, and detailed four part discussion of the Loader pattern on his blog. If you don’t know much about Loaders, or the LoaderManager, or why you might want to use them, go read that series. This is the nickle tour. My goal here is to show you just what you need to get you up and running with this.

Loaders are simple

All you really need to do is move your query into the loadInBackground method, and the rest is boilerplate.

public class DumbLoader extends CursorLoader {
private static final String TAG = "DumbLoader";
public DumbLoader(Context context) {
super(context);
}
@Override
public Cursor loadInBackground() {
// this is just a simple query, could be anything that gets a cursor
return DummyData.getItems();
}
}
view raw DumbLoader.java hosted with ❤ by GitHub

Something to call back to

You’ll need to put the LoaderCallbacks somewhere, you can put it where you like, in an Activity or Fragment, or in a separate class. They just need to go somewhere.

@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new DumbLoader(this);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
// mAdapter is a CursorAdapter
mAdapter.swapCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mAdapter.swapCursor(null);
}

Call it!

Now that you’ve got the Loader and the LoaderCallbacks defined, you can call it, and start benefiting from painless asynchronous loading of your data.

public class MainActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {
CursorAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
// omitted for brevity ...
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
}
}
view raw initialize.java hosted with ❤ by GitHub

Sample

I added a Loader to the same sample project that I blogged about in my previous post. Here’s the source.