首页 > 解决方案 > 如何从 Cloud Firestore android 中的父集合中获取集合和子集合

问题描述

在此处输入图像描述

我有 user_info 作为父集合。在这个父集合下,它有 single_list 作为子集合和一些信息。我想从父集合中获取所有值。请帮我找到答案。提前致谢

标签: androidfirebasekotlingoogle-cloud-firestore

解决方案


           FirebaseFirestore db = FirebaseFirestore.getInstance();
        
                                db.collection("users_info")            
                                .get()
                                .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                                    @Override
                                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                        if (task.isSuccessful()) {
                                            for (DocumentSnapshot document : task.getResult()) {
                                            //Here you can add all documents Id to your documentIdList to fetch all sigle_data at once. 
                                                Log.d(TAG, document.getId() + " => " + document.getData());
                
                                                 documentIdList.add(document.getId());
                                            }
                                   getAllSubCollSingleData(documentIdList);
                                        } else {
                                            Log.w(TAG, "Error getting documents.", task.getException());
                                        }
                                    }
                                });
            
    public void getAllSubCollSingleData(List<Int> documentIdList){
                 for(int i=0;i<documentIdList.size();i++){
            
               
                        db.collection("users_info").document(documentIdList.get(i))(would be phone number)
                         .collection("single_data")  
                    
                                .get()
                                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                                    @Override
                                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                                        if (task.isSuccessful()) {
                                            for (QueryDocumentSnapshot document : task.getResult()) {
                                            //Here you can get all documents in sub collection single_data
                                            
                                            }
                                        } else {
                                            Log.w(TAG, "Error getting documents.", task.getException());
                                        }
                                    }
                                });
            }}

推荐阅读