Android Programming Tutorials

(Romina) #1
Searching For Food

String where=null;

if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {
where="name LIKE \"%"+getIntent().getStringExtra(SearchManager.QUERY)+"%\"";
}

model=helper.getAll(where, prefs.getString("sort_order", "name"));
startManagingCursor(model);
adapter=new RestaurantAdapter(model);
setListAdapter(adapter);
}

The ACTION_SEARCH Intent will be sent to our activity if the activity was


started as the result of a search request. Here, we are having the same


activity be the "normal" presentation and display search results – this


approach may or may not be appropriate for any given application. The


search is simply a WHERE clause, searching for the search term


(getIntent().getStringExtra(SearchManager.QUERY)) anywhere in the


restaurant's name.


You will need to add an import for android.app.SearchManager.


This also means we need to accept a possible WHERE clause in the getAll()


method of RestaurantHelper:


public Cursor getAll(String where, String orderBy) {
StringBuilder buf=new StringBuilder("SELECT _id, name, address, type, notes
FROM restaurants");

if (where!=null) {
buf.append(" WHERE ");
buf.append(where);
}

if (orderBy!=null) {
buf.append(" ORDER BY ");
buf.append(orderBy);
}

return(getReadableDatabase().rawQuery(buf.toString(), null));
}

301
Free download pdf