• 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();  
  • 相关阅读:
    Java 中常用缓存Cache机制的实现
    Spring普通类获取bean
    系统升级shell
    shell 操作文本内容(修改增加)
    接口实践;接口与抽象类
    Java中@Override的作用
    类实现多个接口的例子
    java 反射实践
    对象主要属性及识别
    java抽象类实践
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/6393123.html
Copyright © 2020-2023  润新知