Android Dialog Window Leaked During Orientation Change

642 Views Asked by At

I show a dialog on a fragment, that is supposed to be dismissed when an async task finishes executing. Everything works great until I change the orientation while the dialog is showing: I get a Window leaked error. I know that that is because the activity is recreated, and the dialog is 'attached' to the old one. I cannot use android:configChanges="keyboardHidden|orientation|screenSize" on the manifest because I have different layouts for landscape and portrait, so I dismissed the dialog on the onPause() method, and recreated it again when the new activity is created. But now I have a different problem: my async task does not have a reference to the new dialog, so it cannot dismiss it...

I have already tried the same thing with a dialog fragment, but the problem persists.

Is there a way around this problem?

Thanks.

1

There are 1 best solutions below

2
On BEST ANSWER

I know you said you can't use android:configChanges="keyboardHidden|orientation|screenSize" because you have different layouts for landscape and portrait, but take a look aAndroid documentation concerning Handling the Configuration Change Yourself:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        setContentView(R.layout.landscapeLayout);
        //update your view elements, if any
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        setContentView(R.layout.portraitLayout);
        //update your view elements, if any
    }
}

That way you can mantain your different layouts, and keep the reference to your dialog