Skip to content
Advertisement

Read Firestore Data in Android Java

i am working on android application and i am trying to read data from the firestore. One of the key contains further object data which i want to read. i was able to read the data for purchases but purchases has further array data with contains products keys. i am unable to read that. i want a simple solution, no class implementation please!

docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Map<String, Object> data = (Map<String, Object>) document.getData().get("path");
                Set<String> keys = data.keySet();
                for (String s : keys) {
                    if (Objects.equals(s, "purchases")) {

                        Log.d(TAG, "onComplete: " + data.get(s));

                    }
                }
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

enter image description here

Here purchase is an array and each array element has further data which contains products key . and product is further nested into object. i want to make a llop to read data of products.

Thanks

Advertisement

Answer

I should just go with the data class implementation, pretty easy.

Make a few classes that match the result of the Firebase call:

class Purchases {
    public List<Purchase> purchases;

    public Purchases(List<Purchase> purchases) {
        this.purchases = purchases;
    }
}
class Purchase {
    public String id;
    public Double price;
    public List<Product> products;

    public Purchase(String id, Double price, List<Product> products) {
        this.id = id;
        this.price = price;
        this.products = products;
    }
}

class Product {
    public String addedOn;
    // More values

    public Product(String addedOn) {
        this.addedOn  = addedOn;
        // Add those values to the constructor too
    }
}

And then you should be able to use toObject()

docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                document.toObject(Purchases::class.java) // to Object here
            }
        }
    }
}

So you just need to make a few classes that will simply hold the data. You could read more here.

Advertisement