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】
推荐阅读
- 译Android 7.0 for Developers
- Android编译选项enguseruserdebug的区别
- 管理Android设备的唤醒状态
- Android系统层次解析
- (Android UI)Action Bar
- android 中处理崩溃异常并重启程序
- Android7.0 Phone应用源码分析 phone拒接流程分析
- Android的ImageLoader图片加载简单逻辑
- Android SQLite数据库基本操作