I am trying to update the values in an EditText by observing a LiveData from a ViewModel.
Here is the FRAGMENT in which I am trying to update the values of my EditText:
private var qnaQuestionData: String = "TEST VALUE"
private val communicationViewModel by lazy {
ViewModelProvider(this).get(
MyProfileEditSharedViewModel::class.java
)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
communicationViewModel.question.observe(viewLifecycleOwner, Observer {data ->
data.let { qnaQuestionData = it }
})
et_question.setText(qnaQuestionData)
}
Here is my ViewModel:
class MyProfileEditSharedViewModel : ViewModel() {
val question: MutableLiveData<String> by lazy { MutableLiveData<String>() }
}
When I run this code, the value of my EditText is set to "TEST VALUE" which means that the LiveData was never observed. How can I fix this??
Thank you!
Changing
private val communicationViewModel by lazy {
ViewModelProvider(this).get(
MyProfileEditSharedViewModel::class.java
)
}
to
private val communicationViewModel by lazy {
ViewModelProvider(requireActivity()).get(
MyProfileEditSharedViewModel::class.java
)
}
Solved the problem.
The official docs told me to change this
to requireActivity()