5

I am getting the well known java.lang.IllegalArgumentException: View not attached to window manager. The currently known solution is to ignore the error using empty try-catch block. But is it there a more programmer friendly solution? E.g.

if (dialog.isAttached())
  dialog.dismiss();

Of course, better would be if the Android SDK would have a not failing function (because why the API should fail if it is impossible to avoid it??):

dialog.tryDismiss();

Or is the empty try-catch block architectonically justifiable? Or is it just a workaround for a bad or incomplete API?

Community
  • 1
  • 1
TN.
  • 18,874
  • 30
  • 99
  • 157

2 Answers2

2

I always use:

if(dialog != null && dialog.isShowing())
  dialog.dismiss();
SERPRO
  • 10,015
  • 8
  • 46
  • 63
  • Not working if you click `Home` button during the time the dialog is shown (it is a progress dialog) and the action finishes (the dialog is going to be dismissed) when the activity is no longer visible. – TN. Nov 09 '11 at 12:47
  • Sorry, but I just tried what you said in my application (Upload a picture and while the dialog is showing, press home button and wait for the action to finish (it shows a toast message). No exception at all. – SERPRO Nov 09 '11 at 13:05
  • Hmm, strange. The same thing gives me exception on Android 2.3.6. – TN. Nov 09 '11 at 13:14
0

you can use:

if (dialog != null && dialog.isShowing())dialog.dismiss();

better you dismiss dialog before activity disappears/closes...that means in onPause() and onDestroy() event too..

Hanry
  • 5,481
  • 2
  • 40
  • 53