我在Android Studio中使用libgdx和gdx-sqlite。我想从我的数据库中使用以下代码进行简单查询。
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();
}
桌面版本没有问题,但在Android版本中我收到以下错误:
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)
因此,每次我从游标进行getXXX()查询时都会收到错误,但如果我现在使用以下代码:
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)));
}
我的所有数据都有正确的输出。 有谁知道问题是什么? 谢谢你的帮助
答案 0 :(得分:1)
好的,我自己发现了问题,那就是Android类中的代码
@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);
}
}
问题是在android中光标指向-1所以必须先将其设置到正确的位置,以下代码解决了问题
@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);
}
}
您可以在AndroidCursor类的库gdx-sqlite-android.jar中找到此代码。
我希望这个解决方案有助于某人。