Search code examples
javaandroidsqliteandroid-sqlite

transform the result of rawQuery to an object


Im trying to get an array of an Object and the query returns size 15, but inside it says "All objects are null". I don't know what im doing wrong. I googled a little bit but i didn't find anything.

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;
    }

and the Entity is this:

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;
    }
}

Solution

  • I don't know what this call does:

    (IngredientType) this.cursorToEntity(cursor)
    

    In each iteration of your loop you must create a new IngredientType object and add it to the list:

    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;
    }
    

    I also removed the initial call to cursor.moveToFirst(), because while (cursor.moveToNext()) is enough.