How to get list of documents from a collection in Firestore Android

Ivan Banha :

My structure of Firestore database:

|
|=>root_collection
                  |
                  |=>doc1
                         |                  
                         |=>collection
                  |
                  |=>doc2
                         |                  
                         |=>collection
                  |
                  |=>doc3
                         |                  
                         |=>collection

Now I wanna get list of document from root_collection. There would be a list with following data {"doc1", "doc2", "doc3"}. I need it because I want to make a spinner and put these data in the spinner. Then a user would be choose some document and download it.

I try to use the code below:

firestore.collection("root_collection")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(TAG,document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

But the code works only then I have structure of data without collections in the documents. In other case there aren't any documents in QueryDocumentSnapshot.

Thanks!

Alex Mamo :

To have a list that contains all the name of your documents within the root_collection, please use the following code:

firestore.collection("root_collection").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            List<String> list = new ArrayList<>();
            for (QueryDocumentSnapshot document : task.getResult()) {
                list.add(document.getId());
            }
            Log.d(TAG, list.toString());
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

The result in your logcat will be:

[doc1, doc2, doc3]

Remember, this code will work, only if you'll have some properties within those documents, otherwise you'll end ut with an empty list.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=464701&siteId=1