【问题标题】:How to write a method in Kotlin that will return a string from Firestore? [duplicate]如何在 Kotlin 中编写一个从 Firestore 返回字符串的方法? [复制]
【发布时间】:2021-10-04 12:19:17
【问题描述】:

这不是重复的,建议的链接是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
}

如你所知,这个return语句在从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
        }
    }

}

【问题讨论】:

  • 我可以知道是什么问题吗?

标签: android kotlin google-cloud-firestore


【解决方案1】:

我知道如何获取值,但我无法返回值。

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

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

我最近写了一篇文章叫:

我在其中解释了四种您可以使用以下方式与 Firestore 交互的方式:

  1. 回调
  2. Android 架构组件 -> ViewModel + LiveData
  3. Kotlin Coroutines
  4. Asynchronous Flow

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

【讨论】:

    【解决方案2】:

    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!");
        }
    

    【讨论】:

    • 我需要Kotlin的代码
    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    相关资源
    最近更新 更多