Get the List of Restaurants from the Database
This puts restaurants into the database. Presumably, it would be useful to get them back out sometime. Hence, we need some logic that can query the database and return a Cursor with columnar data from our restaurant table.A Cursor in Android is much like a cursor in other database access libraries – it is an encapsulation of the result set of the query, plus the query that was used to create it.
T o do this, add the following method to RestaurantHelper:
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, name, address, type, notes FROM restaurants
ORDER BY name",
null));
}
Here, we get access to the underlying SQLiteDatabase (opening it in read mode if it is not already open) and call rawQuery(), passing in a suitable query string to retrieve all restaurants, sorted by name.
We will also need to have some way to get the individual pieces of data out of the Cursor (e.g., name). To that end, add a few getter-style methods to RestaurantHelper that will retrieve the proper columns from a Cursor positioned on the desired row:
public String getName(Cursor c) {
return(c.getString(1));
}
public String getAddress(Cursor c) {
return(c.getString(2));
}
public String getType(Cursor c) {
return(c.getString(3));
}
public String getNotes(Cursor c) {
return(c.getString(4));
}
No comments:
Post a Comment