簡體   English   中英

如何從Android上的Firestore中的子集合中獲取數據?

[英]How to get data from a sub-collection in Firestore on Android?

我通過以下方式擁有我的Firestore數據庫:

圖像數據庫Firestore

我一直在嘗試這個以獲得子集合的價值:

  FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    DocumentReference bulletinRef = rootRef.collection("facultades").document("3QE27w19sttNvx1sGoqR").collection("escuelas").document("0");
    bulletinRef.get()
            .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if (task.isSuccessful()) {
                        DocumentSnapshot document = task.getResult();
                        Log.d(LOG_TAG, "RESULTADO DE LA CONSULTA" + "===" + document.getData());
                    }
                }
            });

但這確實返回null: 圖像結果

請幫我。

你得到null ,因為escuelas不是一個子集合,它是保存類型的對象數組HashMap 所以下面的代碼行:

DocumentReference bulletinRef = rootRef.collection("facultades").document("3QE27w19sttNvx1sGoqR")
    .collection("escuelas").document("0");

永遠不會工作。 如果要獲取escuelas數組中的數據,請注意, array類型字段從Cloud Firestore數據庫作為地圖List到達。 所以請使用以下代碼行:

rootRef.collection("facultades").document("3QE27w19sttNvx1sGoqR").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                List<Object> list = (List<Object>) document.get("escuelas");
                //Iterate throught the list and get the data
            }
        }
    }
});

還請注意,在迭代時,從列表中獲取的每個元素都是HashMap類型。 因此,您需要再次迭代以獲取每個HashMap對象中的相應數據。

謝謝,這真的幫了我,我用這個代碼來迭代

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    rootRef.collection("facultades").document("3QE27w19sttNvx1sGoqR")
            .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    List<Object> list = (List<Object>) document.get("escuelas");
                    //Iterate throught the list and get the data

                    Map<String, String> map = new HashMap<>();
                    map.put("key2", list.toString());
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        System.out.println(entry.getKey() + " = " + entry.getValue());
                    }
                }
            }
        }
    });

這是結果: 圖像結果

但我感到困惑,我怎么能得到這個:

圖像數據庫

Facultades>所有文件> escuelas>名稱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM