Firebase Firestore Kotlin API error getting data into custom object: None of the following functions can be called with the arguments supplied

Viewed 633

I try to use Firebase Firestore in a Kotlin Android project. I have an issue when I try to instantiate an object with DocumentSnapshot.toObject(Class valueType). I am trying to read a single object from a collection called 'news' with id eq 1. I can read the data but the API won't let me put the document into my custom object.

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>()
    }

Error in IDE is:

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

Thanks!

1 Answers

It looks like you're not including the Kotlin Extensions (KTX) version of the Firebase SDK, which defines the generic overload of toObject that you're trying to use.

I'll show both options below, since this seems to be quite common.


Using the regular Java/Android SDK

Include the SDK with:

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

Get the object from the data with:

documentSnapshot.toObject(News::class.java)

Using the Android SDK with Kotlin Extensions

Include the SDK with:

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

Get the object from the data with:

documentSnapshot.toObject<News>()
Related