Home > Software design >  Read Map Values within Array Firestore Kotlin
Read Map Values within Array Firestore Kotlin

Time:11-06

I'm trying to retrieve and store the values within this Map in my Firestore. The way I have my Firestore set up is like so:

I've found a way to retrieve other fields within my Firestore database but when trying to access map values like so:

horsepowerTextView.text = result.data?.getValue("Horsepower").toString()

it crashes the application and gives me an error saying that "Key Horsepower is missing in the map".

Can you please tell me how I would be able to get the values within Cars?

The following picture shows Firestore layout and code:

Code within Android Studio

Firestore Layout

I've tried this link (Code Tried

CodePudding user response:

I actually answered that question, but your use case is totally different than the linked one. Why? Simply because "Cars" is an array of maps (custom objects). If you only want to get the value of the "Horsepower" field, then simply use the following lines of code:

val db = Firebase.firestore
val usersRef = db.collection("users")
usersRef.document("TwbJb27eFL3HAS1xLhP1").get().addOnCompleteListener {
    if (it.isSuccessful) {
        val data = it.result.data
        data?.let {
            val cars =  data["Cars"] as List<*>
            for (car in cars) {
                val carMap = car as Map<*, *>
                val horsepower = carMap["Horsepower"]
                Log.d(TAG, "$horsepower")
            }
        }
    }
}

The result in the logcat will be:

120

If you want however to map the "Cars" array into a list of custom objects, then I recommend reading the following resource:

  • Related