How to get a specific Entity in Room

2019-08-30 08:25发布

问题:

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