Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Reading from the Database


Reading from the Database


Reading in data from SQLite is done using the query(...) method. SQLiteDatabase.query(...) has quite
a lot going on. There are a few different overloads of this method. The one you will be using looks like
this:


public Cursor query(
String table,
String[] columns,
String where,
String[] whereArgs,
String groupBy,
String having,
String orderBy,
String limit)


If you have dealt with SQL before, then most of these will be familiar to you as arguments of the
select statement. If you have not, then you only need to worry about the ones you will be using:


public Cursor query(
String table,
String[] columns,
String where,
String[] whereArgs,
String groupBy,
String having,
String orderBy,
String limit)


The table argument is the table to query. The columns argument names which columns you want
values for and what order you want to receive them in. And then where and whereArgs do the same
thing they do in update(...).


Use query(...) in a convenience method to call this on your CrimeTable.


Listing 14.12  Querying for Crimes (CrimeLab.java)


public void updateCrime(Crime crime) {
...
}


private Cursor queryCrimes(String whereClause, String[] whereArgs) {
Cursor cursor = mDatabase.query(
CrimeTable.NAME,
null, // columns - null selects all columns
whereClause,
whereArgs,
null, // groupBy
null, // having
null // orderBy
);


return cursor;
}

Free download pdf