Hello Friends,
most of us facing the issue of Unable to add window — token null
while calling alert dialog from our service class.
As, I am using activity class not the fragment so I am using getApplicationContext()
(as from service we face context issue so instead of using "this" am using
application context) for creating "AlertDialog.Builder" but still facing the issue
while calling dialog.show.
android.view.WindowManager$BadTokenException:
Unable to add window -- token null is not for an application
at android.view.ViewRoot.setView(ViewRoot.java:509)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:241)
Here is my code:
Then after searching a lot I found the solution, I made following few changes in my
code and Its worked for me.
Also need to add following permission in your manifest file
Hope this will helps some one.
Enjoy coding... cheers :)
most of us facing the issue of Unable to add window — token null
while calling alert dialog from our service class.
As, I am using activity class not the fragment so I am using getApplicationContext()
(as from service we face context issue so instead of using "this" am using
application context) for creating "AlertDialog.Builder" but still facing the issue
while calling dialog.show.
android.view.WindowManager$BadTokenException:
Unable to add window -- token null is not for an application
at android.view.ViewRoot.setView(ViewRoot.java:509)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:241)
Here is my code:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( getApplicationContext()); //ok and cancel button code ........... ........... AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show();
Then after searching a lot I found the solution, I made following few changes in my
code and Its worked for me.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( getApplicationContext()); //ok and cancel button code ........... ........... AlertDialog alertDialog = alertDialogBuilder.create(); /* * Window token null exception, when trying to show alert dialog from * service class.use alertDialog.getWindow() for getting window and * add permission in manifest */ alertDialog.getWindow().setType(WindowManager.LayoutParams. TYPE_SYSTEM_ALERT); alertDialog.show();
Also need to add following permission in your manifest file
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Hope this will helps some one.
Enjoy coding... cheers :)