1

In Firestore, how can I get the total number of documents and the id's of these in a collection?

For instance if I have

/Usuarios
    /Cliente
        /JORGE
            /456789
                /filtros
                      /status
                          /activo
                          /inactivo

My code:

FirebaseFirestore db = FirebaseFirestore.getInstance();
Task<QuerySnapshot> docRef = db.collection("Usuarios").document("Cliente").collection("JORGE").document("filtros").collection("status").get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            int contador = 0;
                            for (DocumentSnapshot document: task.getResult()) {
                                contador++;
                            }

                            int cantPS = contador;
}

I want to query how many people I have and get: 2 and the id's: activo, inactivo.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Check also **[this](https://stackoverflow.com/questions/48534676/get-collectionreference-count/48540276)** out. – Alex Mamo Jul 09 '18 at 15:39

1 Answers1

0

To determine the number of documents returned by a query, use QuerySnapshot.size().

To get the list of documents returned by a query, use QuerySnapshot.getDocuments().

To show the key of a document use DocumentSnapshot.getId().

So in total:

public void onComplete(@NonNull Task<QuerySnapshot> task) {
    if (task.isSuccessful()) {
        QuerySnapshot querySnapshot = task.getResult();
        int count = querySnapshot.size();
        System.out.println(count);
        for (DocumentSnapshot document: querySnapshot.getDocuments()) {
            System.out.println(document.getId());
        }
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks for help!. But this returns me 0 in the app. What I am doing is creating buttons dynamically with the amount of document that has a certain collection, and when applying the function provided by Firestore the "CollectionRefence", it has to be changed to: Task because if all the code of the function is wrong – Juan Pejerrey Jul 10 '18 at 23:53
  • When you run this code, should log the document, followed by each individual document ID. If it logs 0, there are no documents in the collection. – Frank van Puffelen Jul 11 '18 at 04:24
  • You're right, my friend, there were still fields to be able to recognize them. It's something that will stay with me, I'm just starting in the world of firebase. Thank you very much for your help. – Juan Pejerrey Jul 13 '18 at 22:17