Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through sub collections to get fields - Firestore Android

Each Notification ID collection contain only one document and I want to Iterate all the collections in ToseefShop1 and get the respective document name and fields data.

Data Model:

enter image description here Sub Collections:

enter image description here enter image description here Code:

dbRef.collection("Shop Notifications")
        .document("ToseefShop1")
        .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot querySnapshot) {
        // Dont know what to do
    }
});

It's not a duplicate question. The other question (someone suggested as duplicate to) is about javascript and answers are for Node.js. With no answer accepted. Infact I can not find getcollections() method in firestore Java.

like image 319
MakesReal Avatar asked Jan 01 '23 21:01

MakesReal


1 Answers

There is no way in Firestore to query a document to get the subcollections beneath it. In order to get the document name and fields data that you are asking for, first you need to have the names of subcollections and then use them in a reference. If you have only 2 subcollections, I suggest you to use the following code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query firstQuery = rootRef
    .collection("Shop Notifications")
    .document("ToseefShop1")
    .collection("Notification ID:0");
Query secondQuery = rootRef
    .collection("Shop Notifications")
    .document("ToseefShop1")
    .collection("Notification ID:1");

Task firstTask = firstQuery.get();
Task secondTask = secondQuery.get();

Task combinedTask = Tasks.whenAllSuccess(firstTask, secondTask).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
    @Override
    public void onSuccess(List<Object> list) {
         //Do what you need to do with your list
    }
});
like image 133
Alex Mamo Avatar answered Jan 05 '23 06:01

Alex Mamo