How I can check array length from google cloud firestore For Android

Viewed 36

I am developing an Android app and want to check array length in Cloud Firestore. I have tried many times but could not find a solution. Can you help me?

edited below:

I want to get the size of the array that which user favorited it. Below is my array in Firestore. Also, I can access document II, because I save it when It is created first. firestore screenshot

The code which I get fail is below: code screenshot

I really tried many times but cannot get size of array.

1 Answers

As I understand from your question, you need to read the size of the favoriteUser array that exists in all documents that are returned by your query. In this case, most likely you should use a simple get() call rather than reading the data in real-time. So the simplest solution would be:

val query = Firebase.firestore.collection("Created").whereEqualTo(someId)
query.get().addOnCompleteListener {
    if (it.isSuccessful) {
        for (doc in it.result) {
            val obj = doc.getData()["favoriteUser"]
            if(obj != null) {
                val arraySize = (obj as List<String>).size
                Log.d("TAG", "$arraySize")
            }
        }
    }
}

Remember that DocumentSnapshot#getData() returns an object of type Map<String, Object>, so that's the reason why we can read the content inside it.

Related