如何在Kotlin中编写一个方法,将从Firestore返回字符串?



这不是重复的,建议的链接是JAVA,但我正在寻找Kotlin

我想写一个方法,将returnFirestore文档的特定字段的值。我知道如何获取值,但我不能返回值。

这是我的。

fun getCurrentUserType(): String {
var userType = ""
mFireStore.collection("users")
.document(getCurrentUserID())
.get()
.addOnSuccessListener { document ->
val usrType: String? = document.getString("user_type")
if (usrType != null) {
userType = usrType
}
}
return userType
}

正如你所知道的,这个返回语句在从Firestore获取数据之前执行,所以它是没有用的。

正如我在Stackoverflow上读到的,返回方法必须在addOnCompleteListener中。我不能在上面的代码中调用addOnCompleteListener,我试着这样做,但这不起作用。你能帮忙吗?

我通过使用以下代码在Logcat中获得正确的值。

如下所示。

fun getCurrentUserType(): String {
mFireStore.collection("users").get().addOnCompleteListener { task ->
if (task.isSuccessful) {
val list = ArrayList<String>()
for (document in task.result) {
val userType = document.data["user_type"].toString()
list.add(userType)
}
Log.d("UserType is ", list[0])
val userTye = list[0]
return@addOnCompleteListener userTye
}
}
}

我知道如何获得值,但我不能返回值。

您已经注意到,您可以读取字段的值,但是不能返回它,这是有意义的,因为Firebase API是异步的。这意味着,任何需要从Firestore获取数据的代码,都需要在onComplete()方法中,或者从那里调用。

简而言之,除非您没有特殊的机制,否则您无法将userType对象作为方法的结果返回。发生这种情况是因为数据加载完成需要一些时间。

我最近写了一篇文章叫:

  • 如何读取数据从云Firestore使用get()?

我已经解释了四个您可以使用以下方式与Firestore交互:

回调
  • Android Architecture Components ->ViewModel + LiveData
  • 芬兰湾的科特林协同程序
  • <
  • 异步流/gh>

    由于您正在寻找从数据库调用返回数据的方法,因此最后三个解决方案将帮助您实现这一目标。请记住,这些处理异步编程的方法是由Android团队推荐的。

  • doc.data()是一个对象,您可以像获取任何其他对象的字段数据一样获取字段数据。

    mFireStore.collection("users").get().then((doc) => {
    if (doc.exists) {
    let data = doc.data()
    let yourField = data.yourFieldsName
    } else {
    // doc.data() will be undefined in this case
    console.log("No such document!");
    }
    

    最新更新