Understanding Content Providers

Android allows you to expose your data sources (or data providers) through a representational state transfer-like (REST-like) abstraction called a content provider. A SQLite database on an Android device is an example of a data source that you can encapsulate into a content provider. To retrieve data from a content provider or save data into a content provider, you will need to use a set of REST-like URIs. For example, if you were to retrieve a set of books from a content provider that is an encapsulation of a book database, you will need to use a URI like this:

content://com.android.book.BookProvider/books

To retrieve a specific book from the book database (book 23), you will need to use a URI like this:

content://com.android.book.BookProvider/books/23

You will see in this section how these URIs translate to underlying database-access mechanisms. Any application on the device can make use of these URIs to access and manipulate data. As a consequence, content providers play a significant role in sharing data between applications.

Strictly speaking, though, the content providers' responsibilities comprise more of an encapsulation mechanism than a data-access mechanism. You'll need an actual data-access mechanism such as SQLite or network access to get to the underlying data sources. So, content-provider abstraction is required only if you want to share data externally or between applications. For internal data access, an application can use any data storage/access mechanism that it deems suitable, such as the following:

• Preferences: A set of key/value pairs that you can persist to store application preferences

• Files: Files internal to applications, which you can store on a removable storage medium

• SQLite: SQLite databases, each of which is private to the package that creates that database

• Network: A mechanism that lets you retrieve or store data externally through the Internet

Note Despite the number of data-access mechanisms allowed in Android, this chapter focuses on SQLite and the content-provider abstraction because content providers form the basis of data sharing, which is much more common in the Android framework compared to other UI frameworks. We'll cover the network approach in Chapter 8 and the preferences mechanism in Chapter 11.

As we go through this section, we will show you the content providers that come with Android and how to explore them. We will discuss in detail the structure of content URIs and how these URIs are linked with MIME types. After covering these content-provider concepts in detail, we will show you how to build a content provider from scratch that encapsulates a simple book database.

0 0

Post a comment