Книга: Beginning Android

Building with Builders

Building with Builders

Yet another option is to use SQLiteQueryBuilder, which offers much richer query-building options, particularly for nasty queries involving things like the union of multiple sub-query results. More importantly, the SQLiteQueryBuilder interface dovetails nicely with the ContentProvider interface for executing queries. Hence, a common pattern for your content provider’s query() implementation is to create a SQLiteQueryBuilder, fill in some defaults, then allow it to build up (and optionally execute) the full query combining the defaults with what is provided to the content provider on the query request.

For example, here is a snippet of code from a content provider using SQLiteQueryBuilder:

@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;
}

Content providers are explained in greater detail in Part 5 of this book, so some of this you will have to take on faith until then. Here, we see the following:

1. A SQLiteQueryBuilder is constructed.

2. It is told the table to use for the query (setTables(getTableName())).

3. It is either told the default set of columns to return (setProjectionMap()), or is given a piece of a WHERE clause to identify a particular row in the table by an identifier extracted from the Uri supplied to the query() call (appendWhere()).

4. Finally, it is told to execute the query, blending the preset values with those supplied on the call to query()(qb.query(db, projection, selection, selectionArgs, null, null, orderBy)).

Instead of having the SQLiteQueryBuilder execute the query directly, we could have called buildQuery() to have it generate and return the SQL SELECT statement we needed, which we could then execute ourselves.

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


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