Using Explicit Where Clauses

Now that you have seen how to use a URI to send in a where clause, consider the other method by which Android lets us send a list of explicit columns and their corresponding values as a where clause. To explore this, let's take another look at the managedQuery method of the Activity class that we used in Listing 3-23. Here's its signature:

public final Cursor managedQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

Notice the argument named selection, which is of type String. This selection string represents a filter (where clause, essentially) declaring which rows to return, formatted as a SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI. In the selection string you can include ?s, which will be replaced by the values from selectionArgs in the order that they appear in the selection. The values will be bound as Strings.

Because you have two ways of specifying a where clause, you might find it difficult to determine how a provider has used these where clauses and which where clause takes precedence if both where clauses are utilized.

For example, you can query for a note whose ID is 23 using either of these two methods:

//URI method managedQuery("content://com.google.provider.NotePad/notes/23"

,null

,null

,null

//explicit where clause managedQuery("content://com.google.provider.NotePad/notes"

,null

The convention is to use where clauses through URIs where applicable and use the explicit option as a special case.

0 0

Post a comment