Yahor Urbanovich
Yahor Urbanovich

Reputation: 773

How to retrieve all documents from Firestore collection in POJO class?

I have some specific question about Firebase Firestore. I have a Firestore example model like this:

Firestore screenshot

Categories is collection, inside some documents. I try to get all documents from collection like this:

query.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
    if (firebaseFirestoreException != null) {
        if (!emitter.isDisposed) {
            TODO("implement new exception logic")
        }
    } else {
        val value = querySnapshot.toObjects(Category::class.java)
    }
}

In this case I get List of Category documents. Can I create class CategoriesEntity like this and get this model class in addSnapshotListener?

public class CategoriesEntity {

    private Map<String, Category> categories;

    public CategoriesEntity() {
    }

    public Map<String, Category> getCategories() {
        return categories;
    }

    public void setCategories(Map<String, Category> categories) {
        this.categories = categories;
    }
}

Upvotes: 2

Views: 1890

Answers (1)

Grimthorr
Grimthorr

Reputation: 6926

There's no convenience method like toObjects() that can create a map instead, but you could iterate through each document manually and add it to a map.

The documents in the collection are returned as a list, so you can iterate through each document, convert it to a Category instance and add it to your map manually, something like this:

query.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
    if (firebaseFirestoreException != null) {
        if (!emitter.isDisposed) {
            TODO("implement new exception logic")
        }
    } else {
        val categories = HashMap<String, Category>()
        for (document in querySnapshot.getDocuments()) {
            categories.put(document.getId(), document.toObject(Category::class.java))
        }
        val categoriesEntity = CategoriesEntity()
        categoriesEntity.setCategories(categories)
    }
}

Upvotes: 2

Related Questions