The Room library does not recognize the TypeConverter that I created for the List enumerations. However, when I change this to an ArrayList enumerations, it works fine. Does anyone know why and what can I do to make this work with List ? (Using List in Kotlin is simpler, and I really don't want to convert back and forth to ArrayList just because of this).
Here is my code:
My model:
@Entity data class Example(@PrimaryKey val id: String?, val name: String, var days: List<DayOfWeek>?)
DayOfWeek is an enumeration:
enum class DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; val value: Int get() = ordinal + 1 companion object { private val ENUMS = DayOfWeek.values() fun of(dayOfWeek: Int): DayOfWeek { if (dayOfWeek < 1 || dayOfWeek > 7) { throw RuntimeException("Invalid value for DayOfWeek: " + dayOfWeek) } return ENUMS[dayOfWeek - 1] } } }
My TypeConverter :
private const val SEPARATOR = "," class DayOfWeekConverter { @TypeConverter fun daysOfWeekToString(daysOfWeek: List<DayOfWeek>?): String? { return daysOfWeek?.map { it.value }?.joinToString(separator = SEPARATOR) } @TypeConverter fun stringToDaysOfWeek(daysOfWeek: String?): List<DayOfWeek>? { return daysOfWeek?.split(SEPARATOR)?.map { DayOfWeek.of(it.toInt()) } } }
And I installed it in my DB class as follows:
@Database(entities = arrayOf(Example::class), version = 1) @TypeConverters(DayOfWeekConverter::class) abstract class AppDatabase : RoomDatabase() { abstract fun exampleDao(): ExampleDao }
My DAO looks like this:
@Dao interface ExampleDao { @Query("SELECT * FROM example") fun getAll(): LiveData<List<Example>> @Insert(onConflict = REPLACE) fun save(examples: List<Example>) }
Error with this code:
error: Cannot figure out how to save this field into database. You can consider adding a type converter for it. e: e: private java.util.List<? extends com.example.DayOfWeek> days;
As I said above, if you change the days property to ArrayList<DayOfWeek> (and make changes to ArrayList in DayOfWeekConverter ), then everything will be fine. If anyone can help me figure this out and tell me how I can use List , it will be very useful here, it drives me crazy: /.
android kotlin android-room android-architecture-components
Franco
source share