Question

I have a DialogFragment that is shown on the screen from a background thread. When I rotate the screen, my app crashes. Below is the code:

public void showDialog(DialogFragment dialog) {
  FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
  ft.addToBackStack(null);
  dialog.show(ft, "dialog");
} 

This gives me the following error:

10-24 13:20:51.490: E/AndroidRuntime(3038): java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

After looking for answers on SO, and this article, I tried doing this:

public void showDialog(DialogFragment dialog) {
  FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
  ft.addToBackStack(null);
  ft.add(dialog, "dialog");
  ft.commitAllowingStateLoss();
}

But with this, I get the following error on ft.commitAllowingStateLoss()

10-24 13:26:58.890: E/AndroidRuntime(3765): java.lang.IllegalStateException: Activity has been destroyed

Any idea what am I missing?

Was it helpful?

Solution

You have a method as showDialog(DialogFragment dialog) but your problem is in your dialogFragment's initialization I guess. If you put dialogFragments initialization data to its arguments, your problem will be solved. Write a newInstance method and use it on creation of your dialog. See sample here.

Edit: Reason of your exception is; your activity and also dialogFragment is destroyed and re-created somehow(maybe by config_changes not set at manifest or "settings -> developer options -> don't keep activities" is selected. This can happen, it is normal). And initialization paramaters of your dialog has been lost(became null). You have to put your initialization parameters to dialogFragment's arguments and so it can read them after re-cration on create.

OTHER TIPS

Try this:

FragmentManager fm = getActivity().getSupportFragmentManager();
dialog.setTargetFragment(this, 0);
dialog.show(fm, 0);

Are you creating the fragment using a constructor with parameters?? if so that could be the case because you are not supposed to create fragments that way

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top