Android Studio Room Type Converter的问题

时间:2018-04-09 17:20:32

标签: java android

出于某种原因,我在Android工作室遇到了类型转换器的问题。我已尝试过其他帖子的各种解决方案,但仍然会收到此错误。当我尝试字符串的Arraylist而不是成分时,typeconverter确实有效。

error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

@Entity(tableName = "Recipes")
    public class recipesDB {
        @PrimaryKey
        @NonNull
        @ColumnInfo(name = "recipeID")
        private int id;

    //Foreign Key to be used from Ingredients
    @ColumnInfo(name = "name")
    private String name;

    @ColumnInfo(name = "url")
    private String url;

    @ColumnInfo(name = "readyInMinutes")
    private int readyInMinutes;

//Issue Here
@ColumnInfo(name = "ingredients")
private ArrayList<ingredient> ingredients;

DataConverter类:

public class DataConverter{


    @TypeConverter
    public static ArrayList<ingredient> toIngredient(String s){
        if(s == null){
            return null;
        }

        Gson gson = new Gson();
        Type listType = new TypeToken<ArrayList<ingredient>>(){}.getType();
        ArrayList<ingredient> ingredients = gson.fromJson(s, listType);
        return ingredients;
    }

    @TypeConverter
    public static String getIngredients(ArrayList<ingredient> ingredients){
        if(ingredients == null){
            return null;
        }

        Gson gson = new Gson();
        Type type = new TypeToken<ArrayList<ingredient>>() {}.getType();
        String json = gson.toJson(ingredients);
        return json;
    }

修改 AppDatabase:

@Database(entities = {recipesDB.class}, version = 1, exportSchema = false)
@TypeConverters({DataConverter.class})
public abstract class AppDatabase extends RoomDatabase {
    private static AppDatabase INSTANCE;
    public abstract recipesDAO recipesdao();
    //public abstract pantryDAO pantrydao();
    public static AppDatabase getInMemoryDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE = Room.inMemoryDatabaseBuilder(context.getApplicationContext(), AppDatabase.class).build();
        }
        return INSTANCE;
    }
    public static void destroyInstance(){INSTANCE = null;}
}

2 个答案:

答案 0 :(得分:0)

新的答案原来,将ingredient重命名为Ingredient解决了问题(??)所以...可能会关注这些类名并遵循Java惯例ClassNamesStartWithUpperCase

OLD ANSWER:

我认为,您可能需要为ingredient创建单独的“实体”(就像recipesDB一样)。

然后ingredient@ForeignKey设置回recipesDB

最后,您可以添加 POJO 以同时拥有recipesDBArrayList<Ingredient>

我这里没有样品,但我在网上看过一堆。

我认为问题是你的“转换器”不知道如何转换“成分”。它知道如何转换List<Ingredient>,但它不是一回事。 ;)

答案 1 :(得分:0)

因此问题的原因是由于当前文件夹目录范围之外的重复成分类。通过将类成分更改为成分,它必须清除Room的混乱。