Home > Software design >  How to get nested collection from Firebase Firestore on Android?
How to get nested collection from Firebase Firestore on Android?

Time:09-05

I am working on an application where I have saved my data in firebase Firestore in nested collection now when I am trying to get/retrieve the data from Firestore but not able to get it. please guide me where am I wrong??

CODE TO WRITE/ADD THE DATA IN FIRESTORE

  DocumentReference uidRef =  firebaseFirestore.collection("listing_details").document(uid);

    uidRef.collection("room_details").add(user).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
       @Override
       public void onSuccess(DocumentReference documentReference) {

           Toast.makeText(getContext(), "data added", Toast.LENGTH_SHORT).show();


       }
   })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {

            Toast.makeText(getContext(), "data adding failure", Toast.LENGTH_SHORT).show();
        }
    });

CODE FOR DATA RETRIEVING

  db.collection("listing_details").document().collection("room_details").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
            for (DocumentSnapshot d : list)
            {
                RoomsDetails obj = d.toObject(RoomsDetails.class);
                roomsDetails.add(obj);
            }
            roomsAdapter.notifyDataSetChanged();

        }
    });

DATA RETRIEVING CODE (UPDATED)

  roomDetailsRef.document(doc_id).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {

        //GUIDE ME HERE HOW CAN I ITERATE THROUGH IT SIR PLEASE
            
        }
    });

CodePudding user response:

Each time you're calling .document() to create the following reference, without passing anything as an argument:

db.collection("listing_details").document().collection("room_details")
//                                           
  • Related