Output values found in cursor to logcat? - Android
Asked Answered
I

5

21

I'm trying to debug an issue myself. May post it later if I fail ;-)

My logcat log states "android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2"

I would like to use log.v("desc", cursor) to show what the cursor returns. Is there a way to specify a value from it like cursor[0] ?

Infrastructure answered 23/6, 2010 at 20:2 Comment(1)
"I would like to use log.v("desc", cursor) to show what the cursor returns. Is there a way to specify a value from it like cursor[0] ?" I wonder what you mean in the sentence? Would you like to see whole row number 0 (value of all columns in row 0)?Indre
I
6

You should call moveToFirst() on Cursor.

Indre answered 23/6, 2010 at 20:5 Comment(0)
C
70

Android has provided a specific class just for debugging Cursors. It is called DatabaseUtils.

Call the method dumpCursorToString() to view the contents of your cursor.

This helper loops through and prints out the content of the Cursor for you, and returns the cursor to its original position so that it doesn't mess up your iterating logic.

Colorific answered 28/10, 2012 at 3:59 Comment(0)
O
64

use this before cursor.moveToFirst()

Log.v("Cursor Object", DatabaseUtils.dumpCursorToString(cursor))
Overseer answered 21/1, 2014 at 10:44 Comment(1)
+ import android.database.DatabaseUtils;Witwatersrand
I
13

If you intend to write contents of the cursor to the logcat row by row you can use code as below:

if (cursor.moveToFirst()) {
    do {
        StringBuilder sb = new StringBuilder();
        int columnsQty = cursor.getColumnCount();
        for (int idx=0; idx<columnsQty; ++idx) {
            sb.append(cursor.getString(idx));
            if (idx < columnsQty - 1)
                sb.append("; ");
        }
        Log.v(TAG, String.format("Row: %d, Values: %s", cursor.getPosition(), 
            sb.toString()));
    } while (cursor.moveToNext());
}
Indre answered 23/6, 2010 at 20:28 Comment(1)
what if column is not string, it may be int double?Phyllisphylloclade
I
6

You should call moveToFirst() on Cursor.

Indre answered 23/6, 2010 at 20:5 Comment(0)
B
0

Or if you're looking for where the cursor is at a specific point in time, call Cursor.getPosition()

Take a look at the Cursor API.

It's often very wordy, but sometimes it helps.

Bullhorn answered 23/6, 2010 at 20:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.