[英]How to get a field which is an object from Firestore?
我有一个这样的数据库:
我想检索那个 q8,我已经在我的应用程序中创建了一个包含所有这些字段的类:
public class Question {
boolean completed;
String hint;
String hintImage;
String hintimagename;
String id;
String imagePathWeb;
String passw;
String strikes;
public Question(boolean completed, String hint, String hintImage, String hintimagename, String id, String imagePathWeb, String passw, String strikes) {
... ...
}
and the getters and setters
我有很多这样的 qs,比如 q1,q2,q3...q20,我希望它们存储在一个列表中。
我被困在这里:
db.collection("games").document(huntPlayID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot snapshot,
@Nullable FirebaseFirestoreException e) {
if(e!=null) {
System.err.println("Listen Failed:" + e);
return;
}
if(snapshot != null && snapshot.exists()) {
changeUI(snapshot);
} else {
System.out.print("curent data: null");
}
}
});
private void changeUI(final DocumentSnapshot game) {
Question q1 = new Question(
// game.get("q1".completed ??
);
}
game 是我的文档,但我如何访问 q8 的完整字段? 或任何其他领域? 我如何访问这些值并将它们插入我的问题对象中..谢谢您的时间!
先感谢您!
当完全获取q1
您会返回一个Map<String,Object>
,然后您可以从中获取子字段:
Map<String,Object> q1 = (Map<String,Object>) snapshot.get("q1");
bool q1completed = (bool) q1["completed"]
我认为您也可以使用点表示法直接处理嵌套字段:
snapshot.get("q1.completed")
最好的解决方案是重新组织您的 firestore 文档并使用数组而不是地图。 请记住,您需要为每个文档加载付费,如果您加载整个文档或 1 个字段,则价格是相同的。 加载时,您需要执行以下操作:
private static class Questions {
Arraylist<Question> questions;
// add constructor + getter
}
private ArrayList<Questions> arr; private void changeUI(final DocumentSnapshot game) {
Questions questions = game.toObject(Questions.class);
arr = questions.getQuestions();
}
如果您仍然想一个一个地阅读字段,您应该这样做:
private void changeUI(final DocumentSnapshot game) {
Question question = game.get("q1").toObject(Question.class);
}
但是你应该记住,第二个选项会贵得多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.