Search code examples
androidexceptionwindow-managerscustomdialog

android.view.WindowManager$BadTokenException on custom dialog


My application crashes with below error stack on specific android version and device (VIVO with android 5.1 & Oneplus one with Android 7.1)

*_ android.view.WindowManager$BadTokenException:
  at android.view.ViewRootImpl.setView (ViewRootImpl.java:679)
  at android.view.WindowManagerGlobal.addView (WindowManagerGlobal.java:342)
  at android.view.WindowManagerImpl.addView (WindowManagerImpl.java:94)
  at android.app.Dialog.show (Dialog.java:329)
  at com.yathirajjp.brainstimuli.QuickMath.showCustomDialog (QuickMath.java:193)
  at com.yathirajjp.brainstimuli.QuickMath$3.onFinish (QuickMath.java:252)
  at android.os.CountDownTimer$1.handleMessage (CountDownTimer.java:127)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6186)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:889)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:779) _*

The code snippet from QuickMath.java as follows

final Dialog customDialog = new Dialog(**this**);
customDialog.setContentView(R.layout.custom_dialog_layout);

waitTimer.cancel();  // Cancelling the CountDownTimer before calling the show custom dialog

customDialog.show();

I suspect the initialisation of customDialog. Am I right in using the context as 'this'?


Solution

  • android.view.WindowManager$BadTokenException:

    You should call YourActivity.this instead of this.

    Don't

    final Dialog customDialog = new Dialog(this);
    

    Do

    final Dialog customDialog = new Dialog(QuickMath.this);