难以显示警告对话框,为什么此代码强制关闭我的应用程序?

时间:2010-07-18 05:17:12

标签: android interface dialog

我对Android很新,所以我一直主要使用Android开发人员页面中的信息。在我从警报对话框部分添加代码之前,一切都很顺利。当我尝试在最后一行运行它时,他们单独提供的代码会给我一个错误,说我必须初始化对话框,但我觉得无论情况如何我都会得到NullPointerException ...继承我的代码:< / p>

protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        switch(id) {
        case NAME_MISSING_ID:
            // do the work to define the Dialog
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Proceed without a name?")
                   .setCancelable(false)
                   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            MainActivity.this.finish();
                       }
                   })
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                       }
                   });
            AlertDialog alert = builder.create();
            break;
        case HARD_SELECTION_ID:
            // do the work to define the Dialog
            AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
            builder2.setMessage("This is INSANE! Are you sure?")
                   .setCancelable(false)
                   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            MainActivity.this.finish();
                       }
                   })
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                       }
                   });
            AlertDialog alert2 = builder2.create();
            break;
        default:
            dialog = null;
        }
        return dialog;
    }

如果我没有在开头将“dialog”实例化为“null”,我就无法运行该程序。我甚至没有尝试做任何疯狂的事情,任何帮助都会很棒,因为我在试图弄清楚这段代码到底要做什么时遇到了很多麻烦。

谢谢你们!

2 个答案:

答案 0 :(得分:1)

在所有情况下都返回null - 请参阅对话框变量,它永远不会被赋值。

您可能想要更改这些行:
AlertDialog alert = builder.create();
AlertDialog alert2 = builder2.create();

到此:
dialog = builder.create();
dialog = builder2.create();

下次最好给我们完整的堆栈跟踪。

答案 1 :(得分:1)

问题是你没有返回对话框...... createDialog总是返回null。

而不是AlertDialog alert = builder.create();你应该

return builder.create();
显然,这两种情况都是如此。