android - Firebase Firestore Kotlin API 将数据导入自定义对象时出错 : None of the following functions can be called with the arguments supplied

标签 android firebase kotlin google-cloud-firestore

我尝试在 Kotlin Android 项目中使用 Firebase Firestore。当我尝试使用 DocumentSnapshot.toObject(Class valueType) 实例化对象时遇到问题。我正在尝试从 ID 为 1 的名为“新闻”的集合中读取单个对象。我可以读取数据,但 API 不允许我将文档放入我的自定义对象中。

News.kt

data class News(
     val id : String? = "",
     val value : String? = ""
)

HomeFragment.kt

val db = FirebaseFirestore.getInstance()

var newsItem = db.collection("news").document("1")
newsItem.get()
    .addOnSuccessListener { documentSnapshot ->

        android.util.Log.d("TAG", "${documentSnapshot.id} => ${documentSnapshot.data}")

        var newsTextView : TextView = view.findViewById(R.id.homeNewsText)
        val newsText = documentSnapshot.toObject<News>()
    }

IDE 中的错误是:

None of the following functions can be called with the arguments supplied. toObject(Class<News!>)   where T = News for   fun <T : Any!> toObject(valueType: Class<T!>): T? defined in com.google.firebase.firestore.DocumentSnapshot toObject(Class<News!>, DocumentSnapshot.ServerTimestampBehavior)   where T = News for   fun <T : Any!> toObject(valueType: Class<T!>, serverTimestampBehavior: DocumentSnapshot.ServerTimestampBehavior): T? defined in com.google.firebase.firestore.DocumentSnapshot

谢谢!

最佳答案

您似乎没有包含 Firebase SDK 的 Kotlin Extensions (KTX) 版本,它定义了您尝试使用的 toObject 的通用重载。

我将在下面展示这两个选项,因为这似乎很常见。


使用常规的 Java/Android SDK

将 SDK 包含在:

implementation 'com.google.firebase:firebase-firestore:21.5.0'

从数据中获取对象:

documentSnapshot.toObject(News::class.java)

将 Android SDK 与 Kotlin 扩展结合使用

将 SDK 包含在:

implementation 'com.google.firebase:firebase-firestore-ktx:21.5.0'

从数据中获取对象:

documentSnapshot.toObject<News>()

关于android - Firebase Firestore Kotlin API 将数据导入自定义对象时出错 : None of the following functions can be called with the arguments supplied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63054611/

相关文章:

kotlin - 未找到生成的类

kotlin - 如果第一个参数为true,则必须在函数中传递第二个参数

java - 仅在一个目录中调用 MediaScanner (android)

java - DecimalFormat 和 Double 异常

java - 获取 Firebase 子项计数

ios - Flutter [firebase_messaging] IOS 构建错误

java - 是否可以使用 Android Studio 将 Kotlin 转换为 Java?

java - 如何在选项卡更改时更改 Activity 标题(滑动 TabLayout)

Android:从我正在运行的服务中获取变量

java - 此应用无权在 app-release.apk 中使用 Firebase 身份验证