Jayson Tamayo
Jayson Tamayo

Reputation: 2811

Counting Array in a Collection in Firestore in Android

I am trying to count the array which is contained in a collection. The data is structured like this:

{requests=[{name=Jayson, created=1599139605672, from=jayson123, to=marco123, timestamp=2020-09-03T13:26:45+00:00}]}

In the example above I would like to count how many arrays does the requests collection contains, which in that case is 1.

I am using snapshot.getData().size() but it is always returning 1. Can you help me pls.

Upvotes: 0

Views: 97

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317808

If you want to know the size of a list type field in a document, you have to:

  1. Read the document as a DocumentSnapshot
  2. Get the field by name - it will be a generic List type object
  3. Use the size() method on that List.

It will be something like this, assuming you have a snapshot:

DocumentSnapshot snapshot = ...
List<Object> requests = (List<Object>) snapshot.get("requests");
int size = requests.size();

Upvotes: 1

Related Questions