无法从CursorWindow读取第1行第1列?

时间:2017-06-14 08:08:17

标签: android sqlite android-sqlite

我只想从我的数据库中提取所有类别:

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中,然后传递给我的Activity中的微调器。这是我要求数据的地方:

    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 个答案:

答案 0 :(得分: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;

}

此外,你的代码完全不必要的循环来从db获取数据,这实际上覆盖了你的arraylist不明白你想要做什么