page.title=Loading Data in the Background page.tags=cursorloader trainingnavtop=true startpage=true @jd:body

Dependencies and prerequisites

You should also read

Try it out

Download the sample

ThreadSample.zip

Querying a {@link android.content.ContentProvider} for data you want to display takes time. If you run the query directly from an {@link android.app.Activity}, it may get blocked and cause the system to issue an "Application Not Responding" message. Even if it doesn't, users will see an annoying delay in the UI. To avoid these problems, you should initiate a query on a separate thread, wait for it to finish, and then display the results.

You can do this in a straightforward way by using an object that runs a query asynchronously in the background and reconnects to your {@link android.app.Activity} when it's finished. This object is a {@link android.support.v4.content.CursorLoader}. Besides doing the initial background query, a {@link android.support.v4.content.CursorLoader} automatically re-runs the query when data associated with the query changes.

This class describes how to use a {@link android.support.v4.content.CursorLoader} to run a background query. Examples in this class use the v4 Support Library versions of classes, which support platforms starting with Android 1.6.

Lessons

Running a Query with a CursorLoader
Learn how to run a query in the background, using a {@link android.support.v4.content.CursorLoader}.
Handling the Results
Learn how to handle the {@link android.database.Cursor} returned from the query, and how to remove references to the current {@link android.database.Cursor} when the loader framework re-sets the {@link android.support.v4.content.CursorLoader}.