我在Java类中的Switch上遇到错误,我不知道该怎么办
错误:
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的格式相同
关于空对象引用的void android.widget.Switch.setOnCheckedChangeListener(android.widget.CompoundButton $ OnCheckedChangeListener)'是什么意思?
我在Java类中的Switch上遇到错误,我不知道该怎么办:错误原因:java.lang.NullPointerException:尝试调用虚拟方法'void android.widget.Switch ... 。
这意味着您正在使用空对象引用注册setOnCheckedChangeListener()。请在调用setOnCheckedChangeListener()之前检查Swich sAllStudents或sGrade是否为null。