gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 00:50:21 25 4
gpt4 key购买 nike

我是 Android 的新手,所以我一直主要使用来自 android 开发者页面的信息。在我从警报对话框部分添加代码之前,一切都很顺利。当我尝试在最后一行运行它时,他们单独给出的代码给我一个错误,说我必须初始化对话框,但我觉得无论是什么情况我都会得到 NullPointerException ......这是我的代码:

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”,我就无法运行程序。我什至还没有尝试做任何疯狂的事情,任何帮助都会很棒,因为我在试图弄清楚这段代码到底想做什么时遇到了很多麻烦。

谢谢大家!

最佳答案

您在所有情况下都会返回 null - 查看对话框变量,它从未被赋值。

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

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

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

关于android - 难以显示警报对话框,为什么此代码会强制关闭我的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3274417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com