【问题标题】:NullPointerException when using CheckBox in android在 android 中使用 CheckBox 时出现 NullPointerException
【发布时间】: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


【解决方案1】:

你的id 是正确的,但你错过了一个非常重要的行 - setContentView。该行将 xml 与 Activity 的视图绑定,它是用于 findViewById 的视图。将此行添加到您的 onCreate:

@Override
public void onCreate(Bundle state){
    super.onCreate(state);
    setContentView(R.layout.name_of_the_xml);

然后是您的其余代码。请务必提供正确的 xml 名称。

【讨论】:

  • 感谢您的回答!多么愚蠢的错误!不敢相信我看不到!
  • 不客气。啊,我知道,有时需要别人才能看到你错过了什么。经常发生在我身上:D
猜你喜欢
  • 2014-09-05
  • 1970-01-01
  • 2016-11-04
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 2012-06-23
  • 2014-04-03
  • 1970-01-01
相关资源
最近更新 更多