首页 > 代码库 > Android android.database.CursorIndexOutOfBoundsException:Index -1 requested, with a size of 1
Android android.database.CursorIndexOutOfBoundsException:Index -1 requested, with a size of 1
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。