【发布时间】:2016-11-11 23:29:03
【问题描述】:
原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'void android.widget.CheckBox.setChecked(boolean)'
这是我无法弄清楚为什么会发生的错误。
这是我的 java 类:
public class PopUpInfoActivity extends Activity {
static final String PREFS = "preference_file";
@Override
public void onCreate(Bundle state){
super.onCreate(state);
CheckBox chk = (CheckBox) findViewById(R.id.dontshow_checkbox);
chk.setChecked(PreferenceManager.getDefaultSharedPreferences(this).getBoolean("value", false));
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//store isChecked to Preferences
SharedPreferences settings = getSharedPreferences(PREFS,0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isChecked", false);
PreferenceManager.getDefaultSharedPreferences(PopUpInfoActivity.this).edit().putBoolean("value", isChecked).apply();
}
});
}
}
我在其中导入了android.widget.CheckBox
这是我的 xml 文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:scaleType="centerInside"
android:src="@drawable/legenda" />
<CheckBox
android:id="@+id/dontshow_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/dont_show"
android:textAllCaps="true"
android:fontFamily="sans-serif"
android:textStyle="bold"
android:layout_gravity="center"/>
</LinearLayout>
如果您能帮我解决这个错误,我将不胜感激!
【问题讨论】:
-
setContentView(R.layout.xmllayout);
标签: java android xml android-studio checkbox