再会。有什么方法可以实现这个吗?
val db = Firebase.firestore
val userID = Firebase.auth.currentUser!!.uid
val infoRef = db.collection("user").document(userID).collection("profile").document("info")
infoRef.get()
.addOnSuccessListener {document ->
if(document != null){
//get the data as cast to hashmap
val data = document.data as HashMap<*, *>
//get the username field and set text for greet user as the same value inside firestore
val username = data["username"] as String
tv_greet_user.text = "Hello, $username"
}
}
//将上面的代码提取为一个名为“getUsername()”的新方法
val 用户名 : String = getUsername()
tv_greet_user.text = "Hello, $username"
是的,您可以创建一个如下所示的函数:
fun getUsername(data: HashMap<String, Any>) = data["username"] as String
在你的回调中只需调用:
val username = getUsername(data)
有没有办法将整个块提取到一个单独的方法中?因此,在 onCreate 方法中,我可以简单地将 TextView 更改为以下内容: val username = getUsername() tv_greet_user.text = "Hello, $username"
Edit:
正如 Frank van Puffelen 在他的《你》中提到的那样无法返回异步操作的结果作为一种方法的结果。由于您使用的是 Kotlin 编程,请注意实际上没有解决方案。我写了一篇文章,名字叫:
- 如何使用 get() 从 Cloud Firestore 读取数据?
我在其中解释了从 Firestore 获取数据的四种方法。所以如果你愿意使用Kotlin 协程,那么事情就会简单得多。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)