Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing enum with room database gives error even with TypeConverters

I've followed the room documentation on how to add TypeConverters for custom types, but I still get an error from my entity class. I'd like to simply convert the Category enum to a String so the room database understands how to store it. Below, every Exercise has a category, and this is where the error occurs. Here are my classes:

Converter

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

Category

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

Exercise. Getters and setters removed for brevity.

@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

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


}
like image 836
Kevin Chan Avatar asked Oct 18 '25 07:10

Kevin Chan


1 Answers

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;
    }
like image 74
theJango Avatar answered Oct 20 '25 22:10

theJango