[英]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.