I'm doing some background work and showing a DialogFragment while I do that. Once my work is done and the relevant callback is invoked, I dismiss the dialog. When I do, I get a crash caused by a NPE in the android source, here:
void dismissInternal(boolean allowStateLoss) { if (mDialog != null) { mDialog.dismiss(); mDialog = null; } mRemoved = true; if (mBackStackId >= 0) { getFragmentManager().popBackStack(mBackStackId, FragmentManager.POP_BACK_STACK_INCLUSIVE); mBackStackId = -1; } else { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.remove(this); if (allowStateLoss) { ft.commitAllowingStateLoss(); } else { ft.commit(); } } }
specifically at the line: FragmentTransaction ft = getFragmentManager().beginTransaction();
This class was deprecated in API level 28. Use the Support Library DialogFragment for consistent behavior across all devices and access to Lifecycle.
tl;dr: The correct way to close a DialogFragment is to use dismiss() directly on the DialogFragment. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog. Dismiss the fragment and its dialog.
Show activity on this post. Dialog: A dialog is a small window that prompts the user to make a decision or enter additional information. DialogFragment: A DialogFragment is a special fragment subclass that is designed for creating and hosting dialogs.
you can set your args. class IntervModifFragment : DialogFragment(), ModContract. View { companion object { fun newInstance( plom:String,type:String,position: Int):IntervModifFragment { val fragment =IntervModifFragment() val args = Bundle() args. putString( "1",plom) args.
This may also occur when you call dismiss() before you have called show() like Sogger said.
After Dialog object is constructed but before dialog is not showed, if (mDialog != null) can be passed and NullPointerException will occur.
When you check if mDialog is null or not,
if (mDialog != null) { mDialog.dismiss(); mDialog = null; }
Add more conditions like below,
if ((mDialog != null) && mDialog.isAdded() && mDialog.isResumed()) { mDialog.dismiss(); mDialog = null; }
I think that mDialog.isAdded() condition might be enough...
Simplest solution is to check "getFragmentManager()" for "null" before calling "dismiss()" method. Also you can extend "DialogFragment" class and override method "dismiss()" to check it there:
@Override public void dismiss() { if (getFragmentManager() != null) super.dismiss(); }
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