Friday, April 11, 2014

Debugging Cursor Values

Many times, you will have to query content providers. For that you'll either use a content resolver or use the CursorLoader class. In both cases you get back a Cursor object back.

For quick debugging, you'd want to examine the contents of the cursor. For quick debugging purpose, it is painful to extract all the columns coz you need to know the column data types and names etc...

Cursor cursor = getContentResolver().query(<uri and other params>);
if (cursor != null) {
    while (cursor.moveToNext()){
          intValue = cursor.getInt(cursor.getColumnIndex(<Column name from provider contract>));
          stringValue = cursor.getString(cursor.getColumnIndex(<Column name from provider contract>));
          longValue = cursor.getLong(cursor.getColumnIndex(<Column name from provider contract>));
          //..... and so on for all the columns you need to debug

I came across this simple method in the DatabaseUtils class which, for some reason, I never noticed :) It has there been since Api level 1 :O

Super useful for quick and dirty debugging.

public static String dumpCurrentRowToString (Cursor cursor)

So now the code becomes:

while (cursor.moveToNext())
       Log.d(TAG,  DatabaseUtils.dumpCurrentRowToString(cursor));

Makes debugging life so easy!