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

(gtxtreme123) #1

Chapter 14  SQLite Databases


Using a CursorWrapper


A Cursor leaves a lot to be desired as a way to look at a table. All it does is give you raw column
values. Pulling data out of a Cursor looks like this:


String uuidString = cursor.getString(
cursor.getColumnIndex(CrimeTable.Cols.UUID));
String title = cursor.getString(
cursor.getColumnIndex(CrimeTable.Cols.TITLE));
long date = cursor.getLong(
cursor.getColumnIndex(CrimeTable.Cols.DATE));
int isSolved = cursor.getInt(
cursor.getColumnIndex(CrimeTable.Cols.SOLVED));


Every time you pull a Crime out of a cursor, you need to write this code one more time. (And that does
not include the code to create a Crime instance with those values!)


Remember the DRY rule of thumb: Don’t repeat yourself. Instead of writing this code each time you
need to read data from a Cursor, you can create your own Cursor subclass that takes care of this in one
place. The easiest way to write a Cursor subclass is to use CursorWrapper. A CursorWrapper lets you
wrap a Cursor you received from another place and add new methods on top of it.


Create a new class in the database package called CrimeCursorWrapper.


Listing 14.13  Creating CrimeCursorWrapper (CrimeCursorWrapper.java)


public class CrimeCursorWrapper extends CursorWrapper {
public CrimeCursorWrapper(Cursor cursor) {
super(cursor);
}
}


That creates a thin wrapper around a Cursor. It has all the same methods as the Cursor it wraps, and
calling those methods does the exact same thing. This would be pointless, except that it makes it
possible to add new methods that operate on the underlying Cursor.


Add a getCrime() method that pulls out relevant column data. (Remember to use the two-step import
trick for CrimeTable here, as you did earlier.)


Listing 14.14  Adding getCrime() method (CrimeCursorWrapper.java)


public class CrimeCursorWrapper extends CursorWrapper {
public CrimeCursorWrapper(Cursor cursor) {
super(cursor);
}


public Crime getCrime() {
String uuidString = getString(getColumnIndex(CrimeTable.Cols.UUID));
String title = getString(getColumnIndex(CrimeTable.Cols.TITLE));
long date = getLong(getColumnIndex(CrimeTable.Cols.DATE));
int isSolved = getInt(getColumnIndex(CrimeTable.Cols.SOLVED));


return null;
}
}

Free download pdf