到目前为止,这让我很困惑。
尝试运行此特定查询时,我不断收到 CursorIndexOutOfBounds。
Cursor c = db.rawQuery("SELECT * FROM table WHERE _id='2'" , null);
但奇怪的是,在该查询之上我正在运行一个循环,该循环输出该表中的所有 _id 值。它输出 1 到 100,所以我知道值在那里。我还输出了所有的列,它们都如我所料。
即使我非常确定有值并且在正确的列中,这行代码仍然会抛出 CursorIndexOutOfBounds。谁能建议解决这个问题的途径。
numval = c.getInt(c.getColumnIndex("_id"));
Logcat 条目
11-21 11:35:09.367: ERROR/AndroidRuntime(11664): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
编辑
这是我正在运行的确切代码。我仍然收到我在这句话上方发布的错误。
Cursor cur = db.rawQuery("SELECT * FROM table" , null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
numval = cur.getInt(cur.getColumnIndex("_id"));
String numvalval = Integer.toString(numval);
Log.e("RESULT",numvalval);
cur.moveToNext();
}
cur.close();
Cursor ti = db.rawQuery("PRAGMA table_info(table)", null);
if ( ti.moveToFirst() ) {
do {
Log.e("COLUMN NAMES","col: '" + ti.getString(1) +"'");
} while (ti.moveToNext());
}
ti.close();
Cursor c = db.rawQuery("SELECT * FROM table WHERE _id='2'" , null);
c.moveToFirst();
numval = c.getInt(c.getColumnIndex("_id"));
正在输出
11-21 13:27:25.906: ERROR/RESULT(13377): 1
11-21 13:27:25.906: ERROR/RESULT(13377): 2
11-21 13:27:25.910: ERROR/COLUMN NAMES(13377): col: '_id'
11-21 13:27:25.910: ERROR/COLUMN NAMES(13377): col: 'country'
最佳答案
请参阅编辑,在您编辑问题后,以下建议不再有效。
当你得到一个 Cursor
对象时,一开始你应该总是把它移到第一行。所以你的代码应该是这样的:
if(c.moveToFirst()) {
numval = c.getInt(c.getColumnIndex("_id"));
}
else {
/* SQL Query returned no result ... */
}
编辑
将您的查询更改为此(不带引号“2”):
Cursor c = db.rawQuery("SELECT * FROM table WHERE _id=2" , null);
关于java - 如何解决 Cursor IndexOutOfBounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8211802/