Content Providers

Much of the time, an application's data is tightly bound to that application. For instance, a book reader application will typically have one datafile per book. Other applications on the mobile phone will have no interest in the files that the book reader uses to store books, so those files are tightly bound to the application, and there is no need to make any effort to share the book data. In fact, the Android OS enforces this tight binding so that applications can't read or write data across packages at all.

However, some applications want to share their data; that is, they want other applications to be able to read and write data within their database. Perhaps the most obvious example is contact data. If each application that required contacts forced the user to maintain a separate database for that specific application, the phone would be all but useless.

Android enables applications to share data using the content provider API. This API enables each client application to query the OS for data it's interested in, using a uniform resource identifier (URI) mechanism, similar to the way a browser requests information from the Internet.

The client does not know which application will provide the data; it simply presents the OS with a URI and leaves it to the OS to start the appropriate application to provide the result.

The content provider API enables full CRUD access to the content. This means the application can:

• Create new records

• Retrieve one, all, or a limited set of records

• Update records

• Delete records if permitted

This section shows how to use the content provider API by examining the inner workings of the NotePad application provided with the Android SDK. Assuming the SDK was installed in the /sdk directory, all file references within the NotePad project are relative to /sdk/samples/NotePad; thus, when the AndroidManifest.xml file is referenced in this section, the /sdk/samples/NotePad/AndroidManifest.xml file is assumed. By studying NotePad's implementation, you'll be able to create and manage content providers of your own.

Throughout this chapter we make the assumption that the backend of a content provider is a SQLite database. This will almost always be the case, and the API uses standard database operations, such as create, read, update, and delete. However, it is possible to use the API to store and retrieve data using any backend that will support the required operations. For instance, a flat file that just does inserts and queries that return some subset of the file is possible. However, in most cases an SQLite database will be on the backend of a content provider, so we use those terms and concepts in this chapter.

Was this article helpful?

0 0

Post a comment