Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ProgressDialog and AlertDialog cause leaked window

Tags:

android

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 ProgressDialogs in AsyncTasks in Fragments.

like image 271
nhaarman Avatar asked Jun 15 '12 13:06

nhaarman


1 Answers

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();
}
like image 133
waqaslam Avatar answered Nov 09 '22 23:11

waqaslam