Working with the where Clause

Content providers offer two ways of passing a where clause:

• Through the combination of a string clause and a set of replaceable string-array arguments

We will cover both of these approaches through some sample code. Passing a where Clause Through a URI

Imagine you want to retrieve a note whose ID is 23 from the Google notes database. You'd use the code in Listing 3-23 to retrieve a cursor containing one row corresponding to row 23 in the notes table.

Listing 3-23. Passing SQL WHERE Clauses Through the URI

Activity someActivity; //..initialize someActivity

String noteUri = "content://"; Cursor managedCursor = someActivity.managedOuery( noteUri, projection, //Which columns to return. null, // WHERE clause null); // Order-by clause.

We left the where clause argument of the managedOuery method null because in this case, we assumed that the note provider is smart enough to figure out the id of the book we wanted. This id is embedded in the URI itself. In a sense, we used the URI as a vehicle to pass the where clause. This becomes apparent when you notice how the notes provider implements the corresponding query method. Here is a code snippet from that query method:

//Retrieve a note id from the incoming uri that looks like

int noteld = uri.getPathSegments().get(l);

//ask a query builder to build a query //specify a table name queryBuilder.setTables(NOTES_TABLE_NAME);

//use the noteid to put a where clause queryBuilder.appendWhere(Notes._ID + "=" + );

Notice how the id of a note is extracted from the URI. The Uri class representing the incoming argument uri has a method to extract the portions of a URI after the root content://com. google.provider.NotePad. These portions are called path segments; they're strings between / separators such as /seg1/seg3/seg4/ and they're indexed by their positions. For the URI here, the first path segment would be 23. We then used this ID of 23 to append to the where clause specified to the OueryBuilder class. In the end, the equivalent select statement would be select * from notes where id == 23

Note The classes Uri and UriMatcher are used to identify URIs and extract parameters from them. (We'll cover UriMatcher further in the section "Using UriMatcher to Figure Out the URIs.") SOLiteOueryBuilder is a helper class in android.database.sqlite that allows you to construct SQL queries to be executed by SOLiteDatabase on a SQLite database instance.

0 0

Post a comment