page.title=Defining and Launching the Query trainingnavtop=true startpage=true @jd:body
To perform a query, create the {@link android.support.v4.content.CursorLoader}, set up its query, and pass it to the loader framework. From then on, the framework manages everything. It runs the query on a background thread, returns the results to the foreground, and watches for changes to the data associated with the query.
Pass a {@link android.support.v4.content.CursorLoader} to the loader framework in your implementation of {@link android.support.v4.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()}. The loader framework calls this method when you create a loader by calling {@link android.support.v4.app.LoaderManager#initLoader initLoader()}. You can create a {@link android.support.v4.content.CursorLoader} anywhere, but the preferred way is to create it in {@link android.support.v4.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()}, because this defers creation until the object is actually needed.
Notice that {@link android.support.v4.app.LoaderManager#initLoader initLoader()} will only
{@link android.support.v4.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()}
if the {@link android.support.v4.content.CursorLoader} doesn't already exist; otherwise, it
re-uses the existing {@link android.support.v4.content.CursorLoader}. The loader framework
tracks {@link android.support.v4.content.CursorLoader} instance using the id
value passed to {@link android.support.v4.app.LoaderManager#initLoader initLoader()}.
To create a {@link android.support.v4.content.CursorLoader} and define its
query at the same time, call the constructor
{@link android.support.v4.content.CursorLoader#CursorLoader(Context, Uri, String[], String, String[], String)
CursorLoader(context, uri, projection, selection, selectionArgs, sortOrder)}. The
context
and uri
arguments are required, but the others are optional.
To use the default value for an optional argument, pass in null
. The
{@link android.support.v4.content.CursorLoader} runs the query against the
{@link android.content.ContentProvider} identified by uri
, just as if you had
called {@link android.content.ContentResolver#query ContentResolver.query()} with the same
arguments.
For example:
public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle) { /* * Takes action based on the ID of the Loader that's being created */ switch (loaderID) { case URL_LOADER: /* * Return a new CursorLoader */ return new CursorLoader( this, // Context DataProviderContract.IMAGE_URI, // Provider's content URI PROJECTION, // Columns to return null, // Return all rows null, // No search arguments null); // Default search order default: // An invalid id was passed in return null; } }