首页 > 解决方案 > 获取数组列表来自 SQLite

问题描述

我将我的 ArrayList 保存在 SQLite 中。保存代码:

public void HistoryADD(ArrayList<String> full, String owner){
    int size = full.size();
    SQLiteDatabase db = getWritableDatabase();
    try{
        for (int i = 0; i < size ; i++){
            ContentValues cv = new ContentValues();
            cv.put(FULL, full.get(i));
            cv.put(OWNER, owner);
            db.insert(TABLE_NAME, null, cv);
        }
        System.out.println("added:" + full);
        db.close();
    }catch (Exception e){
        System.out.println("Failed to add" + full);
    }
}

它正在工作。我想从 SQLite 获取这个 ArrayLists。清单代码:

 public ArrayList<String> History_list(String owner) {
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<String> history_list = new ArrayList<>();

    Cursor cursor = db.rawQuery("SELECT * from " + TABLE_NAME + " WHERE owner='"+owner+"'",
            new String[] {});

    cursor.close();
    return history_list;
}

但列表代码不起作用。这段代码有什么问题?谢谢。

标签: javaandroidandroid-sqlite

解决方案


你需要做这样的事情:

Cursor cursor = db.rawQuery(...);
try {
    while (cursor.moveToNext()) {
        //Here you have to add the item in your array list

    }
} finally {
    cursor.close();
}

推荐阅读