Search code examples
androidsqlitesqliteopenhelper

Android SQLiteOpenHelper


My application crashes with

java.lang.RuntimeException: Unable to start activity ComponentInfo{...}:
    java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
    ...

Here is the method that is causing the error:

public int getWeek(int yearAndWeek) throws CursorIndexOutOfBoundsException {
    SQLiteDatabase db = this.getReadableDatabase();

    String selectQuery = "SELECT  * FROM " + TABLE_WEEKS + " WHERE "
            + KEY_WEEK + " = " + yearAndWeek;

    Cursor c = db.rawQuery(selectQuery, null);

    if (c.getCount() > 0)
        c.moveToFirst();

    return c.getInt(c.getColumnIndex(KEY_WEEK_NUMBER));
}

The error occurs in this line return c.getInt(c.getColumnIndex(KEY_WEEK_NUMBER));. Please help me to fix this bug.


Solution

  • To Keep proper reply from a method you can try with the following code.

    public int getWeek(int yearAndWeek) throws CursorIndexOutOfBoundsException {
    
        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery = "SELECT * FROM " + TABLE_WEEKS + " WHERE " + KEY_WEEK + " = " + yearAndWeek;
        Cursor c = db.rawQuery(selectQuery, null);
    
        if (c.getCount() > 0) {
            c.moveToFirst();
            return c.getInt(c.getColumnIndex(KEY_WEEK_NUMBER));
        }
        return -1;        
    }