. f Android Error: Unable to add window — token null is not for an application ~ Android Developers Blog

Monday, 19 May 2014

Android Error: Unable to add window — token null is not for an application

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:

  1. AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(  
  2.      getApplicationContext());  
  3. //ok and cancel button code  
  4. ...........  
  5. ...........  
  6. AlertDialog alertDialog = alertDialogBuilder.create();  
  7. alertDialog.show();  

Then after searching a lot I found the solution, I made following few changes in my
code and Its worked for me.

  1. AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(  
  2.      getApplicationContext());  
  3. //ok and cancel button code  
  4. ...........  
  5. ...........  
  6. AlertDialog alertDialog = alertDialogBuilder.create();  
  7. /* 
  8. * Window token null exception, when trying to show alert dialog from 
  9. * service class.use alertDialog.getWindow() for getting window and 
  10. * add permission in manifest 
  11. */  
  12. alertDialog.getWindow().setType(WindowManager.LayoutParams.  
  13.     TYPE_SYSTEM_ALERT);  
  14. alertDialog.show();  

Also need to add following permission in your manifest file

  1. <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />  

Hope this will helps some one.
Enjoy coding... cheers :)

Mukesh Kumar

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

2 comments:

 

Copyright @ 2013 Android Developers Blog.