我正在尝试将这个对象保存到Room数据库中,我了解到可以使用TypeConverters将复杂对象转换为一个字段,从而可以存储在数据库中。但是我遇到了以下错误:
error: Not sure how to convert a Cursor to this method's return type (androidx.lifecycle.LiveData>).---- public abstract androidx.lifecycle.LiveData> queryQuestions(@org.jetbrains.annotations.NotNull()
我的代码是基于我在解决与room对象转换的类似问题时找到的解决方案,但对我来说不起作用。
我的Question类:
@Entity
data class Question(@PrimaryKey var questionId: String = "",
val uid: String,
val name: String,
val photo: String,
val question: String,
val points: Int,
@ServerTimestamp val timestamp: Date? = null,
val options: ArrayList<Option>){
constructor(): this("", "", "", "", "", 0, null, ArrayList())
}
data class Option(val optionText: String,
val correct: Boolean,
var votes: Int = 0,
var usersVoted: ArrayList<UserVoted> = ArrayList()){
constructor(): this("", false /*,0, ArrayList()*/)
}
data class UserVoted(val name: String,
val photo: String){
constructor(): this("", "")
}
我的dao类:
@Dao
interface QuestionDao {
@Insert(onConflict = REPLACE)
fun insertQuestions(question: ArrayList<Question>)
@Query("SELECT * FROM question WHERE uid = :userId")
fun queryQuestions(userId: String): LiveData<ArrayList<Question>>
}
我的数据库类:
@Database(entities = [Question::class], version = 1)
@TypeConverters(Converter::class)
abstract class AppDatabase : RoomDatabase(){
abstract fun questionDao(): QuestionDao
}
我的转换器类:
class Converter {
@TypeConverter
fun fromTimestampToDate(value: Long?): Date? {
return value?.let { Date(it) }
}
@TypeConverter
fun fromDateToTimestamp(date: Date?): Long? {
return date?.time?.toLong()
}
@TypeConverter
fun fromStringToArrayList(value: String): ArrayList<Option> {
Log.i("alengenije", "fromStringToArrayList string = $value")
val listType = object:TypeToken<ArrayList<Option>>() {}.type
return Gson().fromJson(value, listType)
}
@TypeConverter
fun fromArrayLisrToString(list: ArrayList<Option>): String {
val gson = Gson()
return gson.toJson(list)
}
}