简体   繁体   English

Room DAO 不断返回 NULL

[英]Room DAO keeps returning NULL

In room , I have a dao to something like this:room中,我有一个 dao 是这样的:

@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.但问题是它返回给我null但是当我在检查器中运行该查询时它起作用了。 Am I missing something?我错过了什么吗?

在此处输入图像描述

在此处输入图像描述

LiveData doesn't immediately have an initial value. LiveData 不会立即具有初始值。 Room queries the database and gets the result on a background thread. Room 查询数据库并在后台线程上获取结果。 Then on the next loop of the main thread, the LiveData's value will be set to this retrieved value.然后在主线程的下一个循环中,LiveData 的value将设置为此检索到的值。 You are logging value too early.您过早记录value The initial value is going to appear some time in the future, after this function has already returned.初始值将在未来某个时间出现,在这个 function 已经返回之后。

Normally you should only be getting a LiveData value through observing it.通常你应该只通过观察它来获得一个 LiveData 值。

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.直接检查value通常只应在您管理 MutableLiveData 并使用先前的值来帮助确定您要发布的下一个值时进行。

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.如果你想看到一些实时数据,你必须观察它,以便在收到信息后,观察者会被调用并记录信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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