What’s the best way to check if a collection exists in the cloudFirestore (Android)?

Asked

Viewed 123 times

0

I am having trouble verifying the existence of a collection. I am using the following code to perform this function:

FirebaseFirestore.getInstance().collection("ID da COLEÇÃO").document("ID do DOCUMENTO").collection("ID da SUB-COLEÇÃO").get().addOnSucessLi.... & addOnFailureLi.....

My intention is to know if the collection "SUB-COLLECTION ID" exists to enter addOnSusse... and if it does not exist then enter addOnFailu...

However, even though there is no "SUB-COLLECTION ID", addOnSuces... is being called.

1 answer

0


Hello, André!

onFailure is only called if the Firestore request fails. To find out if something exists, you need to wait for the callback to be successful in onSuccess.

To solve your problem, wait onSuccess be called and execute your code:

firestore.collection("colecao_1")
        .document("documento_id")
        .collection("colecao_2")
        .get()
        .addOnSuccessListener(snapshots -> {
            if (snapshots.isEmpty()) {
               // Execute seu código aqui
            }
        })

With this verification, we have two certainties: that the colecao_2 is empty (the most obvious) or that it simply does not exist, which for practical purposes, are the same thing.

I hope this helps!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.