简体   繁体   中英

Room DAO keeps returning NULL

In room , I have a dao to something like this:

@Dao
interface FacultyDao {
    @Query("select * from faculty")
    fun getAll(): LiveData<List<Faculty>>
  
    ...
}

And inside the repository, I'm simply calling this method and logging it:

class FacultyRepository(application: Application) {

    private val facultyDao: FacultyDao

    init {
        val db: AppDB = AppDB.getInstance(application)
        facultyDao = db.facultyDao()
    }

    fun getAllFaculty(): LiveData<List<Faculty>> {
        val v = facultyDao.getAll()
        Log.d("muaxx", v.value.toString())
        return v
    }
     ...

}

But the thing is it's returning me null , but when I ran that query in inspector it worked. Am I missing something?

在此处输入图像描述

在此处输入图像描述

LiveData doesn't immediately have an initial value. Room queries the database and gets the result on a background thread. Then on the next loop of the main thread, the LiveData's value will be set to this retrieved value. You are logging value too early. The initial value is going to appear some time in the future, after this function has already returned.

Normally you should only be getting a LiveData value through observing it.

Directly checking the value should usually only be done when you are managing a MutableLiveData and are using the previous value to help determine the next value that you are going to post.

Live data gives us real-time data. Therefore, for the first time, you still don't have some in yourself. And it is waiting for the response of the database. If you want to see some of the live data, you must observe it so that after receiving the information, the observer will be called and the information will be logged.

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