我正在使用复选框,运行apk时出现此错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
在我要使用的行上复选框.setOnClickListener
这是代码
final CheckBox settings_1 = (CheckBox) findViewById(R.id.settings_1);
settings_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if( go_to_menu == 1)
{
settings_1.setChecked(false);
go_to_menu = 0;
SharedPreferences sharedpref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpref.edit();
String key = getString(R.string.check1);
editor.putInt(key, go_to_menu);
editor.commit();
}
else
{
settings_1.setChecked(true);
go_to_menu = 1;
SharedPreferences sharedpref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpref.edit();
String key = getString(R.string.check1);
editor.putInt(key, go_to_menu);
editor.commit();
}
}
});
答案 0 :(得分:1)
可能在setContentView()
之前调用此代码,或者活动的布局不包含ID为settings_1
的视图