Search code examples
sqlitelibgdxcursor

android.database.CursorIndexOutOfBoundsException in desktop version only


I am using libgdx and gdx-sqlite in Android Studio. I want to query my database using:

try {
    cursorSettings = dbHandler.rawQuery("SELECT "+COLUMN_SETTING+" FROM "+TABLE_SETTINGS+" WHERE "+COLUMN_SETTINGSID+" =13");
    System.out.println(cursorSettings.getLong(0));
} catch (SQLiteGdxException e) {
    e.printStackTrace();
}

The desktop version works but in the Android version I get:

05-25 10:21:47.341 11978-12232/ch.shuttering.rapporte E/AndroidRuntime: FATAL EXCEPTION: GLThread 82275
Process: ch.shuttering.rapporte, PID: 11978
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
    at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
    at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
    at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:74)
    at com.badlogic.gdx.sqlite.android.AndroidCursor.getLong(AndroidCursor.java:61)
    at ch.shuttering.rapporte.Manager.SQLiteManager.SaveMangerSQLite.creatSQLiteSettings(SaveMangerSQLite.java:295)
    at ch.shuttering.rapporte.RapporteMain.create(RapporteMain.java:66)
    at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:311)
    at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1546)
    at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1262)

Every time I do a getXXX() query from the cursor I get an error, but if I use:

try {
    cursorSettings = dbHandler.rawQuery("SELECT * FROM "+TABLE_SETTINGS);
} catch (SQLiteGdxException e) {
    e.printStackTrace();
}
while (cursorSettings.next()) {
    Gdx.app.log("FromDb", String.valueOf(cursorSettings.getString(1)));
}

I get the correct output with all data. What is the problem?


Solution

  • It was the code in the Android class:

    @Override
    public long getLong (int columnIndex) {
        try {
            return cursor.getLong(columnIndex);
        } catch (SQLiteException e) {
            Gdx.app.log(DatabaseFactory.ERROR_TAG, "There was an error in getting the long", e);
            throw new SQLiteGdxRuntimeException(e);
        }
    }
    

    In Android the cursor points to -1, so it needs to be set to the correct position first:

    @Override
    public long getLong (int columnIndex) {
        try {
            cursor.moveToFirst();
            return cursor.getLong(columnIndex);
        } catch (SQLiteException e) {
            Gdx.app.log(DatabaseFactory.ERROR_TAG, "There was an error in getting the long", e);
            throw new SQLiteGdxRuntimeException(e);
        }
    }
    

    You can find this code in the library gdx-sqlite-android.jar in the class AndroidCursor.