Search code examples
androidsqliteandroid-cursor

Cursor Index Out Of Bounds Exception - Android SQLite


I'm attempting to query my SQLite database but I'm getting the error "Cursor Index Out Of Bounds Exception: Index 0 requested, with a size of 0". When I run the same query in SQLite Man, I get the result I'm looking for.

public int getHighScore () {

    String query = "SELECT score FROM " + SCORE_TABLE + ";";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    cursor.moveToFirst();
    int score = cursor.getInt(0);
    cursor.close();
    return score;

}

Solution

  • Please check if cursor is not null then you want to fetch record from cursor.Use this line to fetch record: cursor.getInt(cursor.getColumnIndex("score")))

    use this code :

    public int getHighScore () {
    int score=0;
        String query = "SELECT score FROM " + SCORE_TABLE + ";";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(query, null);
       if (cursor != null && cursor.moveToFirst()) {
         score = cursor.getInt(cursor.getColumnIndex("score")));
    }
        cursor.close();
        return score;
    
    }