[英]How to get list from Firestore in Kotlin
I need to get the data from a list in Firestore.我需要从 Firestore 的列表中获取数据。 I searched but don't find any results for this, even in the Firebase Documents.我搜索但没有找到任何结果,即使在 Firebase 文档中也是如此。
The list is a List of Strings.该列表是一个字符串列表。 Let's call him Users
.让我们称他为Users
。 The Users
list brings a list of names. Users
列表带来了一个名称列表。 How can I get just the values from the Firestore?我怎样才能只从 Firestore 中获取值?
The code I'm using is我使用的代码是
firestoreClient.collection("Users").get().addOnSuccessListener { result -> }
What do I do inside the addOnSuccessListener
method?我在addOnSuccessListener
方法中做什么?
I Already tried something like document.data
but don't work for a list, because a list brings Any data type.我已经尝试过类似document.data
的方法,但不适用于列表,因为列表会带来 Any 数据类型。
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
}
}
Since you're using Kotlin, the simplest method to read user documents would be to call get() and attach a listener.由于您使用的是 Kotlin,读取用户文档的最简单方法是调用 get() 并附加一个侦听器。 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!
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.