14.01.2013 Views

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6: Data Storage, Retrieval, and Sharing<br />

Introducing Content Resolvers<br />

190<br />

Each application Context has a single ContentResolver, accessible using the getContentResolver<br />

method, as shown in the following code snippet:<br />

ContentResolver cr = getContentResolver();<br />

Content Resolver includes several methods to transact and query Content Providers. You specify the<br />

provider to interact using a URI.<br />

A Content Provider’s URI is defi ned by its authority as defi ned in its application manifest node. An<br />

authority URI is an arbitrary string, so most providers expose a CONTENT_URI property that includes its<br />

authority.<br />

Content Providers usually expose two forms of URI, one for requests against all the data and<br />

another that specifi es only a single row. The form for the latter appends / to the standard<br />

CONTENT_URI.<br />

Querying for Content<br />

As in databases, query results are returned as Cursors over a result set. You can extract values from the<br />

cursor using the techniques described previously within the database section on “Extracting Results<br />

from a Cursor.”<br />

Content Provider queries take a very similar form to database queries. Using the query method on the<br />

ContentResolver object, pass in:<br />

❑ The URI of the content provider data you want to query<br />

❑ A projection that represents the columns you want to include in the result set<br />

❑ A where clause that defi nes the rows to be returned. You can include ? wild cards that will be<br />

replaced by the values stored in the selection argument parameter.<br />

❑ An array of selection argument strings that will replace the ?’s in the where clause<br />

❑ A string that describes the order of the returned rows<br />

The following skeleton code demonstrates the use of a Content Resolver to apply a query to a Content<br />

Provider:<br />

// Return all rows<br />

Cursor allRows = getContentResolver().query(MyProvider.CONTENT_URI,<br />

null, null, null, null);<br />

// Return all columns for rows where column 3 equals a set value<br />

// and the rows are ordered by column 5.<br />

String where = KEY_COL3 + “=” + requiredValue;<br />

String order = KEY_COL5;<br />

Cursor someRows = getContentResolver().query(MyProvider.CONTENT_URI,<br />

null, where, null, order);<br />

You’ll see some more practical examples of querying for content later in this chapter when the native<br />

Android content providers are introduced.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!