5

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?

Yoann Hercouet
  • 17,894
  • 5
  • 58
  • 85

2 Answers2

5

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.

matiash
  • 54,791
  • 16
  • 125
  • 154
  • Thanks for your answer. About `dismiss()`, are we sure that the dialog deletion is always done right away? In my code I have to remove my `DialogFragment` just before the call to `super.onSaveInstanceState(savedInstanceState)`. I want to be 100% sure this dialog won't be retained in the instance. – Yoann Hercouet May 31 '14 at 06:48
  • Not sure but I would guess not. You can always use `dismissAllowingStateLoss()`. – matiash May 31 '14 at 06:50
  • OK I will accept your answer for now and try it with `dismiss()` only. I will update the question later if I see the problem is still not solved. – Yoann Hercouet May 31 '14 at 06:52
0

For showing Dialog Fragment dialogFragment.show(transition,FocusDialogFragment.TAG);

For dismissing dialog fragment by dialogFragment.dismiss();

Android
  • 99
  • 1
  • 1
  • 13
Qamar
  • 4,959
  • 1
  • 30
  • 49