无法添加窗口 - 令牌null不适用于应用程序

时间:2012-11-30 10:15:52

标签: android dialog android-asynctask spinner layout-inflater

我试图在视图(A.xml)中使用AsyncTask的onPostExecute()来扩展视图(B.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**);

}

它适用于4.0及以上

但是对于2.3.3 我得到一个错误

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)

是的,我尝试使用getApplicationContext(),但这仍然是同样的错误

我提到了

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"

2 个答案:

答案 0 :(得分:6)

好的,尝试为您vi变量使用这样的构造函数:LayoutInflater vi = LayoutInflater.from(YourActivityName.this);

答案 1 :(得分:0)

您只能传递LayoutInflater.from(this);