如何在房间中获取特定实体

时间:2019-07-07 01:06:13

标签: android kotlin android-room android-query

enter image description here

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

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

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

代码如下:

实体:

@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)
    }

    ...
}

1 个答案:

答案 0 :(得分:0)

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

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

但如果您要致电

val users = mViewModel.getAllUsers()

结果将为空

相关问题