ProgressDialog and AlertDialog cause leaked window

android

Solution

You need to cancel dialog in activity's onStop or onDestroy method. For example:

private AlertDialog diag = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    diag = showWelcomeMessageIfNecessary();

    if(diag != null)
        diag.show();
}

private AlertDialog showWelcomeMessageIfNecessary() {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Editor edit = prefs.edit();
    AlertDialog alert = null;

    if (!prefs.getBoolean("welcomemessage", false)) {
        edit.putBoolean("welcomemessage", true);
        edit.commit();

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.messages_welcome_content).setCancelable(false).setPositiveButton(R.string.errors_ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // Do nothing
            }
        }).setTitle(R.string.messages_welcome_title);
        alert = builder.create();
    }

    return alert;
}


@Override
protected void onStop() {
    super.onStop();

    if(diag != null)
        diag.dismiss();
}

Problem

I have an Activity which shows a welcome message if started for the first time: ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); showWelcomeMessageIfNecessary(); } private void showWelcomeMessageIfNecessary() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final Editor edit = prefs.edit(); if (!prefs.getBoolean("welcomemessage", false)) { edit.putBoolean("welcomemessage", true); edit.commit(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.messages_welcome_content).setCancelable(false).setPositiveButton(R.string.errors_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Do nothing } }).setTitle(R.string.messages_welcome_title); AlertDialog alert = builder.create(); alert.show(); } } ``` This all works beautifully, however when I start the app, and immediately rotate the screen, I get the well-known leaked window exception. How would I prevent this? Is there a better way to show dialogs? This also happens when I use `ProgressDialog`s in `AsyncTask`s in `Fragment`s.

Original source