How To Get Data From Array in Firestore Collection Android Java

Viewed 22

I want to get the data from an array of a map from a Firestore collection. I m attaching an image to better understand my problem, I want to get the data in red, while the yellow is an Array and blue is Map. Tried many things, but not working. Any help will be appreciated. Thanks in advance.

Image of Firestore Collection

1 Answers

Yes, the field that is highlighted in yellow is an array. If you want to read the first element in the array, basically the object that exists at index 0, then you should create a reference that points to that particular document, make a get() call and attach a listener to read the data. If you need to map the element in the array into an object of a particular class, then you should create two classes that look like this:

class Game {
    public int added, id;
    public String name, slug;

    public Game() {}

    public Game(int added, int id, String name, String slug) {
        this.added = added;
        this.id = id;
        this.name = name;
        this.slug = slug;
    }
}

And:

class Document {
    public List<Game> games;
}

And perform the Firestore call:

db.collection("Home_New2").document("7ZEshkdgUIInTXo9H9Cv").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            Document document = task.getResult().toObject(Document.class);
            if (document != null) {
                Game firstGame = document.games.get(0);
                Log.d(TAG, firstGame.added + " / " + firstGame.id + " / " + firstGame.name + " / " + firstGame.slug);
            }
        } else {
            Log.d("TAG", "Failer with: ", task.getException());
        }
    }
});

The result in the logcat will be:

7676 / 3387 / Bloodborne / bloodborne

For more details, I recommend you check the following resource:

How to map an array of objects from Cloud Firestore to a List of objects?

Related