Reputation: 1
In my fragment, I use viewlifecycleowner to observe live data but in some cases my app crashes with this log:
Fatal Exception: java.lang.IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()
So I ask how to reproduce and avoid this issue please!
Upvotes: 0
Views: 1997
Reputation: 1
I'm using observe(this@yourfragment)
instead observe(viewlifecycleowner)
. And add @SuppressLint("FragmentLiveDataObserve")
on the top of the method.
This work for me.
Upvotes: 0
Reputation: 8335
You should register your LiveData
observer in Fragment
's onViewCreated
. where viewlifecycleowner
can never be null
.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.someLiveData.observe(viewLifecycleOwner, Observer<Something> {
// Update the UI.
})
}
Upvotes: 1