Android开发7――android.database.CursorIndexOutOfBoundsException:Index -1 requested


android中数据库处理使用cursor时,游标不是放在为0的下标,而是放在为-1的下标处开始的。

也就是说返回给cursor查询结果时,不能够马上从cursor中提取值。

下面的代码会返回错误

 
 
  1. User u = null;  

  2. SQLiteDatabase db = dbHelper.getReadableDatabase();  

  3. Cursor cursor = db.rawQuery("select * from user where id = ?", new String[] { id.toString() });  

  4. Integer uid = cursor.getInt(cursor.getColumnIndex("id"));  

  5. String uname = cursor.getString(cursor.getColumnIndex("name"));  

  6. float uamount = cursor.getFloat(cursor.getColumnIndex("amount"));  

  7. u = new User(uid, uname, uamount);  

正确的用法

 
 
  1. User u = null;  

  2. SQLiteDatabase db = dbHelper.getReadableDatabase();  

  3. Cursor cursor = db.rawQuery("select * from user where id = ?", new String[] { id.toString() });  

  4. if (cursor.moveToFirst())  

  5. {  

  6. Integer uid = cursor.getInt(cursor.getColumnIndex("id"));  

  7. String uname = cursor.getString(cursor.getColumnIndex("name"));  

  8. float uamount = cursor.getFloat(cursor.getColumnIndex("amount"));  

  9. u = new User(uid, uname, uamount);  

  10. }  


你可能感兴趣的:(android,数据库,Cursor,where,requested)