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

(gtxtreme123) #1

Chapter 14  SQLite Databases


Converting to model objects


With CrimeCursorWrapper, vending out a List from CrimeLab will be straightforward. You
need to wrap the cursor you get back from your query in a CrimeCursorWrapper, then iterate over it
calling getCrime() to pull out its Crimes.


For the first part, update queryCrimes(...) to use CrimeCursorWrapper.


Listing 14.17  Vending cursor wrapper (CrimeLab.java)


private Cursor queryCrimes(String whereClause, String[] whereArgs) {
private CrimeCursorWrapper 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;
return new CrimeCursorWrapper(cursor);
}


Then get getCrimes() into shape. Add code to query for all crimes, walk the cursor, and populate a
Crime list.


Listing 14.18  Returning crime list (CrimeLab.java)


public List getCrimes() {
return new ArrayList<>();
List crimes = new ArrayList<>();


CrimeCursorWrapper cursor = queryCrimes(null, null);


try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
crimes.add(cursor.getCrime());
cursor.moveToNext();
}
} finally {
cursor.close();
}


return crimes;
}


Database cursors are called cursors because they always have their finger on a particular place in a
query. So to pull the data out of a cursor, you move it to the first element by calling moveToFirst(),
and then read in row data. Each time you want to advance to a new row, you call moveToNext(), until
finally isAfterLast() tells you that your pointer is off the end of the data set.

Free download pdf