我已经关注了有关如何为自定义类型添加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和Setters。
@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;
}
}
答案 0 :(得分:1)
You need to write the other way round conversion also.
e.g
@TypeConverter
public static Category fromStringToCategory(String category) {
if (TextUtil.isEmpty(category))
return DEFAULT_CATEGORY;
return YOUR_LOGIC_FOR_CONVERSION;
}