1

I have a service that creates collections based on id and saves necessary data to them. I want to return all of these collections without knowing their name or id. I tried several ways but every time I access the top collection and its contents. Is there a way to reach all collections?

As you can see in the picture below, I have two collections starting with ckJCeY... and one starting with fzwKx... but unfortunately I can only access the one starting with ckJCeY....

enter image description here

Here is my code:

public List<Currency> getRemindedCurrencies() throws ExecutionException, InterruptedException {
    String key = "deviceKey";
    Firestore db = FirestoreClient.getFirestore();

    Iterable<CollectionReference> collectionReferences = db.listCollections();
    Iterator<CollectionReference> iterator = collectionReferences.iterator();
    List<Currency> currencyList = new ArrayList<>();
    HashMap<String, List<Currency>> deviceKeyCurrencyListMap = new HashMap<>();

    if (iterator.hasNext()) {
        CollectionReference next = iterator.next();
        for (Currencies currencies : Currencies.values()) {
            DocumentReference document = next.document(currencies.name().toLowerCase() + "-reminder");
            ApiFuture<DocumentSnapshot> snapshotApiFuture = document.get();
            DocumentSnapshot documentSnapshot = snapshotApiFuture.get();
            if (documentSnapshot.exists()) {
                String keyVal = documentSnapshot.getData().get(key).toString();
                currencyList.add(documentSnapshot.toObject(Currency.class));
                deviceKeyCurrencyListMap.put(keyVal, currencyList);
                if (deviceKeyCurrencyListMap.containsKey(key)) {
                    deviceKeyCurrencyListMap.get(keyVal).add(documentSnapshot.toObject(Currency.class));
                }
            } else {
                continue;
            }
        }
    }
    return currencyList;
}
Halil Sahin
  • 568
  • 1
  • 6
  • 25
  • What if you make a list of all collections and there they are added or removed/modified on parallel with corresponding actions? – Aitsuken Aug 21 '22 at 09:44
  • 1
    @Kloody The service I wrote already provides control of this every minute. – Halil Sahin Aug 21 '22 at 09:46
  • then whats the issue if you can use that list to iterate through all collections? You can use that list to get ids/names and go through them or whatever you desire – Aitsuken Aug 21 '22 at 09:48
  • There is no way you can return `currencyList` as a result of a method. Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a callback. You might also be interested in reading this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-cloud-firestore-using-get-bf03b6ee4953). – Alex Mamo Aug 21 '22 at 10:15

0 Answers0