Unable to add window -- token null is not for an application

ashish.n picture ashish.n · Nov 30, 2012 · Viewed 7.8k times · Source

hi im trying to inflate an view(B.xml)(which has spinner in it)from a AsyncTask's onPostExecute() in a view(A.xml)mainActivity

MainActivity.class

protected void onPostExecute(String result) {
        LayoutInflater vi = (LayoutInflater) getApplicationContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = vi.inflate(R.layout.B, null);
        branded_spinner = (Spinner) v.findViewById(R.id.Spinner01);

        adapter_branded = new ArrayAdapter<String>(**MainActivity.this**,
                android.R.layout.simple_spinner_item, Branded);
        adapter_branded.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        branded_spinner.setAdapter(adapter_branded);                        
        branded_spinner.setOnItemSelectedListener(**MainActivity.this**);

}

it works fine for 4.0 and Above

but for 2.3.3 im getting an error

11-30 15:28:55.492: E/AndroidRuntime(540): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
11-30 15:28:55.492: E/AndroidRuntime(540):  at android.view.ViewRoot.setView(ViewRoot.java:531)
11-30 15:28:55.492: E/AndroidRuntime(540):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
11-30 15:28:55.492: E/AndroidRuntime(540):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)

yes i tried to use getApplicationContext() , this but still the same error

i referred

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

Android: ProgressDialog.show() crashes with getApplicationContext

Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"

Answer

Evos picture Evos · Nov 30, 2012

Ok, try to use constructor like this for you vi variable: LayoutInflater vi = LayoutInflater.from(YourActivityName.this);