2017-06-14 98 views
-2

我只是想拉一切從我的數據庫類別:無法從CursorWindow讀取第1行,第1列?

private static final int DB_VERSION = 1; 
private static final String DB_NAME = "WishListDB.DB"; 
private static final String TABLE_ITEMS = "items_table"; 
private static final String COLUMN_INDEX = "item_index"; 
private static final String COLUMN_TITLE = "item_title"; 

private static final String COLUMN_CATEGORY = "item_category"; 

private static final String COLUMN_VENDOR = "item_vendor"; 
private static final String COLUMN_PRICE = "item_price"; 
private static final String COLUMN_IMAGE = "item_image"; 

所以我的總體目標是讓所有的類別,並將其存儲在一個ArrayList太然後傳遞到我的活動微調。這裏就是我所說的數據:

db_manager = new databaseManager(this, null, null, 1); 
    int index_value = (int) db_manager.Get_Length_of_DB(); 
    for (int i = 0; i <= index_value; i++) 
    { 

     category_List = db_manager.get_all_Categories(); 
    } 
    ArrayAdapter categories_adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, category_List); 
    cat_spinner.setAdapter(categories_adapter); 

這裏是我的「get_all_categories」方法

public ArrayList<String> get_all_Categories() 
{ 

    String get_Cats_Query = "SELECT item_category from " + TABLE_ITEMS; 
    Cursor cursor = getReadableDatabase().rawQuery(get_Cats_Query, null); 
    cursor.moveToFirst(); 
    ArrayList<String> cats_from_db = new ArrayList<String>() {}; 
    if(!cursor.isAfterLast()) 
    { 
     for (int i = 0; i < cursor.getCount(); i++) 
     { 
      cats_from_db.add(cursor.getString(i)); 
      cursor.moveToNext(); 
     } 
    } 
    cursor.close(); 
    return cats_from_db; 

} 

和這裏的錯誤:

Failed to read row 1, column 1 from a CursorWindow which has 2 rows, 1 columns.  

java.lang.IllegalStateException: Couldn't read row 1, col 1 from 
CursorWindow. Make sure the Cursor is initialized correctly before 
accessing data from it. 

我不是真的那麼偉大與數據庫,所以我真的很苦惱,我已經成功地添加到數據庫,但無法弄清楚如何獲取數據。如果有人可以幫助它將不勝感激,謝謝! :)

+1

明顯'Cursor.getString(INT)'需要字段(列)數量沒有行號作爲參數 – Selvin

回答

1

問題是get_all_Categories你試圖拿錯列索引嘗試下面的代碼

public ArrayList<String> get_all_Categories() 
{ 

    String get_Cats_Query = "SELECT item_category from " + TABLE_ITEMS; 
    Cursor cursor = getReadableDatabase().rawQuery(get_Cats_Query, null); 

    ArrayList<String> cats_from_db = new ArrayList<String>() {}; 
    if(cursor.moveToFirst()) 
    { 
     do{ 
      cats_from_db.add(cursor.getString(0)); 
     } 
     while(cursor.moveToNext()); 
    } 
    cursor.close(); 
    return cats_from_db; 

} 

而且你的代碼完全不必要的循環,從而獲得從數據庫實際上重寫ArrayList中的數據不知道你想什麼做

+0

呀,當我相當疲憊哈哈整理,現在這個循環進行編碼。非常感謝你的回答,你是一個真正的救星。我現在唯一的問題是它將類別和標題保存到ArrayList中?任何想法可能會導致這種情況? –

+0

創建自定義對象的數組列表檢查這個,你會得到一個想法https://stackoverflow.com/questions/15377312/create-new-object-in-arraylist-with-attributes – Pavan

+0

所以我應該做一個自定義對象列表,然後調用數據填充如下:ArrayList ListName.add(get_all_categories(),get_all_vendors(),method3()); ?難道這仍然不會拉動同樣的數據壽命,所以仍然拉動類別應該是的標題? –

相關問題