我只是想在多个表中搜索数据。如果第一个表 (tab1) 中不存在 where 条件数据,则它必须在第二个表 (tab2) 中搜索,但我收到异常显示
Cursor Index Out of Bounds Exception: Index -1 requested with size 0
这是我的代码
SQLiteDatabase db=openOrCreateDatabase("train",SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor c1;
String[] table={"tab1","tab2","tab3","tab4"};
int i=0;
do {
c1 = db.rawQuery("select * from '"+table[i]+"' where name='Triplicane'", null);
i++;
} while(c1 == null);
int id1=c1.getInt(0);
String nam1=c1.getString(1);
Toast.makeText(fare.this,"ID no:"+id1, Toast.LENGTH_LONG).show();
Toast.makeText(fare.this,"name"+nam1, Toast.LENGTH_LONG).show();
最佳答案
所以从一开始。隐含地,每个 Cursor 都位于第一行之前,因此如果你想使用它,你需要调用
cursor.moveToFirst()
如果不为空,则将 Cursor 移动到第一行,然后就可以开始工作了。如果 Cursor 为空,则返回 false。所以我现在提到这个方法是非常方便的指示器,指示您的 Cursor 是否有效。
根据我的建议,我建议您更改代码,因为我认为它已损坏并且听起来像“意大利面条代码”
Cursor c = null;
String[] tables = {"tab1", "tab2", "tab3", "tab4"};
for (String table: tables) {
String query = "select * from '" + table + "' where name = 'Triplicane'";
c = db.rawQuery(query, null);
if (c != null) {
if (c.moveToFirst()) { // if Cursor is not empty
int id = c.getInt(0);
String name = c.getString(1);
Toast.makeText(fare.this, "ID: " + id, Toast.LENGTH_LONG).show();
Toast.makeText(fare.this, "Name: " + name, Toast.LENGTH_LONG).show();
}
else {
// Cursor is empty
}
}
else {
// Cursor is null
}
}
注意事项:
现在我想告诉你一些建议:
使用参数化语句是非常好的做法,因此在 future ,如果您将使用语句,请在其中使用占位符。然后您的语句变得更易于阅读、更安全 (
SQL Injection
) 和更快。创建静态最终字段也是一个很好的做法 您的列名、表名等并使用
getColumnIndex(<columnName>)
避免正在寻找非常糟糕的“拼写错误”的方法。
关于android - 游标索引越界异常: Index -1 requested with size 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15719264/