错误:无法弄清楚如何将该字段保存到数据库中。 :科特林厅

时间:2019-12-23 18:31:47

标签: android kotlin android-room

我已经阅读了教程和答案,但是某种程度上它对我不起作用。

这是我要工作的数据类:

@Entity
data class Base (
    var version: Int,
    @TypeConverters(MoviesConverter::class)
    var movies: List<Movie>,
    @TypeConverters(ResStringsConverter::class)
    var strings : HashMap<String, String>
) {
    @PrimaryKey
    var id = 1
}

这是我的两个转换器:

class MoviesConverter {
    private val gson = Gson()

    @TypeConverter
    fun toMovies(data: String?): List<Movie> {
        if (data == null) {
            return emptyList()
        }
        val listType = object : TypeToken<List<Movie>>(){}.type
        return gson.fromJson(data, listType)
    }

    @TypeConverter
    fun fromMovies(movies: List<Movie>): String {
        return gson.toJson(movies)
    }
}

class ResStringsConverter {

    val gson = Gson()

    @TypeConverter
    fun storedStringToStrings(data: String?): HashMap<String, String> {
        if (data == null) {
            return HashMap()
        }
        val listType = object : TypeToken<HashMap<String, String>>() {}.type
        return gson.fromJson(data, listType)
    }

    @TypeConverter
    fun stringsToStoredString(strings: HashMap<String, String>): String {
        return gson.toJson(strings)
    }
}

但仍然在两个字段上都遇到相同的错误:

error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
    private java.util.List<com.vladdrummer.moviequizandroid.model.Movie> movies

1 个答案:

答案 0 :(得分:0)

使用Kotlin,您需要添加companion object@JvmStatic

已编辑TypeConverters(MoviesConverter::class)class Base

@Entity
@TypeConverters(MoviesConverter::class)
data class Base (
    @PrimaryKey
    val id : Int,
    val movies: List<Movie>
)

data class Movie(val id: Int)


class MoviesConverter {
    companion object {
        private val gson = Gson()

        @TypeConverter
        @JvmStatic
        fun toMovies(data: String?): List<Movie> {
            if (data == null) {
                return emptyList()
            }
            val listType = object : TypeToken<List<Movie>>() {}.type
            return gson.fromJson(data, listType)
        }

        @TypeConverter
        @JvmStatic
        fun fromMovies(movies: List<Movie>): String {
            return gson.toJson(movies)
        }
    }
}