Home > OS >  Read Firestore Data in Android Java
Read Firestore Data in Android Java

Time:06-27

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

CodePudding user response:

I should just go with the data class implementation, pretty easy. (Sorry for the code, it is in Kotlin, but you can make it in Java)

Make a data class that matches the result of the Firebase call.

// SORRY FOR THE KOTLIN
data class Purchases (
    val purchases: List<Purchase>? = null,
)

data class Purchase (
    val id: String? = null,
    val price: Double? = null,
    val products: List<Pruduct>? = null,
)

data class Pruduct (
    val addedOn: String? = null,
    // More values
)

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 class that will simply hold the data.

  • Related