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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With