我尝试在 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/