码迷,mamicode.com
首页 > 移动开发 > 详细

Android android.database.CursorIndexOutOfBoundsException:Index -1 requested, with a size of 1

时间:2017-02-13 12:19:57      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:lan   null   use   tostring   roi   提取   blog   blank   不能   

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

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

下面的代码会返回错误

User u = null;  
SQLiteDatabase db = dbHelper.getReadableDatabase();  
Cursor cursor = db.rawQuery("select * from user where id = ?", new String[] { id.toString() });  
Integer uid = cursor.getInt(cursor.getColumnIndex("id"));  
String uname = cursor.getString(cursor.getColumnIndex("name"));  
float uamount = cursor.getFloat(cursor.getColumnIndex("amount"));  
u = new User(uid, uname, uamount);cursor.close();  

正确的用法

User u = null;  
SQLiteDatabase db = dbHelper.getReadableDatabase();  
Cursor cursor = db.rawQuery("select * from user where id = ?", new String[] { id.toString() });  
if (cursor.moveToFirst())  
{  
 Integer uid = cursor.getInt(cursor.getColumnIndex("id"));  
 String uname = cursor.getString(cursor.getColumnIndex("name"));  
 float uamount = cursor.getFloat(cursor.getColumnIndex("amount"));  
 u = new User(uid, uname, uamount);  
}  
cursor.close();  

 

Android android.database.CursorIndexOutOfBoundsException:Index -1 requested, with a size of 1

标签:lan   null   use   tostring   roi   提取   blog   blank   不能   

原文地址:http://www.cnblogs.com/zhujiabin/p/6393123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!