【发布时间】:2017-06-09 05:47:51
【问题描述】:
我不断收到此错误消息:“原因:android.database.CursorIndexOutOfBoundsException:请求索引 0,大小为 0”在我的代码中。
我已经引用了以下链接,但没有一个有效: Android cursor out of bounds exception
Cursor Index Out Of Bounds Error Android?
cursor index out of bounds exception
public Product getProduct(int id) {
db = this.getReadableDatabase();
Cursor cursor = db.query(
TABLE_NAME,
null,
COLUMN_ID + " = ?",
new String[] { Integer.toString(id)},
null, null, null, null);
Product product = new Product();
cursor.moveToFirst();
if (cursor != null) {
product.setID(cursor.getInt(0));
product.setName(cursor.getString(1));
product.setSize(cursor.getDouble(2));
product.setHp(cursor.getDouble(3));
product.setCategory(cursor.getString(4));
product.setPowerType(cursor.getString(5));
product.setExplosionProof(cursor.getInt(6));
product.setRPM(cursor.getInt(7));
product.setBypassPSI(cursor.getInt(8));
product.setGPM(cursor.getInt(9));
product.setPrice(cursor.getDouble(10));
cursor.close();
}
db.close();
return product;
}
这是我的常量:
private static final String TABLE_NAME = "Products";
private static final String COLUMN_ID = "'_id'";
如果有任何帮助,我将不胜感激。
现在,它不会进入 if 循环。我直接从另一个堆栈溢出问题中得到了该查询模型。
【问题讨论】:
-
如果您的结果为空,就会发生这种情况。你能显示完整的堆栈跟踪吗
-
在调用
cursor.moveToFirst()的行后面加上if (cursor != null)有什么意义? -
添加检查 if(cursor.moveToFirst()) 而不是 if (cursor != null)
-
当我执行 if(cursor.moveToFirst()) 时,它永远不会进入 if 循环
-
你应该使用
if(cursor.moveToNext())
标签: java android sqlite android-sqlite