我试图将此对象保存在Room数据库中,我读了有关Typeconverters的信息,该类用于将复杂对象转换为一个可以存储在数据库中的文件。我收到此错误: 错误:不确定如何将Cursor转换为此方法的返回类型(androidx.lifecycle.LiveData>)。 公共抽象androidx.lifecycle.LiveData> queryQuestions(@ org.jetbrains.annotations.NotNull() 我的代码基于我发现的解决方案,这些解决方案在将对象转换为空间时遇到类似问题,但这对我不起作用。
我的问题课:
@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
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)
}
}
答案 0 :(得分:0)
您遇到的问题是由于使用LiveData引起的。 支持库从Android API 28移至androidx 这意味着您必须将所有内容移至androidx。 您的问题在于build.gradle文件。 您可能在那里有andoidx生命周期,但Room lib是旧的1.1.1 Room lib。 您应该像这样更新所有支持库以使用androidx:
def lifecycle_version = "2.0.0"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.0'
// Add RecyclerView dependency; must match SDK version
implementation 'androidx.recyclerview:recyclerview:1.0.0'
// Add FAB dependency
implementation 'com.google.android.material:material:1.0.0-rc01'
def room_version = "2.1.0-alpha07"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
答案 1 :(得分:0)
将ArrayList
更改为List
。
对我有用。