我的应用程序从主视图打开一个新视图,其中包含:
Intent ElementsIntent = new Intent(this, ElementList.class);
startActivityForResult(ElementsIntent, 0);
它显示了一个元素列表,当推送其中一个元素时,一个视图会以与以前相同的方式打开一个新的 Activity。在这个视图中,我想在按钮单击处理程序中显示一个 AlertDialog,但是当我调用 show() 时,应用程序崩溃了。
根据我尝试打开对话框的位置,我很确定它与上下文不正确有关,但我尝试从主视图创建静态上下文,我尝试使用 element.this,这是连接到活动的类,我尝试了getApplicationContext,所有这些都导致应用程序崩溃。
我希望有人能解释我做错了什么。
谢谢。
这是崩溃的 AlertDialog 代码:
public void GoBackClickHandler(View v)
{
AlertDialog.Builder builder = new AlertDialog.Builder(ElementItem.this);
builder.setMessage("Skal ændringer i besvarelse gemmes?")
.setCancelable(false)
.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
if(inputIsValue())
{
UpdateELement task = new UpdateELement();
task.applicationContext = ElementItem.this;
task.execute(1);
}
}
})
.setNegativeButton("Nej", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
如果我将此代码移至 OnCreate,则警报会显示得很好,并且不会出现应用程序崩溃。只有当我将它放在 ClickHandler 中时它才会崩溃。