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!

3 comments:

  1. This is really a great stuff for sharing. Thanks for sharing.
    https://www.bharattaxi.com

    ReplyDelete
  2. In most cases, a cursor returns a string. For example, the cursor hire someone to take my class for a file would return the contents of that file. However, in some cases, a cursor may return a number. For example, the cursor for a database connection might return the number of rows in the table. These values are not always human-readable. This book provides the knowledge to debug your cursor values and make sense of them.

    ReplyDelete