![](/img/trans.png)
[英]Android Studio - How do I get documents from a sub-collection in Firestore?
[英]How to get data from a sub-collection in Firestore on Android?
我通過以下方式擁有我的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.