2014-12-01 2 views
-2

Я извлечение строки из поля продукта:DataBase курсора нелегального состояние исключение

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

help

ответ

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; 
} 
+0

спасибо! он работает, я собираюсь принять ваш ответ, как только сайт позволит мне :) – zenta

0

Ваш курсор не имеет 10 строк, он возвращает всего 2 строки.
Попробуйте зацикливание на размер курсора cursor.getCount().

Смежные вопросы