Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to remove a DialogFragment: dismiss() or transaction.remove()?

I still have a problem due to a DialogFragment used on my main activity.

I am currently using this code to remove it:

FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment frag = getFragmentManager().findFragmentByTag("LockDialog");

if(frag != null) {
    transaction.remove(frag);
    transaction.commit();
}

The problem is that I am still getting crashes due to the fact that the dialog has duplicates (meaning the dialog was not properly removed sometimes).

So my question is: is it a right way to remove a DialogFragment or must it be only used only for Fragments?

Do I have to use the dismiss() method all the time?:

Fragment lockFragment = getFragmentManager().findFragmentByTag("LockDialog");

//If the dialog already exist, we dismiss it
if(lockFragment != null  && lockFragment instanceof LockDialogFragment) {
    LockDialogFragment lockDialog = (LockDialogFragment) lockFragment;
    lockDialog.dismiss();
}

This is currently my biggest bug on one of my apps so I want to be sure before choosing one or the other.

Thanks!

EDIT: I just realized my current problem is maybe due to the fact that commits can be delayed, I will add executePendingTransactions to see if it gets any better. But still it brings another question, is it necessary to call transaction.remove() if the dialog has been dismissed? Is using dismiss() more straightforward and safe than using the transactions?

like image 807
Yoann Hercouet Avatar asked May 31 '14 06:05

Yoann Hercouet


1 Answers

DialogFragment.dismiss() is the correct way. From the documentation:

Dismiss the fragment and its dialog. If the fragment was added to the back stack, all back stack state up to and including this entry will be popped. Otherwise, a new transaction will be committed to remove the fragment.

like image 93
matiash Avatar answered Sep 30 '22 12:09

matiash