Книга: Beginning Android

Making Queries

Making Queries

Given a base Uri, you can run a query to return data out of the content provider related to that Uri. This has much of the feel of SQL: you specify the “columns” to return, the constraints to determine which “rows” to return, a sort order, etc. The difference is that this request is being made of a content provider, not directly of some database (e.g., SQLite).

The nexus of this is the managedQuery() method available to your activity. This method takes five parameters:

1. The base Uri of the content provider to query, or the instance Uri of a specific object to query

2. An array of properties of instances from that content provider that you want returned by the query

3. A constraint statement, functioning like a SQL WHERE clause

4. An optional set of parameters to bind into the constraint clause, replacing any ?s that appear there

5. An optional sort statement, functioning like a SQL ORDER BY clause

This method returns a Cursor object, which you can use to retrieve the data returned by the query.

“Properties” is to content providers as columns are to databases. In other words, each instance (row) returned by a query consists of a set of properties (columns), each representing some piece of data.

This will hopefully make more sense given an example.

Our content provider examples come from the ContentProvider/Constants sample application, specifically the ConstantsBrowser class:

constantsCursor = managedQuery(Provider.Constants.CONTENT_URI,
 PROJECTION, nullnullnull);

In the call to managedQuery(), we provide:

• The Uri passed into the activity by the caller (CONTENT_URI), in this case representing the collection of physical constants managed by the content provider

• A list of properties to retrieve (see the following code)

• Three null values, indicating that we do not need a constraint clause (the Uri represents the instance we need), nor parameters for the constraint, nor a sort order (we should only get one entry back)

private static final String[] PROJECTION = new String[] {
 Provider.Constants._ID, Provider.Constants.TITLE,
 Provider.Constants.VALUE};

The biggest “magic” here is the list of properties. The lineup of what properties are possible for a given content provider should be provided by the documentation (or source code) for the content provider itself. In this case, we define logical values on the Provider content provider implementation class that represent the various properties (namely, the unique identifier, the display name or title, and the value of the constant).

Оглавление книги


Генерация: 1.286. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз