【问题标题】:Storing enum with room database gives error even with TypeConverters即使使用 TypeConverters,使用房间数据库存储枚举也会出错
【发布时间】:2018-07-25 04:19:41
【问题描述】:

我遵循了关于如何为自定义类型添加 TypeConverters 的房间文档,但我的实体类仍然出现错误。我想简单地将Category 枚举转换为String,以便房间数据库了解如何存储它。下面,每个Exercise 都有一个类别,这就是发生错误的地方。这是我的课程:

转换器

public class Converter {
    @TypeConverter
    public static String fromCategoryToString(Category category) {
        if (category == null)
            return null;
        return category.toString();
    }
}

分类

public enum Category {
    EXERCISE("Exercise"),
    REST("Rest"),
    COUNTDOWN("Countdown");

    private final String text;

    Category(final String text) {
        this.text = text;
    }

    @Override
    public String toString() {
        return text;
    }
}

锻炼。为简洁起见,移除了 getter 和 setter。

@Entity(tableName = "exercise",
        foreignKeys = @ForeignKey(entity = Routine.class,
                parentColumns = "rid",
                childColumns = "routineId",
                onDelete = ForeignKey.CASCADE),
        indices = {@Index(value = "name", unique = true), @Index("routineId")})
public class Exercise {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "eid")
    private int exerciseID;

    @ColumnInfo(name = "category")
    private Category category; // error occurs here

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

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

    public Exercise(Category category, @NonNull String name) {
        this.category = category;
        this.name = name;
    }

}

数据库

@Database(entities = { Routine.class, Exercise.class}, version = 1)
@TypeConverters({ Converter.class })
public abstract class AppDatabase extends RoomDatabase {
    private static AppDatabase instance;
    private static final String dbName = "routines.db";

    public abstract RoutineDao routineDao();
    public abstract ExerciseDao exerciseDao();

    public static AppDatabase getInstance(final Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, dbName).build();
        }
        return instance;
    }


}

【问题讨论】:

    标签: java android android-room


    【解决方案1】:

    您还需要编写相反的转换方式。

    例如

    @TypeConverter
        public static Category fromStringToCategory(String category) {
            if (TextUtil.isEmpty(category))
                return DEFAULT_CATEGORY;
            return YOUR_LOGIC_FOR_CONVERSION;
        }
    

    【讨论】:

      猜你喜欢
      • 2022-11-11
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      • 2019-05-21
      • 2019-04-22
      • 1970-01-01
      相关资源
      最近更新 更多