0

I get this error android.view.WindowManager$BadTokenException in my crash reports. On some devices it only reports the exception but doesn't crash the app, other devices experience a crash.

It is related to how the app is displaying dialogs.

Other answers suggest that the wrong context is being used, like a global one, but in my case I am not doing that, I am passing my activity's context to a different object's method.

public class Utils {

contains a method

public static void noConnection(Context context){
    final CustomAlertDialog alert = new CustomAlertDialog(context, context.getString(R.string.ErrorPastTense), context.getString(R.string.ErrorInternet), context.getString(R.string.OkButton), null);

    View.OnClickListener listener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            int id = v.getId();
            switch(id){
                case R.id.alertConfirm:
                    alert.dismiss();
                    break;
                default:
                    break;
            }
        }
    };
    alert.setListener(listener);
    alert.show();
}

which is called by a method in my activity like this Utils.noConnection(myActivity.this);

the error logs show the exception as occuring at alert.show()

why? and how to avoid

CQM
  • 42,592
  • 75
  • 224
  • 366

1 Answers1

1

Are you sure you are showing the dialog from a UI Thread ? Try something like:

Handler handler = new Handler();
handler.post(new Runnable() {
    @Override
    public void run() {
        alert.show()
    }
});
  • hm, it runs in `onPostExecute()` so thats definitely the UI thread but there could be another dialog still displayed in a condition. I added another `dialog.dismiss()` just before my call to the `Utils` class – CQM Jun 11 '13 at 14:40
  • You are opening a dialog from an async task ? Your context might be invalid by the time you try to open it ? – Martin Petransky Jun 11 '13 at 15:27
  • invalid? the asynctask runs in the same activity, and this message occurs if the server didn't return properly in which case I am not changing the activity or any UI elements etc, just popping up a dialog. – CQM Jun 11 '13 at 16:40
  • its inconclusive, some of my users are able to get the exception, I am not – CQM Jun 11 '13 at 19:13
  • So you say your users are still getting the exception using the code above ? – Martin Petransky Jun 12 '13 at 09:14