getViewLifecycleOwner() in DialogFragment leads to crash

Alex.Marynovskyi picture Alex.Marynovskyi · Feb 19, 2019 · Viewed 7.2k times · Source

I use DialogFragment (onCreateDialog) and ViewModel for it. But, when I try to pass getViewLifecycleOwner() to the LiveData::observe method I get the error below:

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

Is it possible to use getViewLifecycleOwner() inside a DialogFragment?

Answer

Ionut Negru picture Ionut Negru · Feb 28, 2020

This happens because of how the DialogFragment is created. If you use onCreateDialog() than a slightly different lifecycle is used for this type of Fragment. The onCreateView() will not be used, thus the viewLifecycleOwner for this Fragment won't be initialized.

As a workaround for this, you can use the Fragment instance as the owner for the observer: .observe(this, Observer {...}. Although you will get a warning for using this instead of the viewLifecycleOwner.