开发者

Unable to add window error in Android [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

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

I've tried different things, but I still keep the same error:

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

At this line:

alertDialog.show();

Can you look at the code?

/** 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 Thre开发者_如何学Goad(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();
        }
    }
 };


This is because the context you are using to create the alertDialog doesn't support it. So instead of mContext, try getParent() or getApplicationContext(). That might work.


I think that's because you're running this in a thread. alertDialog.show(); has to be executed on the UI thread. Try using an AsyncTask instead.

EDIT: my bad, I didn't read carefully the code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜