Search code examples
androidsqlitecursor

CursorIndexOutOfBoundsException with cursor.getInt()


this is my code:

 Log.d("MYTAG", "random number -->" + randomNumber);
 idRandomCards[i] = cursorTypeZero.getInt(randomNumber);

this is the error Log:

7620-7620/package D/MYTAG﹕ random number -->94
04-02 16:06:51.804    7620-7620/package D/AndroidRuntime﹕ Shutting down VM
04-02 16:06:51.804    7620-7620/package W/dalvikvm﹕ threadid=1: thread exiting    with uncaught exception (group=0x41bafda0)
04-02 16:06:51.854    7620-7620/package D/dalvikvm﹕ GC_FOR_ALLOC freed 1283K,     45% free 9237K/16608K, paused 42ms, total 46ms
04-02 16:06:51.864    7620-7620/package E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: package, PID: 7620
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 206
        at ecc

as you will see, the random number in this case has the value of 94. the cursor.getCount() = 206.

why i have this exception?

i dont' wanna use the cursor.getColumnIndexOrThrow() method, because i need a random row.

someone can help me?


Solution

  • Because the column does not exits. If I understood correctly. you want to move the cursor to the random position, and read the data from that row:

    use

     cursor.moveToPosition(randomNumber);
    

    and then read from the correct column, using getColumnIndexOrThrow to read the column's index. You should also check that randomNumber is between 0 and cursor.getCount() - 1