gpt4 book ai didi

java - 使用房间数据库存储枚举即使使用 TypeConverters 也会出错

转载 作者:行者123 更新时间:2023-11-30 07:45:40 27 4
gpt4 key购买 nike

我已按照有关如何为自定义类型添加 TypeConverter 的房间文档进行操作,但我的实体类仍然出现错误。我想简单地将 Category 枚举转换为 String,以便房间数据库了解如何存储它。下面,每个 Exercise 都有一个类别,这就是错误发生的地方。这是我的类(class):

转换器

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


}

最佳答案

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

例如

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

关于java - 使用房间数据库存储枚举即使使用 TypeConverters 也会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510725/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com