Книга: 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,
null, null, 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.
- Using Double Quotes to Resolve Variables in Strings with Embedded Spaces
- Drawbacks with restore
- 7. AGGREGATION WITH INDEPENDENT WORKS
- Chapter 2 Building and Deploying a Run-Time Image
- Конструкция with-do
- 3. Hexadecimal – the way we communicate with micros
- CHAPTER 3 Working with GNOME
- CHAPTER 8 Printing with Fedora
- CHAPTER 15 Remote Access with SSH
- CHAPTER 20 Remote File Serving with FTP
- Managing Files with the Shell
- Working with Compressed Files