I am using live data in my application for all the network calls and response handling.
In one of the scenarios, my recycler view is loading some data in its view holder's onBind
and the response is updating the UI. In order to do so, I have to provide a lifecycleOwner
to the observer.
As recycler view doesn't have any lifecycle owner of its own, I am using the parent fragment for that by using parentFragment.viewlifecycleOwner
but somehow it is giving an error.
How can a view Holder have its instance when the parent fragment is not having its instance?
viewModel.responseState.observe(parentFragment.viewLifecycleOwner, Observer {
updateUI(it)
})
Fatal Exception: java.lang.IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()
This can be fixed, by triggering the logic which is raising the error, from around end of onCreateView(...)
callback (not onCreate(...)
nor onAttach(...)
).
In getViewLifecycleOwner() documentation, I don't think, I can explain better:
The first method where it is safe to access the view lifecycle is onCreateView(LayoutInflater, ViewGroup, Bundle) under the condition that you must return a non-null view (an IllegalStateException will be thrown if you access the view lifecycle but don't return a non-null view).
The view lifecycle remains valid through the call to onDestroyView(), after which getView() will return null, the view lifecycle will be destroyed, and this method will throw an IllegalStateException. Consider using getViewLifecycleOwnerLiveData() or FragmentTransaction.runOnCommit(Runnable) to receive a callback for when the Fragment's view lifecycle is available.
public LifecycleOwner getViewLifecycleOwner() {
if (mViewLifecycleOwner == null) {
throw new IllegalStateException("Can't access the Fragment View's LifecycleOwner when "
+ "getView() is null i.e., before onCreateView() or after onDestroyView()");
}
return mViewLifecycleOwner;
}
i faced the same problem and i could fix it with the code bellow , just check if the view is null or not
if ( view != null)
viewModel.responseState.observe(parentFragment.viewLifecycleOwner, Observer {
updateUI(it) })
The solution for me was writing code inside onViewCreated insted of writing in onCreateView.... and my problem fixed.
The problem is that the observer is still active on the parent's viewLifecycleOwner
even after the view is destroyed (when you navigate to the next fragment). The most reliable way to fix this is to clear out the observers.
override fun onDestroyView()
viewModel.responseState.removeObservers(parentFragment.viewLifecycleOwner)
super.onDestroyView()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With