Handlind Android dialog whos context is destroyed

1.2k Views Asked by At

I got a class which handles a dialog creation and display in my app.

It got a dialog as a class member and a method which has the following lines:

public static void setAlertDialog(String title, final Context con, boolean dialogCancelable)
{
    if(myDialog == null)
    {
        myDialog = new Dialog(con);
    ...
}

The context can be destroyed after some time (by an action of the application which means its not that rare), and then I get an exception of

Unable to add window – token android.os.BinderProxy@422d2228 is not valid; is your activity running?

Since the dialog remains the same instance, a fix suggesting doing the following will not work:

if(!((Activity)con).isFinishing())
{
        myDialog.show();
}

I fixed it for now with simply creating a new instance of the dialog every time I use it.

The question is if my fix is ok or if there are better ways of handling this situation?

1

There are 1 best solutions below

0
On BEST ANSWER

I would need a little bit more context on how setAlertDialog is called in conjunction with showing the dialog. Since the activity is being destroyed, it sound like the dialog is probably being displayed from an async task.

Further, what is your reasoning for keeping the dialog as an instance variable? Usually this is done so the dialog can be cleaned up when pausing or destroying the Activity.

TlDr; Your fix sounds fine.

The long version (making some assumptions):

In my experiences, you typically want to handle creating and showing a dialog at the same time. If you don't want to create the dialog multiple times (and you don't plan on destroying the Activity between creating the dialog and showing it) something like the following should work:

if(!((Activity) context).isFinishing()){
  if (myDialog == null) {
    myDialog = new Dialog(context);
  }
  myDialog.show();
}

Then adding the following to the Activity to make sure the dialog is cleaned up:

@Override
protected void onDestroy() {
  // Dismiss any dialogs to avoid leaking windows.
  if (myDialog != null && myDialog.isShowing()) {
    myDialog.dismiss();
    // This is optional, but would keep you from having the context
    // issue if you are still having it and don't mind re-creating
    // the dialog each time.
    myDialog = null;
  }

  super.onDestroy();
}