我写了一个查询,根据id选择名称和指定字段,然后在片段类中我调用属于相应查询的方法,但不幸的是我得到了Sqlite异常。
数据库方法
public Employee getEmployeeName(int id) {
SQLiteDatabase db = this.getWritableDatabase();
Employee employee = new Employee();
String query ="SELECT " + KEY_NAME +", " +KEY_DESIG +" FROM " + TABLE_EMPLOYEES+ " WHERE " + KEY_ID + "=" + id;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
employee.setName(cursor.getString(1));
employee.setDesignation(cursor.getString(2));
} while (cursor.moveToNext());
}
return employee;
}
从片段中调用
db.getEmployeeName(selectedManager);
异常
01-07 06:02:34.185: E/AndroidRuntime(2386): java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
答案 0 :(得分:3)
列索引从零开始。 getString(2)
引用第三列,光标只有两列。
更改
employee.setName(cursor.getString(1));
employee.setDesignation(cursor.getString(2));
到
employee.setName(cursor.getString(0));
employee.setDesignation(cursor.getString(1));
答案 1 :(得分:2)
试试这个
if (cursor.moveToFirst()) {
do {
employee.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME));
employee.setDesignation(cursor.getString(cursor.getColumnIndex(KEY_DESIG));
} while (cursor.moveToNext());
}
使用Cursor
cursor.getColumnIndex(COLUMN NAME)
获取数据