Home > Net >  Room DAO keeps returning NULL
Room DAO keeps returning NULL

Time:01-22

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?

enter image description here

enter image description here

CodePudding user response:

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.

CodePudding user response:

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.

  • Related