Home > Net >  Retrieving custom object from Firebase Firestore field using kotlin
Retrieving custom object from Firebase Firestore field using kotlin

Time:06-07

I am trying to retrieve a field from the Firebase Firestore and put it into a custom object. I managed to upload the custom object from code without any problem, but when I am trying to read and access the list of objects from Firestore, I keep getting the following error:

java.lang.ClassCastException: java.util.HashMap cannot be cast to SelfMadeQuestion

The SelfMadeQuestion class looks like this:

class SelfMadeQuestion(
    var openQuestion: Boolean = false,
    var questionText: String = "",
    var answers: List<String>? = mutableListOf(),
    var rightAnswer: String? = ""
) {}

And this is what I have tried to do in order to read the list of SelfMadeQuestion s from firebase:

 fStore.collection("users").get().addOnSuccessListener { documents ->
                /**
                 * start loading data
                 * */

                for (it in documents) {
               
                 val questions = it.get("selfMadeQuestions") as 
                                 MutableList<SelfMadeQuestion>?

                                       }

And this is a picture from the database: enter image description here

Since uploading the custom object to firebase is possible and works fine, I am wondering whether there is any way to read the field as an object?

CodePudding user response:

Please note that DocumentSnapshot#get(String field) method, returns an object of type Object. Since the selfMadeQuestions field is composed of pairs of keys and values, the type of object that is returned is a HashMap.

So you're getting the following error:

java.lang.ClassCastException: java.util.HashMap cannot be cast to SelfMadeQuestion

Because you're trying to convert a HashMap into an object of type SelfMadeQuestion, which is actually not possible in Kotlin.

The simplest solution that I can think of would be to create another class that contains a List<SelfMadeQuestion>:

class SelfMadeQuestions(
    var selfMadeQuestions: List<SelfMadeQuestion> = mutableListOf()
)

Then you can simply map that array into a List<SelfMadeQuestion> like this:

fStore.collection("users").get().addOnSuccessListener  { documents ->
    for (doc in documents) {
        if (doc.get("selfMadeQuestions") != null) {
            val questions = doc.toObject(SelfMadeQuestions::class.java).questions
            Log.d(TAG, questions.size.toString())
        }
    }
}

The result in the logcat will be the size of each list. To understand it better, I also recommend you to read the following article:

  • Related