英文:
Android LiveData contains value but when assigning to variable it is null
问题
我正在从Room数据库检索数据,并将其作为LiveData<User>返回。当我将该数据放入活动中的变量中时,它显示为null,但LiveData具有值。问题是什么?
var loginCredentials: User? = null
DBUtils.with(this).getDB().userDao()
.loginValidation(accoutNo, pincode)
.observe(this) {
loginCredentials = it
Log.e("Login it", it.toString())
}
Log.e("Login variable", loginCredentials.toString())
我猜想该值位于另一个线程。我该如何解决这个问题?
英文:
I am retrieving data from Room database and returing it as LiveData<User>. When I am putting that data inside a variable in the activity it is showing null but the Live data has the value. What is the problem?
var loginCredentials: User? = null
DBUtils.with(this).getDB().userDao()
.loginValidation(accoutNo, pincode)
.observe(this) {
loginCredentials = it
Log.e("Login it", it.toString())
}
Log.e("Login variable", loginCredentials.toString())
I am guessing the value is on another thread. How can I fix this?
答案1
得分: 1
问题在于你在观察者之外显示了下面的日志:
Log.e("Login variable", loginCredentials.toString())
而且 loginCredentials 可能尚未赋值,因为 LiveData 观察者尚未触发,上面的日志语句在观察者触发之前被调用。
你需要在观察者内部执行任务,以便在 loginCredentials 变量中有值。
var loginCredentials: User? = null
DBUtils.with(this).getDB().userDao()
.loginValidation(accountNo, pincode)
.observe(this) {
loginCredentials = it
Log.e("Login it", it.toString())
Log.e("Login variable", loginCredentials.toString())
}
英文:
The problem is that you are showing the below log outside the observer
Log.e("Login variable", loginCredentials.toString())
And loginCredentials may be not assigned because livedata observer does not trigger yet, and above log statement called before the observer trigger.
You need to do your task inside the observer so that you have value in loginCredentials variable.
var loginCredentials: User? = null
DBUtils.with(this).getDB().userDao()
.loginValidation(accoutNo, pincode)
.observe(this) {
loginCredentials = it
Log.e("Login it", it.toString())
Log.e("Login variable", loginCredentials.toString())
}
答案2
得分: 1
因为它正在另一个线程上运行。你不能像这样传递值。这是一个异步过程。
你必须创建一个LiveData观察者,然后在活动或片段中观察特定的元素。这样才能正常工作。
可以按照以下步骤进行操作:
- 初始化变量:
private val _catValuesList = MutableLiveData<List<Values>>()
val catValuesList: LiveData<List<Values>> = _catValuesList
- 在响应中使用postValue:
_catValuesList.postValue(catResponse.data)
- 观察:
viewModel.catValuesList.observe(viewLifecycleOwner) { list -> }
英文:
Because it's working on another thread. you can't pass the value like this. it's an async process.
You have to create a live-data observer and observe that particular element on activity or fragment. that's how it will work.
Steps which you can follow :-
- Init variables :-
private val _catValuesList = MutableLiveData<List<Values>>()
val catValuesList: LiveData<List<Values>> = _catValuesList
- postvalue in response :-
_catValuesList.postValue(catResponse.data)
- Observe :-
viewModel.catValuesList.observe(viewLifecycleOwner) { list -> }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论