首页 > 解决方案 > 活动的简单对话框错误 - android.view.WindowManager$BadTokenException

问题描述

我的主要活动调用了第二个活动。这第二个活动调用了一个 viewholder java 类,从中调用了一个警报对话框:

                    Log.w(LOG_TAG, "call the alertdialog");
                    showAlertDialog();


public void showAlertDialog() {
    /** define onClickListener for dialog */
    DialogInterface.OnClickListener listener
            = new   DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // do some stuff eg: context.onCreate(super)
        }
    };

    /** create builder for dialog */
    AlertDialog.Builder builder = new AlertDialog.Builder(NFLActivity.context)
            .setCancelable(false)
            .setMessage("You have made all bets. Select OK to submit...")
            .setTitle("All Bets Are In")
            .setNegativeButton("Return", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

应用程序因此崩溃:06-29 10:03:31.340 3740-3740/com.bab_c.picksandbets E/AndroidRuntime: 致命异常:主进程:com.bab_c.picksandbets,PID:3740 android.view.WindowManager$BadTokenException:无法添加窗口——token null 无效;您的活动正在运行吗?

我研究发现对话框需要一个活动,但是当使用第二个活动showAlertDialog(SecondActivity.context)时它仍然失败。

标签: javaandroidandroid-activityandroid-alertdialog

解决方案


首先,使用 viewHolder 类来保存视图并使用 viewHolder 的视图从第二个 Activity 调用警报。

第二件事,不要将上下文设为静态


推荐阅读