Room数据库查询没有返回数据,即使数据库中有数据。

3
我正在DAO类中使用这种方法来访问数据库中的数据:
@Query("select * from location_search_results WHERE searchQuery = :query")
fun searchForLocation(query: String): LiveData<LocationSearchResponse>

"我是这样调用它的:"
locationResponse = locationResponseDao.searchForLocation(query)
Log.d("db", locationResponse.value.toString())

我接着这样观察这个值:
    fun bindUI() = launch {
        val locationResults = locationViewModel.locationResponse
        val owner = viewLifecycleOwner

        locationResults.observe(owner, Observer {
            if (it == null) return@Observer

            initRecyclerView(it.features.toLocationSearchResultListItem())
        })
    }

我的问题是,无论我做什么,观察者始终返回null,即使数据库中有与查询匹配的数据。我也尝试过只使用“select * from location_search_results”以确定是否存在searchQuery参数的问题,但结果仍然是null。
这是数据库的样子:

database

我对Room和SQLite都很陌生,所以非常感谢任何帮助。谢谢。

locationResponse.value. 嗯,不要这样调用它,使用 observe - undefined
你必须观察LiveData,因为在执行Log.d时,LiveData的值仍然为null。这是因为Android在不同的线程中运行查询。 - undefined
我稍后会观察数据,如果它仍然为空,抱歉我已经编辑了帖子以澄清 - undefined
1个回答

0

由于您从Room查询中返回LiveData,因此应该观察以获取值。 类似这样: locationResponseDao.searchForLocation(query).observeForever{ response -> locationResponse.value = response

}


我稍后会观察它,对于造成的困惑我表示道歉。我已经编辑了问题,并提供了更多信息以澄清。 - undefined
不,我的意思是你需要在视图模型中观察。请看我的更新答案。 - undefined
这会改变它为空的事实吗?为什么改变观察者的位置会使返回的数据不同?我是真心问的,因为我有另一组基本上和这个做完全相同事情的类,它将观察者放在片段类中,而且一切都正常工作。 - undefined
不,我的意思是先观察视图模型中的LiveData并更新对象。我没有说要删除片段观察者代码。基本上,片段观察者观察视图模型LiveData,后者从视图模型可变数据中得到更新。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接