CQM
CQM

Reputation: 44278

android.view.WindowManager$BadTokenException related to Dialog and Context

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

Upvotes: 0

Views: 307

Answers (1)

Martin Petransky
Martin Petransky

Reputation: 80

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()
    }
});

Upvotes: 1

Related Questions