如何在房间中获取特定实体 [英] How to get a specific Entity in Room

查看:106
本文介绍了如何在房间中获取特定实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在使用Room数据库存储课程,而且我坚持使用以我想要的名称(课程)返回课程的方法,因为它总是返回null.我已将数据库减少为2门课程,其课程变量为:

So, I'm using Room database to store courses and I'm stuck on the method that returns the course with the name(course) that I want because it's always returning null. I have diminished my database to have 2 courses with the course variable as:

如上图所示,当我尝试使用course = fun在存储库中获取CourseEnt时(我可以在下面看到它存在),它将返回一个具有空值的LiveData而不是我所返回的CourseEnt想要的.

As you can see in the picture above, when I try to get the CourseEnt in the Repository with course = fun, which I can see below that it exists, it returns a LiveData with a null value instead of the CourseEnt that I wanted.

关于我做错了什么或应该如何使用调试器的任何想法?

Any idea on what I'm doing wrong or on what should I look into with debugger?

代码如下:

实体:

@Entity(tableName = "courses_table")
data class CoursesEnt (@PrimaryKey val course: String, 
                                   val location: String, 
                                   val description: String,                           
                                   val difficulty: Double, 
                                   val distance: Double, 
                                   val photos: ListInt, 
                                   val category: String, 
                                   val activities: ListString)//ListString is a type converter that converts a String into a List<String> and vice-versa

DAO:

@Dao
interface CoursesDao {

   @Query("SELECT * from courses_table ORDER BY course ASC")
    fun getAllCourses(): LiveData<List<CoursesEnt>>

   @Query("SELECT * FROM courses_table WHERE course LIKE :str")
    fun getCourse(str: String):LiveData<CoursesEnt>

   ...
}

存储库:

class CoursesRepository(private val coursesDao: CoursesDao){

    val allCourses: LiveData<List<CoursesEnt>> = coursesDao.getAllCourses()
    var singleCourse: LiveData<CoursesEnt> = coursesDao.getCourse("")

    @WorkerThread
    fun getCourse(str: String) {

        singleCourse = coursesDao.getCourse(str)
    }

    ...
}

推荐答案

阅读文档,liveData将始终返回null以进行直接调用,您必须观察LiveData,来自Room的结果值将处于阻塞状态.这是用法的一个例子

Read documentation, liveData will always return null for straight call, you have to observe LiveData, the result value from Room will be in block. This is some example of usage

mViewModel.getAllUsers().observe( this@YourActivity, Observer {
        // it - is all users from DB
    })

但是如果您要致电

val users = mViewModel.getAllUsers()

结果将为空

这篇关于如何在房间中获取特定实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆