我有一个列表视图,当我点击一个项目时,它应该显示一个带有Radiobuttons的AlertDialog。但是当调用alertDialog时,应用程序崩溃了。 Logcat给出了NullPointerException。我做错了什么?
private void registerClickCallBack() {
ListView list = (ListView) findViewById(R.id.settingsList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
if (position == 0) {
final AlertDialog levelDialog
final CharSequence[] items = { " Easy ", " Medium ",
" Hard ", " Very Hard " };
AlertDialog.Builder builder = new AlertDialog.Builder(
MyActivity.this);
builder.setTitle("Select The Difficulty Level");
builder.setSingleChoiceItems(items, -1,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
Intent i = new Intent(
getApplictionContext(),
MyActivity.class);
switch (item) {
case 0:
String msg = "Alert A";
Toast.makeText(
MyActivity.this,
msg, Toast.LENGTH_LONG).show();
break;
case 1:
String msga = "Alert B";
Toast.makeText(
MyActivity.this,
msga, Toast.LENGTH_LONG).show();
break;
case 2:
String msgz = "Alert C";
Toast.makeText(
MyActivity.this,
msgz, Toast.LENGTH_LONG).show();
break;
case 3:
String msge = "Alert E";
Toast.makeText(
MyActivity.this,
msge, Toast.LENGTH_LONG).show();
break;
}
}
});
levelDialog.dismiss();
levelDialog = builder.create();
levelDialog.show();
}
else if (position == 1) {
String msg = "1";
Toast.makeText(MyActivity.this, msg,
Toast.LENGTH_LONG).show();
} else if (position == 2) {
String msg = "2";
Toast.makeText(MyActivity.this, msg,
Toast.LENGTH_LONG).show();
}
else if (position == 3) {
String msg = "3";
Toast.makeText(MyActivity.this, msg,
Toast.LENGTH_LONG).show();
}
}
});
}
答案 0 :(得分:2)
在实例化之前,您正在调用levelDialog
上的函数
levelDialog.dismiss();
levelDialog = builder.create();
levelDialog.show();
将其更改为
levelDialog = builder.create();
levelDialog.show();
levelDialog.dismiss();
但我不确定你为什么要在那里打dismiss()
。如果这没有解决它,那么请发布logcat,以便我们知道NPE
的位置。为了更清楚,切换这些行应该会修复NPE
,但不应该在那里调用dismiss()
。
修改强>
取出这个
AlertDialog levelDialog=null;
并在此处声明并初始化
final AlertDialog levelDialog = builder.create();
levelDialog.show();
并在dismiss()
中致电onClick()
,但使用dialog.dismiss()
代替levelDialog.dismiss()
此外,通常最好使用Activity Context
代替Application Context
,因此在您的Intent
中,您可以将getApplicationContext()
更改为MyActivity.this