Книга: Beginning Android

query()

query()

As one might expect, the query() method is where your content provider gets details on a query some activity wants to perform. It is up to you to actually process said query.

The query method gets the following as parameters:

• A Uri representing the collection or instance being queried

• A String[] representing the list of properties that should be returned

• A String representing what amounts to a SQL WHERE clause, constraining which instances should be considered for the query results

• A String[] representing values to “pour into” the WHERE clause, replacing any ? found there

• A String representing what amounts to a SQL ORDER BY clause

You are responsible for interpreting these parameters however they make sense and returning a Cursor that can be used to iterate over and access the data.

As you can imagine, these parameters are aimed toward people using a SQLite database for storage. You are welcome to ignore some of these parameters (e.g., you can elect not to try to roll your own SQL WHERE-clause parser), but you need to document that fact so activities attempt to query you only by instance Uri and not using parameters you elect not to handle.

For SQLite-backed storage providers, however, the query() method implementation should be largely boilerplate. Use a SQLiteQueryBuilder to convert the various parameters into a single SQL statement, then use query() on the builder to actually invoke the query and give you a Cursor back. The Cursor is what your query() method then returns.

For example, here is query() from Provider:

@Override
public Cursor query(Uri url, String[] projection, String selection,
 String[] selectionArgs, String sort) {
 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
 qb.setTables(getTableName());
 if (isCollectionUri(url)) {
  qb.setProjectionMap(getDefaultProjection());
 } else {
  qb.appendWhere(getIdColumnName()+"="+url.getPathSegments().get(1));
 }
 String orderBy;
 if (TextUtils.isEmpty(sort)) {
  orderBy = getDefaultSortOrder();
 } else {
  orderBy = sort;
 }
 Cursor c = qb.query(db, projection, selection, selectionArgs,
  nullnull, orderBy);
 c.setNotificationUri(getContext().getContentResolver(), url);
 return c;
}

We create a SQLiteQueryBuilder and pour the query details into the builder. Note that the query could be based on either a collection or an instance Uri — in the latter case, we need to add the instance ID to the query. When done, we use the query() method on the builder to get a Cursor for the results.

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

Оглавление статьи/книги

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