我遇到了导致空指针异常的问题。
问题在于我的OnCheckedChanged()方法的结构方式。目前,基于创建时传递的字符串会膨胀不同的Dialog视图。基于此视图,可以向用户显示不同的开关。
我正在寻找一种方法来重新配置以下代码,以便它确实贯穿所有" if语句"和崩溃。我希望它能做类似于switch(v.getId())+ switch结构的东西。
我正在努力避免为我的应用程序实现单独的OnCheckedChange侦听器。
任何人都知道如何重构这个以避免NullPointerException?
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (alertDelete.isChecked()) {
// The toggle is enabled
permSet.add("alert_delete");
Log.e("ALERTDELETE", "CHECKED");
} else {
// The toggle is disabled
permSet.remove("alert_delete");
Log.e("ALERTDELETE", "UNCHECKED");
}
if (autoCreate.isChecked()) {
// The toggle is enabled
permSet.add("auto_create");
Log.e("ALERTDELETE", "CHECKED");
} else {
// The toggle is disabled
permSet.remove("auto_create");
Log.e("ALERTDELETE", "UNCHECKED");
}
if (autoDelete.isChecked()) {
// The toggle is enabled
permSet.add("auto_delete");
Log.e("ALERTDELETE", "CHECKED");
} else {
// The toggle is disabled
permSet.remove("auto_delete");
Log.e("ALERTDELETE", "UNCHECKED");
}
if (autoEdit.isChecked()) {
// The toggle is enabled
permSet.add("auto_edit");
Log.e("ALERTDELETE", "CHECKED");
} else {
// The toggle is disabled
permSet.remove("auto_edit");
Log.e("ALERTDELETE", "UNCHECKED");
}
}
答案 0 :(得分:1)
您也可以使用一种简单的方法来避免重复
private void checkAndSet(Checkable checkable, String param) {
if (checkable.isChecked()) {
// The toggle is enabled
permSet.add(param);
Log.e("ALERTDELETE", "CHECKED");
} else {
// The toggle is disabled
permSet.remove(param);
Log.e("ALERTDELETE", "UNCHECKED");
}
}
并且在每种情况下都可以致电:
checkAndSet(autoDelete, "auto_delete");
答案 1 :(得分:0)
实现了switch()和上面的答案。
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
switch (buttonView.getId()) {
case R.id.switchAlertDelete:
if (alertDelete.isChecked()) {
// The toggle is enabled
permSet.add("alert_delete");
Log.e("ALERTDELETE", "CHECKED");
} else {
// The toggle is disabled
permSet.remove("alert_delete");
Log.e("ALERTDELETE", "UNCHECKED");
}
break;
case R.id.switchAutomationCreate:
if (autoCreate.isChecked()) {
// The toggle is enabled
permSet.add("auto_create");
Log.e("ALERTDELETE", "CHECKED");
} else {
// The toggle is disabled
permSet.remove("auto_create");
Log.e("ALERTDELETE", "UNCHECKED");
}
break;
case R.id.switchAutomationDelete:
if (autoDelete.isChecked()) {
// The toggle is enabled
permSet.add("auto_delete");
Log.e("ALERTDELETE", "CHECKED");
} else {
// The toggle is disabled
permSet.remove("auto_delete");
Log.e("ALERTDELETE", "UNCHECKED");
}
break;
case R.id.switchAutomationEdit:
if (autoEdit.isChecked()) {
// The toggle is enabled
permSet.add("auto_edit");
Log.e("ALERTDELETE", "CHECKED");
} else {
// The toggle is disabled
permSet.remove("auto_edit");
Log.e("ALERTDELETE", "UNCHECKED");
}
break;
}