我想从firestore检索布尔值,我想要的是一种语法,从中我可以再次检查从firestore获得真值的复选框



布尔无线网;复选框cB1;

事情是代码不工作,我正在从吐司更改数据类型时获得值,但我真的需要在获得"ture"后再次检查复选框。来自Firestore的value…期待您的回复

DocumentReference dc = firebaseFirestore.collection("Hostel Admin").document(var);
dc.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {

wifi = Boolean.valueOf(value.getString("Wifi"));
if (wifi.equals("true")) {
cB1.setChecked(true);
} else {
cB1.setChecked(false);
}
}
});

如果您想使用Java在Firestore中获得一个名为wifi的文档字段,您可以运行以下代码:

DocumentReference dc = firebaseFirestore.collection("Hostel Admin").document(var);
dc.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot snapshot,
@Nullable FirestoreException e) {
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}
// IF the document exists
if (snapshot != null && snapshot.exists()) {
System.out.println("Current data: " + snapshot.getData());

// Get the wifi field of the document
String document_wifi = snapshot.getString("wifi");
// Convert the value to boolean
Boolean wifi1 = Boolean.valueOf(document_wifi);
boolean wifi = wifi1.booleanValue();
// Or you can use the boolean primitive type (Uncomment the following line if you want boolean primitive type)
// boolean wifi = Boolean.parseBoolean(document_wifi);
// Then check if the boolean wifi contains the value true or false
if (wifi) {
cB1.setChecked(true);
} else {
cB1.setChecked(false);
}
} else {
System.out.print("Current data: null");
}
}
});

请查看以下Firebase文档

你的代码不工作,因为你试图检查什么包含一个布尔变量与。equals()方法,这是比较字符串。

请注意在Java中布尔类型和布尔类型是有区别的:

Boolean boolean1 = Boolean.valueOf("true");
boolean boolean2 = Boolean.parseBoolean("true");
  • Boolean: Boolean类将基本类型Boolean的值包装在对象中。Boolean类型的对象包含一个Boolean类型的字段。

  • boolean:不需要实例,您使用原始类型。

因此,如果您使用Boolean.valueof(str)方法,它将返回一个布尔对象,并且要查看它包含的内容,您需要使用布尔类的Boolean()方法。

所以如果你想从字符串转换为布尔值,你可以使用基本类的方法parseBoolean(str)

相关内容

最新更新