无法在Android中添加窗口错误

时间:2011-08-17 11:40:02

标签: java android

  

可能重复:
  Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application"

我尝试了不同的东西,但我仍然保持同样的错误:

android.view.WindowManager$BadTokenException: Unable to add window 

在这一行:

alertDialog.show();

你能看一下代码吗?

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.splashscreen);

    Context mContext = this;
    alertDialog = new AlertDialog.Builder(mContext).create();

    LoadData();
}

public void LoadData()
{
    Thread t1 = new Thread(this);
t1.start();
}

private Handler handler = new Handler()
{
@Override
    public void handleMessage(Message msg) 
    {            
        if(!rssItems.isEmpty())
        {
            switch (msg.what) {
            case STOPSPLASH:
                //remove SplashScreen from view
                //splash.setVisibility(View.GONE);
                Intent intent = new Intent(
                "news.displayNews");
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                NewsDisplayer.rssItems.clear();
                NewsDisplayer.rssItems.addAll(rssItems);

                startActivity(intent);
                Close();
                break;
            }
        }
        else
        {
            alertDialog.setCancelable(false); // This blocks the 'BACK' button
            alertDialog.setMessage("No connection.");
            alertDialog.setTitle("Error...");
            alertDialog.setButton("Again", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();     
                    LoadData();
                }
            });
            alertDialog.setButton2("Close", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();     
                    System.exit(0);
                }
            });
            alertDialog.show();
        }
    }
 };

2 个答案:

答案 0 :(得分:0)

这是因为您用于创建alertDialog的上下文不支持它。因此,请尝试 getParent() getApplicationContext(),而不是mContext。那可能有用。

答案 1 :(得分:-2)

我认为那是因为你在一个帖子中运行它。必须在UI线程上执行alertDialog.show();。请尝试使用AsyncTask

编辑:我的不好,我没有仔细阅读代码。