我的 SQLite 数据库中有以下表结构。
在我的 SqliteOpenHelper 类中,我编写了以下方法。
public Form getAllForms(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+FORM_TABLE, null);
int count = cursor.getCount();
String formID = cursor.getString(0);
Form form = new Form();
form.setId(formID);
cursor.close();
db.close();
return form;
}
我确定其中有一些数据,因为我已经在 Debug模式下观察了 count
并且我看到了数据库中实际存在的行数。但是 CursorIndexOutOfBoundException 出现在 cursor.getString(0)。加上 cursor.getInt(0) 和 cursor.getString(1) 也不起作用。可能是什么问题?
最佳答案
您需要将光标移动到有效行。
有效行的索引从 0 到 count-1。首先,游标将指向行索引 -1,即第一行之前的行。
遍历所有行的规范方式是
if (cursor.moveToFirst()) {
do {
// now access cursor columns
} while (cursor.moveToNext());
}
关于android - 我无法从游标对象获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24177570/