简体   繁体   中英

How to get a specific Entity in Room

在此处输入图片说明

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

    ...
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM