android - 房间查询不起作用

标签 android android-room android-architecture-components android-livedata android-architecture

我正在尝试在我的项目中将RoomLiveData结合使用。在我的应用程序中,我有 authors 表。数据插入得很好,但是当我尝试从表中读取某些内容时,它没有给我记录。我还使用 SQLite Opener 软件查看数据库。它向我显示了所有数据。

下面是我的作者实体。

@Entity(tableName = "authors")
    data class AuthorModel(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id") val id: Long = 0,
    @ColumnInfo(name = "name") var name: String
)

这是我的 Author Dao 界面。

@Dao
interface AuthorDao {

    @Query(value = "SELECT * FROM authors")
    fun allAuthors(): LiveData<List<AuthorModel>>

    @Query(value = "SELECT * FROM authors WHERE id = :authorId")
    fun authorWithId(authorId: Long): LiveData<AuthorModel?>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(author: AuthorModel): Long

}

最后,这是我的 RoomDatabase 类。

@Database(entities = [AuthorModel::class], version = 1)
abstract class BookLibraryDatabase : RoomDatabase() {

abstract fun authorDao(): AuthorDao

}

感谢您的宝贵时间。

最佳答案

你必须观察LiveData。第一次获取时livedata.value将为null。

关于android - 房间查询不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51579976/

相关文章:

android - 在 iOS 和 Android 中使用 facebook 登录会给出不同的 id。如何处理服务器端?

java - 如何更改子 Activity 中startActivityForResult的响应代码

android - 新行的损坏插入 ID

Android:我已经删除了我的数据,但房间里仍然存在一些数据

android - LiveData 没有将数据从一个 Activity 更新到另一个 Activity - Android

android - View 绑定(bind)出现错误 : incompatible with attribute android:visibility

android - 需要帮助 Kotlin Coroutines、Architecture Component 和 Retrofit

android - 如何为 OkHttp Android 设置陈旧时间?

android - 检查按钮是否被点击

java - Room Insert 仅插入主键而不插入列