How to get nested collection from Firebase Firestore on Android?

Viewed 82

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
            
        }
    });
1 Answers

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")
//                                

It means that you're generating a brand new unique document ID. If you want to create a reference that points to a particular document, then you have to pass the particular document ID that already exists in the database to the document() method, and not generate a new one.

So your code should look like this:

//Code to add data to Firestore.
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference uidRef =  db.collection("listing_details").document(uid);
CollectionReference roomDetailsRef = uidRef.collection("room_details");
String docId = roomDetailsRef.document().getId();
roomDetailsRef.document(docId).set(user).addOnSuccessListener(/*.../*);
//                       

See, I have used DocumentReference#getId() to get the ID of the document, and DocumentReference#set(Object data) to actually add the document to Firestore.

//Code to read data from Firestore.
roomDetailsRef.document(docId).get().addOnSuccessListener(/*.../*);
//                       

See, I have passed the document ID that was generated earlier, to the CollectionReference#document() method.

Edit:

If you want to get all documents that exist under the room_details collection, then please use the following lines of code:

roomDetailsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                if (document != null) {
                    RoomsDetails obj = document.toObject(RoomsDetails.class);
                    roomsDetails.add(obj);
                }
            }
            roomsAdapter.notifyDataSetChanged();
        } else {
            Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});
Related