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:

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 :)

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.