Question

Hi fellow Androiddevelopers,

I try to have two DialogFragments in a row, so when the first is cancelled a second one pops up.

Here is what I have so far:

In my Activity I call the following method:

void showFirstDialog() {
        // Pass the context to do a callback
        DialogFragment newFragment = ChangeDialogFragment.newInstance(mContext);
        newFragment.show(getSupportFragmentManager(), "myFirstDialogTag");
    }

In my DialogFragment I have following code to detect that it will be cancelled:

@Override
    public void onCancel(DialogInterface dialog) {
            // Use Context to do a callback and inform the Activity that
            // Fragment is cancelled
        ((Activity) mContext).firstDialogCanceled();
        super.onCancel(dialog);
    }

Back in my Activity I react on that eventy by starting the second dialog:

void firstDialogCanceled {
        DialogFragment newFragment = InformationDialogFragment.newInstance();
        newFragment.show(getSupportFragmentManager(), "mySecondDialogTag");
    }

This works perfectly as long as I don't have an orientation change on the first dialog. When I have one I get the following error:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

This exceptions is raised on the line "newFragment.show(getSupportFragmentManager(), "mySecondDialogTag");"

What I thought how I could fix this problem is to dismiss the first dialog by hand. I tried following:

DialogFragment firstFragment = (DialogFragment) getSupportManager().findFragmentByTag("myFirstDialogTag");
firstFragment.dismiss();

Again without an orientation change everyhting is working fine. When I have an orientation change while first dialog is on screen I get a NullPointerException on line "firstFragment.dismiss()".

Why is that happening? Why does the FragmentManager forget about my DialogFragment after a orientation change and why can't I just show the second one. Androidreferences say:

you should use show(FragmentManager, String) or show(FragmentTransaction, String) to add an instance of DialogFragment to your UI, as these keep track of how DialogFragment should remove itself when the dialog is dismissed.

I DO use show, but it is still not working properly.

Any hint is highly appreciated!

Cheers Ali3n

Was it helpful?

Solution

You are using old instance of the activity in your dialog fragment. I guess you are passing the current activity as mContext in newInstance method. After a configuration change such as orientation or keyboard, this context object becomes invalid and it is no longer attached to any window.

You can use getActivity() method of FragmentDialog to get the current activity it lives in.

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