TypeConverter 不适用于 android Room DB

TypeConverter not working for android Room DB

因此,我试图将字符串对列表保存到我的数据库中,但 TypeConverter 存在一些问题,我尝试按照指南和其他 SO 帖子进行操作,但无法找出问题所在...

我的实体:

@Entity
data class Credential(
    @PrimaryKey()
    val id: String,

    @ColumnInfo(name = "name")
    val name: String,

    @ColumnInfo(name = "url")
    val url: String?,

    @TypeConverters(ListPairTypeConverter::class)
    @ColumnInfo(name = "fields")
    val fields: List<Pair<String, String>>
)

我的类型转换器:

class ListPairTypeConverter {
    @TypeConverter
    fun storedStringToPairList(value: String): List<Pair<String, String>> {
        return value.split("~!!!!!~").map {
            val vals = it.split("!~~~~~!")
            Pair(vals[0], vals[1])
        }
    }

    @TypeConverter
    fun pairListToStoredString(pl: List<Pair<String, String>>): String {
        return pl.joinToString(separator = "~!!!!!~") { it.first + "!~~~~~!" + it.second }
    }
}

我的错误:

error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
    private final java.util.List<kotlin.Pair<java.lang.String, java.lang.String>> fields = null;
                                                                                  ^

您在错误的地方添加了类型转换器。而不是

@TypeConverters(ListPairTypeConverter::class)
@ColumnInfo(name = "fields")
val fields: List<Pair<String, String>>

您需要在此处添加

@Database(entities = [User::class], version = 1)
@TypeConverters(ListPairTypeConverter::class)
abstract class AppDatabase : RoomDatabase() {
  abstract fun userDao(): UserDao
}