Android Room错误:无法识别枚举列表的TypeConverter

前端之家收集整理的这篇文章主要介绍了Android Room错误:无法识别枚举列表的TypeConverter前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Room库无法识别我为枚举列表创建的TypeConverter.但是,当我将其更改为枚举的ArrayList时,它工作正常.任何人都知道为什么以及我该怎么做才能使这个工作与List? (在Kotlin中使用List更容易,我真的不想因为这个原因而转换回ArrayList).

这是我的代码

我的模特:

@Entity
data class Example(@PrimaryKey val id: String?,val name: String,var days: List<DayOfWeek>?)

DayOfWeek是一个枚举:

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

    }

}

我的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()) }
    }

}

我将它设置在我的DB类中,如下所示:

@Database(entities = arrayOf(Example::class),version = 1)
@TypeConverters(DayOfWeekConverter::class)
abstract class AppDatabase : RoomDatabase() {

    abstract fun exampleDao(): ExampleDao

}

我的DAO看起来像这样:

@Dao
interface ExampleDao {

    @Query("SELECT * FROM example")
    fun getAll(): LiveData<List<Example>>

    @Insert(onConflict = REPLACE)
    fun save(examples: List<Example>)

}

我用这段代码得到的错误是:

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;

就像我上面说的,如果我将days属性更改为ArrayList< DayOfWeek> (并在DayOfWeekConverter中对ArrayList进行更改)然后一切正常.如果有人能帮我解决这个问题并告诉我如何在这里使用List它会有很大的帮助,它让我发疯:/.

解决方法

出于某种原因,Room不喜欢Kotlin List,但是当我用MutableList替换List时,它开始工作:
@Entity
data class Example(@PrimaryKey val id: String,var days: MutableList<DayOfWeek>?)

class DayOfWeekConverter {
    companion object {

        @TypeConverter
        @JvmStatic
        fun daysOfWeekToString(daysOfWeek: MutableList<DayOfWeek>?): String? =
                daysOfWeek?.map { it.value }?.joinToString(separator = SEPARATOR)

        @TypeConverter
        @JvmStatic
        fun stringToDaysOfWeek(daysOfWeek: String?): MutableList<DayOfWeek>? =
                daysOfWeek?.split(SEPARATOR)?.map { DayOfWeek.of(it.toInt()) }?.toMutableList()
    }
}

这不是完美的解决方案,但希望您可以通过它进行更多调查.

您还需要将@PrimaryKey更改为不可为空

原文链接:https://www.f2er.com/android/317993.html

猜你在找的Android相关文章