How to get a specific Entity in Room

半腔热情 提交于 2020-01-06 06:31:48

问题


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:

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?

Here's the code:

Entity:

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

   ...
}

Repository:

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:


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

but if you will call

val users = mViewModel.getAllUsers()

the result will be null



来源:https://stackoverflow.com/questions/56918707/how-to-get-a-specific-entity-in-room

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!