我在java类的开关上出错了,我不知道该做什么
错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
at com.example.aclcshsnotifier.AdminDrawer.onCreate(AdminDrawer.java:120)
OnCreate方法中java类中的代码:
final Switch sAllStudents = findViewById(R.id.switchStudent);
final Switch sGrade = findViewById(R.id.switchGrade);
final Switch sBlock = findViewById(R.id.switchBlock);
final Switch sHouse = findViewById(R.id.switchHouse);
final TextView student = findViewById(R.id.txtIndStudent);
final TextView grade = findViewById(R.id.txtindGrade);
final TextView block = findViewById(R.id.txtIndBlock);
final TextView house = findViewById(R.id.txtIndHouse);
sAllStudents.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (sAllStudents.isChecked()){
sGrade.setEnabled(true);
sBlock.setEnabled(true);
sHouse.setEnabled(true);
student.setEnabled(true);
} else {
sGrade.setEnabled(false);
sBlock.setEnabled(false);
sHouse.setEnabled(false);
student.setEnabled(false);
}
}
});
sGrade.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (sGrade.isChecked()){
grade.setEnabled(true);
} else {
grade.setEnabled(false);
}
}
}); //the same format for sBlock and sHouse
具有开关的
xml:
<Switch
android:checked="false"
android:text="All SHS Students"
android:textSize="18sp"
android:paddingLeft="20dp"
android:paddingRight="180dp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="@+id/switchStudent"
android:background="@drawable/border"
android:backgroundTint="#80ffffff" app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="60dp"/>
//我在java类中初始化的其他开关与xml中的switchStudent格式相同
空对象引用上的空android.widget.Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)‘意味着什么?
发布于 2020-03-05 07:01:19
在设置setOnCheckedChangeListener之前,应该向开关添加一个空检查,如下所示
Switch s = (Switch) findViewById(R.id.SwitchID);
if (s != null) {
s.setOnCheckedChangeListener(this);
}
这可能会解决你的问题。
发布于 2020-03-05 06:58:08
这意味着您正在使用空对象引用注册setOnCheckedChangeListener()。在调用sAllStudents ()之前,请检查Swich、sGrade或null是否为空。
https://stackoverflow.com/questions/60539609
复制相似问题