gpt4 book ai didi

android - 如何从 Room 获取 LiveData?

转载 作者:行者123 更新时间:2023-11-29 16:30:07 25 4
gpt4 key购买 nike

我正在尝试从 Room 获取 LiveData。因此,如果数据库中的任何内容发生更改,我的 RecycleView 可以进行实时更新

我试过不使用 LiveData 并且可以正常工作,但是当我添加 LiveData 时总是显示此错误。

error: Not sure how to convert a Cursor to this method's return type     (androidx.lifecycle.LiveData<java.util.List<com.example.models.Club>>).
public abstract java.lang.Object getAll(@org.jetbrains.annotations.NotNull()

我用谷歌搜索并在这个网站上寻找解决方案,但遇到这个问题的每个人都使用了 rxjava、rxandroid、rxkotlin 或 ArrayList。对他们来说,解决方案是用 List 替换 ArrayList,并让 RX 尝试协程。好吧,我正在使用 Coroutine 和 List,但仍然没有任何进展。

这是我的 ClubDao

ClubDao
@Query("SELECT * FROM club")
suspend fun getAll(): LiveData<List<Club>>

在俱乐部我有这个属性

Club
@Entity
data class Club(@PrimaryKey var id: Int,
@ColumnInfo(name = "logo_url") var logoUrl: String,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "town") var town: String,
@ColumnInfo(name = "address") var address: String,
@ColumnInfo(name = "contact_name") var contactName: String,
@ColumnInfo(name = "phone_numbers") var phoneNumbers: String,
@ColumnInfo(name = "email") var email: String)

phoneNumbers 应该是 List,但我使用 TypeConverters 将它们与 json 相互转换

TypeConverter 在这里

TypeConverter
class ConvertersDB {
@TypeConverter
fun fromString(value: String): ArrayList<String> {
val listType = object : TypeToken<ArrayList<String>>() {

}.type
return Gson().fromJson(value, listType)
}

@TypeConverter
fun fromArrayList(list: ArrayList<String>): String {
val gson = Gson()
return gson.toJson(list)
}
}

还有我的数据库

DataBase
@Database(entities = [Club::class], version = 1, exportSchema = false)
@TypeConverters(ConvertersDB::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun clubDao(): ClubDao

companion object {
@Volatile
private var instance: AppDatabase? = null
private val LOCK = Any()

operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
instance ?: buildDatabase(context).also { instance = it }
}

private fun buildDatabase(context: Context) = Room.databaseBuilder(context,
AppDatabase::class.java, "pss.db")
.allowMainThreadQueries()
.build()
}
}

在我的 fragment 中,我需要通过 ViewModel 和 Repository 从数据库中观察所有俱乐部,并将它们发送到 RecycleView

现在我得到错误:

error: Not sure how to convert a Cursor to this method's return type     (androidx.lifecycle.LiveData<java.util.List<com.example.models.Club>>).
public abstract java.lang.Object getAll(@org.jetbrains.annotations.NotNull()

有人知道这个的解决方案吗?

编辑:

Gradle
apply plugin: 'com.android.application'
apply plugin: 'androidx.navigation.safeargs'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'


android {
compileSdkVersion 28
defaultConfig {
applicationId "com.overswayit.plesnisavezsrbije"
minSdkVersion 24
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
dataBinding {
enabled true
}
packagingOptions {
exclude 'META-INF/atomicfu.kotlin_module'
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.31"
implementation 'com.jakewharton:butterknife:10.1.0'
implementation 'com.google.android.material:material:1.1.0-alpha07'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.appcompat:appcompat:1.1.0-beta01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'

// Room components
implementation "androidx.room:room-runtime:$rootProject.roomVersion"
implementation "androidx.room:room-ktx:$rootProject.roomVersion"
kapt "androidx.room:room-compiler:$rootProject.roomVersion"
androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"

// Room and RxJava
implementation "androidx.room:room-rxjava2:$rootProject.roomVersion"

// Lifecycle components
implementation "androidx.lifecycle:lifecycle-extensions:$rootProject.archLifecycleVersion"
kapt "androidx.lifecycle:lifecycle-compiler:$rootProject.archLifecycleVersion"
androidTestImplementation "androidx.arch.core:core-testing:$rootProject.androidxArchVersion"

// ViewModel Kotlin support
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$rootProject.archLifecycleVersion"

//LiveData Kotlin
implementation "androidx.lifecycle:lifecycle-livedata:$rootProject.archLifecycleVersion"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$rootProject.archLifecycleVersion"

implementation "androidx.lifecycle:lifecycle-runtime-ktx:$rootProject.archLifecycleVersion"

// Coroutines
api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.coroutines"
api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.coroutines"

//RxJava
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation "io.reactivex.rxjava2:rxjava:2.2.6"
implementation 'com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2'

implementation "org.jetbrains.kotlin:kotlin-stdlib:1.3.31"
annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.kaopiz:kprogresshud:1.0.5'
implementation 'com.squareup:otto:1.3.8'
implementation 'agency.tango.android:avatar-view:0.0.2'
implementation 'agency.tango.android:avatar-view-picasso:0.0.2'
implementation 'com.mikhaellopez:circularimageview:3.2.0'
implementation 'com.googlecode.libphonenumber:libphonenumber:8.1.0'

// Data Binding
kapt "com.android.databinding:compiler:3.1.4"

testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation project(path: ':tuple')

// Navigation Component
implementation 'androidx.navigation:navigation-fragment-ktx:2.0.0'
implementation 'androidx.navigation:navigation-ui-ktx:2.0.0'

//Gson
implementation 'com.google.code.gson:gson:2.8.5'
}

kapt {
generateStubs = true
}

顶级 Gradle

buildscript {

repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.31"
classpath "android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0"


// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
google()
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

ext {
roomVersion = '2.1.0'
archLifecycleVersion = '2.2.0-alpha01'
androidxArchVersion = '2.0.0'
coroutines = '1.2.0'
}

最佳答案

如评论中所述,删除suspend。当一个方法返回一个可观察对象时,没有理由让它暂停,因为它只是返回和对象,在被观察之前不会运行任何查询。

@Query("SELECT * FROM club")
fun getAll(): LiveData<List<Club>>

Room 的协程集成带来了返回挂起值的能力,但是当值本身是 asnyc 时,没有理由使用它。

关于android - 如何从 Room 获取 LiveData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56833407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com