Issue
I am having a LiveData observer inside fragment, sometimes the code inside Observer{} throws error
Exception: java.lang.IllegalStateException: Fragment not attached to an activity.
at androidx.fragment.app.Fragment.requireActivity(Fragment.java:833)
It is happening because requireActivity() is returning null so the exception
myViewModel.saveData(data).observe(requireActivity(), Observer {
it?.let { response->
when(response.status){
Status.SUCCESS -> {
Toast.makeText(requireActivity(),"SUCCESS",Toast.LENGTH_LONG).show()
}
Status.ERROR -> {
Toast.makeText(requireActivity(),"ERROR",Toast.LENGTH_LONG).show()
}
Status.LOADING -> {
}
}
}
})
I confirmed there is no scenario that my fragment being detached from the activity. I am suspecting the crash might be happening because I am not passing lifecycleowner reference to Observer?
Solution
Use ViewLifecycleOwner as LifecycleOwner while observing livedata from the fragment. Because the ViewLifecycleOwner is tied to the fragment's view lifecycle, but requireActivity() is tied to the fragment's overall lifecycle.
myViewModel.saveData(data).observe(viewLifecycleOwner) {
it?.let { response->
when(response.status){
Status.SUCCESS -> {
Toast.makeText(requireActivity(),"SUCCESS",Toast.LENGTH_LONG).show()
}
Status.ERROR -> {
Toast.makeText(requireActivity(),"ERROR",Toast.LENGTH_LONG).show()
}
Status.LOADING -> {
}
}
}
}
Answered By - sabith.ak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.