Ale*_*len 6 android gson kotlin android-room
我正在尝试将此对象保存在 Room 数据库中,我读到了有关 Typeconverters 的信息,用于转换一个可以存储在数据库中的文件中的复杂对象。我收到此错误: 错误:不确定如何将游标转换为该方法的返回类型 (androidx.lifecycle.LiveData>).---- public abstract 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("", "")
}
Run Code Online (Sandbox Code Playgroud)
我的 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>>
}
Run Code Online (Sandbox Code Playgroud)
我的数据库类:
@Database(entities = [Question::class], version = 1)
@TypeConverters(Converter::class)
abstract class AppDatabase : RoomDatabase(){
abstract fun questionDao(): QuestionDao
}
Run Code Online (Sandbox Code Playgroud)
我的转换器类:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
您遇到的问题是由使用 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"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7016 次 |
最近记录: |