DataBase游标非法状态异常

时间:2014-12-01 09:24:50

标签: android database cursor indexoutofboundsexception

我正在从“产品”字段中检索字符串:

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类中使用游标,我对添加到db的最后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

帮助

2 个答案:

答案 0 :(得分:2)

你正在移动两个位置。方法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;
}

答案 1 :(得分:0)

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