我已經遵循了有關如何為自定義類型添加 TypeConverters 的房間文檔,但我仍然從我的實體類中收到錯誤消息。我想簡單地將Category枚舉轉換為 a,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; }}
1 回答

互換的青春
TA貢獻1797條經驗 獲得超6個贊
您還需要以相反的方式編寫轉換。
例如
@TypeConverter
public static Category fromStringToCategory(String category) {
if (TextUtil.isEmpty(category))
return DEFAULT_CATEGORY;
return YOUR_LOGIC_FOR_CONVERSION;
}
添加回答
舉報
0/150
提交
取消