2017-06-14 50 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()); ?难道这仍然不会拉动同样的数据寿命,所以仍然拉动类别应该是的标题? –

相关问题