Hope you are doing well.
I created a dialog fragment and called show() on the instance. I passed a custom tag to show()'s parameter. The fragment requires no other arguments. On config change, resizing the window of the app, the app crashes.
Caused by: android.view.InflateException: Binary XML file line #35 in com.signal.android.stage:layout/activity_main2: Binary XML file line #35 in com.signal.android.stage:layout/activity_main2: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #35 in com.signal.android.stage:layout/activity_main2: Error inflating class fragment
Caused by: java.lang.IllegalStateException: DialogFragment 0 doesn't exist in the FragmentManager
at androidx.navigation.fragment.DialogFragmentNavigator.onRestoreState(DialogFragmentNavigator.java:148)
This is a method from the DialogFragmentNavigator.java:
@Override
public void onRestoreState(@Nullable Bundle savedState) {
if (savedState != null) {
mDialogCount = savedState.getInt(KEY_DIALOG_COUNT, 0);
for (int index = 0; index < mDialogCount; index++) {
DialogFragment fragment = (DialogFragment) mFragmentManager
.findFragmentByTag(DIALOG_TAG + index);
if (fragment != null) {
fragment.getLifecycle().addObserver(mObserver);
} else {
throw new IllegalStateException("DialogFragment " + index
+ " doesn't exist in the FragmentManager");
}
}
}
}
Please see that the DIALOG_TAG that has been used has been hard coded to "androidx-nav-fragment:navigator:dialog:". So It makes sense that the Fragment is not found since I gave a custom TAG.
What is the expectation form the clients calling the show() method? What tag should be passed to gracefully restore the fragment?
Stay safe!
The change I have made to the
mTag
field of my customDialogFragment
class triggered this same crash when I try to restore the app from background.As you can see from the source code you have posted, the
tag
field is set and use byDialogFragmentNavigator
when restoring state. It simply means that you can't use a custom tag.So you should either hard-code the prefix:
show(... "androidx-nav-fragment:navigator:dialog:0")
or show it with the lib:
navigate(R.id.you_dialog_fragment_defined_in_nav_graph_xml)
or may even
dismiss
it as a workaround to avoid the restoring process: