': Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()

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()



Solution 1:[1]

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;
}

Solution 2:[2]

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) })

Solution 3:[3]

The solution for me was writing code inside onViewCreated insted of writing in onCreateView.... and my problem fixed.

Solution 4:[4]

The solution for me was simplified. I am using separate observers - one for the network which is using Lifecycleowner from the main activity (or just from any activity) and one for the fragment view (model view view model).

Solution 5:[5]

 myModel.getOfflineData().observeForever(new Observer<List<indiaStateModel>>() {
                @Override
                public void onChanged(List<indiaStateModel> indiaStateModels) {
                    adapter = new stateAdapter(indiaStateModels);
                    recyclerView.setAdapter(adapter);
                }
            });

// use this forever observer when your are getting that error // mainly this error comes when you try to change your phone theme to dark to light or light to dark

Solution 6:[6]

Best To Use FLow() instead of LiveData()

Convert LiveData() to Flow()

Before

viewModel.responseState.observe(parentFragment.viewLifecycleOwner, Observer {
    updateUI(it)
})

AFTER

lifecycleScope.launch {

viewModel.responseState.asFlow().collectLatest{
 
updateUI(it)

l?

}

}

Solution 7:[7]

In my case I was setting observer inside view runnable:

view.post(() ->{
    ...
    viewModel.getDate().observe();
})

Solution 8:[8]

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()
}

Solution 9:[9]

The solution, as your comment, is to ensure the fragment's view is not null. This happened to me with a Fragment inside a ViewPager.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Top-Master
Solution 2 Abdev
Solution 3 Alireza Haji gholamreza
Solution 4
Solution 5 Sourav Rawat BCA
Solution 6 Anuj Kumar Rai
Solution 7 Te Global
Solution 8
Solution 9 Emmanuel Guerra