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?
Use
ViewLifecycleOwner
asLifecycleOwner
while observing livedata from the fragment. Because theViewLifecycleOwner
is tied to the fragment's view lifecycle, butrequireActivity()
is tied to the fragment's overall lifecycle.