【问题标题】:DataBase cursor illegal state exception数据库游标非法状态异常
【发布时间】:2014-12-01 09:24:50
【问题描述】:

我正在从 Product 字段中检索一个字符串:

public class Product {
private int _id;
private int _quantity;

public Product() {
}

public Product(int id, int quantity) {
    this._id = id;
    this._quantity = quantity;
}

public Product(int quantity) {

    this._quantity = quantity;
}

public void setID(int id) {
    this._id = id;
}

public int getID() {
    return this._id;
}


public void setQuantity(int quantity) {
    this._quantity = quantity;
}

public int getQuantity() {
    return this._quantity;
}

}

使用 DBHander 类中的光标,我对添加到数据库的最后 10 个产品执行相同的操作:

public int[] retrieveNumbers(){
    String query = "SELECT * FROM " + TABLE_PRODUCTS;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    int[] numbers;
    numbers = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int i;
    if(cursor.moveToLast()){
        cursor.moveToLast();
        for(i=0; i<10; i++){
            numbers[i]=Integer.parseInt(cursor.getString(1));
            if(cursor.moveToPrevious()){
                cursor.moveToPrevious();
            }
        }
        cursor.close();
        db.close();
        return numbers;
    }else{
        cursor.close();
        db.close();
        return numbers;
    }
}

错误是:cursorindexoutofboundexception -1 请求大小为 2

帮助

【问题讨论】:

    标签: android database cursor indexoutofboundsexception


    【解决方案1】:

    您正在移动两个位置而不是一个位置。方法cursor.moveToPrevious()返回true并移动到上一个位置,但是你又移动了一次:

     if(cursor.moveToLast()){
        boolean finished = false;
        for(i=0; i<10 && !finished; i++){
            numbers[i]=Integer.parseInt(cursor.getString(1));
            if(!cursor.moveToPrevious())
            {
               finished = true;
            }
        }
        cursor.close();
        db.close();
        return numbers;
    }else{
        cursor.close();
        db.close();
        return numbers;
    }
    

    【讨论】:

    • 谢谢!它有效,只要网站允许,我就会接受你的回答:)
    【解决方案2】:

    您的光标没有 10 行,它只返回 2 行。
    尝试循环光标cursor.getCount() 的大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多