Home > other >  How to get list from Firestore in Kotlin
How to get list from Firestore in Kotlin

Time:12-28

I need to get the data from a list in Firestore. I searched but don't find any results for this, even in the Firebase Documents.

The list is a List of Strings. Let's call him Users. The Users list brings a list of names. How can I get just the values from the Firestore?

The code I'm using is

firestoreClient.collection("Users").get().addOnSuccessListener { result -> }

What do I do inside the addOnSuccessListener method?

I Already tried something like document.data but don't work for a list, because a list brings Any data type.

CodePudding user response:

Try the following code.

val db = Firebase.firestore
var userNameList = listOf<String>()             //<-- To store list of user's name
db.collection("Users").get().addOnSuccessListener { documents ->
     for (document in documents) {
        
        // assuming the attribute name is 'userName'
         val userName = document["userName"].toString()  

       // add the userName to the list
         userNameList  = userName        
     }
}

CodePudding user response:

Since you're using Kotlin, the simplest method to read user documents would be to call get() and attach a listener. And in code, it would be as simple as:

val usersRef = Firebase.firestore.collection("Users")
usersRef.get().addOnCompleteListener {
    if (it.isSuccessful) {
        var names = mutableListOf<String>()
        for (document in it.result) {
            val name = document.getString("name")
            names.add(name)
        }
        //Do what you need to do with the list
        Log.d(TAG,"${names.size}")
    } else {
        Log.d(TAG, "${it.exception?.message}") //Never ignore potential errors!
    }
}
  • Related