20.08.2016 Views

Professional Android 4 Application Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Adding Search to Your <strong>Application</strong> x 299<br />

LISTING 8-31: Returning the correct MIME type for search results<br />

@Override<br />

public String getType(Uri uri) {<br />

// Return a string that identifies the MIME type<br />

// for a Content Provider URI<br />

switch (uriMatcher.match(uri)) {<br />

case ALLROWS:<br />

return “vnd.android.cursor.dir/vnd.paad.elemental”;<br />

case SINGLE_ROW:<br />

return “vnd.android.cursor.item/vnd.paad.elemental”;<br />

case SEARCH :<br />

return SearchManager.SUGGEST_MIME_TYPE;<br />

default:<br />

throw new IllegalArgumentException(“Unsupported URI: “ + uri);<br />

}<br />

}<br />

code snippet PA4AD_ Ch08_DatabaseSkeleton/src/MySearchSuggestionsContentProvider.java<br />

The Search Manager requests your search suggestions by initiating a query on your Content<br />

Provider, passing in the query value as the last element in the URI path. To provide suggestions, you<br />

must return a Cursor using a set of predefined columns.<br />

There are two required columns, SUGGEST_COLUMN_TEXT_1, which displays the search result text,<br />

and _id, which indicates the unique row ID. You can supply up to two columns containing text, and<br />

an icon to be displayed on either the left or right of the text results.<br />

It’s also useful to include a SUGGEST_COLUMN_INTENT_DATA_ID column. The value returned in this<br />

column can be appended to a specified URI path and used to populate an Intent that will be fired if<br />

the suggestion is selected.<br />

As speed is critical for real-time search results, in many cases it’s good practice to create a separate<br />

table specifically to store and provide them. Listing 8-32 shows the skeleton code for creating a<br />

projection that returns a Cursor suitable for search results.<br />

LISTING 8-32: Creating a projection for returning search suggestions<br />

public static final String KEY_SEARCH_COLUMN = KEY_COLUMN_1_NAME;<br />

private static final HashMap SEARCH_SUGGEST_PROJECTION_MAP;<br />

static {<br />

SEARCH_SUGGEST_PROJECTION_MAP = new HashMap();<br />

SEARCH_SUGGEST_PROJECTION_MAP.put(<br />

“_id”, KEY_ID + “ AS “ + “_id”);<br />

SEARCH_SUGGEST_PROJECTION_MAP.put(<br />

SearchManager.SUGGEST_COLUMN_TEXT_1,<br />

continues

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!