page.title=Setting Up the Loader trainingnavtop=true startpage=true @jd:body

This lesson teaches you to

  1. Extend an Activity
  2. Retrieve a LoaderManager
  3. Initialize the Loader Framework

You create a {@link android.support.v4.content.CursorLoader} within a loader framework. To set up the framework, you implement the {@link android.support.v4.app.LoaderManager.LoaderCallbacks LoaderCallbacks<Cursor>} as part of an {@link android.app.Activity}. In addition, to provide compatibility compatible with platform versions starting with Android 1.6, you must extend the {@link android.app.Activity} with the {@link android.support.v4.app.FragmentActivity} class.

Note: A {@link android.support.v4.app.Fragment} is not a prerequisite for {@link android.support.v4.content.CursorLoader}. As a convenience, the support library class {@link android.support.v4.app.FragmentActivity} contains the fragment and the loader frameworks, but they are completely independent of each other.

Before you can use the loader framework, you need to initialize it. To do this, retrieve a {@link android.support.v4.app.LoaderManager} object and call its {@link android.support.v4.app.LoaderManager#initLoader initLoader()} method.

If you do use one or more {@link android.support.v4.app.Fragment} objects in an {@link android.app.Activity}, the {@link android.support.v4.app.LoaderManager} you retrieve is available to all of them.

Extend an Activity

To set up an {@link android.app.Activity} subclass to contain a {@link android.support.v4.content.CursorLoader}, extend the subclass with must extend {@link android.support.v4.app.FragmentActivity}, which provides the loader framework, and implement the {@link android.support.v4.app.LoaderManager.LoaderCallbacks LoaderCallbacks<Cursor>} interface, which specifies method signatures that the loader framework uses to interact with the {@link android.app.Activity}.

For example:

public class DisplayActivity extends FragmentActivity
        implements LoaderManager.LoaderCallbacks<Cursor>

Retrieve a LoaderManager

To get an instance {@link android.support.v4.app.LoaderManager} for use in your {@link android.app.Activity}, call {@link android.support.v4.app.FragmentActivity#getSupportLoaderManager FragmentActivity.getSupportLoaderManager()} at the beginning of the {@link android.app.Activity#onCreate onCreate()} method. For example:

private LoaderManager mLoaderManager;
public void onCreate() {
...
mLoaderManager = this.getSupportLoaderManager();

Initialize the Loader Framework

Once you have the {@link android.support.v4.app.LoaderManager} object, initialize it by calling {@link android.support.v4.app.LoaderManager#initLoader initLoader()}. For example:

// CursorLoader instance identifier
public static final int URL_LOADER = 0;
...
// Initializes the CursorLoader
getSupportLoaderManager().initLoader(URL_LOADER, null, this);