Content Providers
- Introduction
- Content providers store and retrieve data, and make data accessible to all applications.
- Content providers are a way to share data across applications.
- The storage of data in a content provider is hidden, and access is through a common
interface.
- See some details in the
Android pages.
- Android ships with a number of content providers for common data types (audio, video,
images, personal contact information, etc.).
- The Media Store is an example.
- To get some content into the media store, upload and cold boot to make the media
scanner.
- Querying a Content Provider
- Content is accessed using a ContentResolver
- A URI is used to identify the data to be accessed
- The data is presented as a relational database table
- The fields of the table are known for each content provider, and all have an
_ID field that serves as the primary key.
- Four pieces of information are needed to query a content provider
- The URI for the data
- The names of the fields you need (projection)
- Specification of which rows you need (selection)
- Sort order for the results
- The data is provided via a Cursor, which allows you to step through the records
of the data.
You must use moveToFirst (or somewhere) to place the cursor before accessing
the data.
You can move to a specific position (indexed from 0) using moveToPosition().
- To run a query in the background, use a CursorLoader, which allows interaction
to continue while the data is retrieved.
- A common use of a cursor is to provide the data for an adapter, e.g., a
SimpleCursorAdapter.
- If the content is on the SD card, you need to add permission to read it in the manifest,
with android.permission.READ_EXTERNAL_STORAGE, and also from the user.
- Example: Audio
MainActivity.java
activity_main.xml
strings.xml
AndroidManifest.xml
- Example: Images
MainActivity.java
activity_main.xml
strings.xml
AndroidManifest.xml
- Modifying data in a Content Provider
- Creating a Content Provider