arberb
arberb

Reputation: 960

Cursor Index Out Of Bounds Error Android?

Hey I am getting index out of bounds error in my code.

From Activity:

            Cursor cursor = mDbHelper.fetchA(b);
            @SuppressWarnings("static-access")
            int a = (int) cursor.getDouble(cursor.getColumnIndex(mDbHelper.KEY_I));
            cursor.close();

My DB Adaptor:

public Cursor fetchA(String b){
    return mDb.query(DATABASE_TABLE, new String[] {KEY_I}, "b=\""+B+"\"", null, null, null, null);
}

Error:

    E/AndroidRuntime( 5766): FATAL EXCEPTION: main

    E/AndroidRuntime( 5766): android.database.CursorIndexOutOfBoundsException: Index

     -1 requested, with a size of 1

How can I fix this?

Upvotes: 3

Views: 2267

Answers (2)

kosa
kosa

Reputation: 66677

Cursor cursor = mDbHelper.fetchA(b);
startManagingCursor(cursor);
cursor.moveToNext();
.......

Here your retrieval code.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 360056

Cursors start out pointing to the position before the first row. Consequently, you need to move the cursor to the first row before you can get data. Cursor#moveToFirst() or #moveToNext() ought to do the job.

Cursor cursor = mDbHelper.fetchA(b);
cursor.moveToNext();
@SuppressWarnings("static-access")
int a = (int) cursor.getDouble(cursor.getColumnIndex(mDbHelper.KEY_I));
cursor.close();

Upvotes: 5

Related Questions