Loading Data in the Background

Dependencies and prerequisites

  • Android 1.6 or later

You should also read

Try it out

Download the sample

ThreadSample.zip

Querying a ContentProvider for data you want to display takes time. If you run the query directly from an 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 Activity when it's finished. This object is a CursorLoader. Besides doing the initial background query, a CursorLoader automatically re-runs the query when data associated with the query changes.

This class describes how to use a 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 CursorLoader.
Handling the Results
Learn how to handle the Cursor returned from the query, and how to remove references to the current Cursor when the loader framework re-sets the CursorLoader.