将rawQuery的结果转换为对象

时间:2019-09-17 15:27:03

标签: android android-sqlite

我试图获取一个Object数组,查询返回大小15,但在其内部显示“所有对象均为空”。我不知道我在做什么错。我在Google上搜索了一下,但没有找到任何东西。

public ArrayList<IngredientType> ingredientsTypeAll(){
        ArrayList<IngredientType> returnArray = new ArrayList<>();
        Cursor cursor = db.rawQuery("SELECT code, cod_category, name FROM recipe_tags_master",null);
        cursor.moveToFirst();
        while(!cursor.isAfterLast()) {
            returnArray.add((IngredientType) this.cursorToEntity(cursor));
            cursor.moveToNext();
        }
        cursor.close();
        return  returnArray;
    }

实体是这样的:

public class IngredientType {

    private int code;
    private int code_category;
    private String name;

    public IngredientType(int code, int code_category, String name) {
        this.code = code;
        this.code_category = code_category;
        this.name = name;
    }

    public int getCode() {
        return code;
    }

    public int getCode_category() {
        return code_category;
    }

    public String getName() {
        return name;
    }
}

1 个答案:

答案 0 :(得分:1)

我不知道此呼叫的作用:

(IngredientType) this.cursorToEntity(cursor)

在循环的每次迭代中,您必须创建一个新的IngredientType对象并将其添加到列表中:

public ArrayList<IngredientType> ingredientsTypeAll() {
    ArrayList<IngredientType> returnArray = new ArrayList<>();
    Cursor cursor = db.rawQuery("SELECT code, cod_category, name FROM recipe_tags_master", null);
    while (cursor.moveToNext()) {
        returnArray.add(
            new IngredientType(
                cursor.getInt(cursor.getColumnIndex("code")),
                cursor.getInt(cursor.getColumnIndex("cod_category")),
                cursor.getString(cursor.getColumnIndex("name"))
            )
        );
    }
    cursor.close();
    return returnArray;
}

我还删除了对cursor.moveToFirst()的初始调用,因为while (cursor.moveToNext())就足够了。