Home > Net >  how to read mapped data from firestore in kotlin
how to read mapped data from firestore in kotlin

Time:11-23

I am trying to read mapped data from Firestore. I am reading data but I do not know how to reach one of the keys in the map.

this is mapped data

dbSaveAvailableTimes.addSnapshotListener { snapshot, e ->
            if (snapshot != null && snapshot.exists()) {
                val chaplainAvailableTimes = snapshot.data
                if (chaplainAvailableTimes != null) {
                    Log.d("chaplainAvailableTimes", chaplainAvailableTimes.toString())
                }

I read the data here.

D/chaplainAvailableTimes: {1637868400000={patientUid=null, isBooked=false, time=1637868400000}, 1637863200000={patientUid=null, isBooked=false, time=1637863200000}}

I get results like this in the log.

when I try the chaplainAvailableTimes["time"], I get null.

So, how can I take the time key data after that? I am not familiar with the map in Kotlin. thanks for your help in advance?

CodePudding user response:

According to my last question:

So to understand better, you want to read the value of "time" that exists under each object, right?

And your last answer:

hi, yes. thanks

To get the values of "time" from within each object, please use the following lines of code:

val db = FirebaseFirestore.getInstance()
val availableTimesRef = db.collection("chaplainTimes").document("availableTimes")
availableTimesRef.get().addOnCompleteListener {
    if (it.isSuccessful) {
        val data = it.result.data
        data?.let {
            for ((key, value) in data) {
                val v = value as Map<*, *>
                val time = v["time"]
                Log.d(TAG, "$key -> $time")
            }
        }
    }
}

The result in the logcat will be:

1637863200000 -> 1637863200000
1637868400000 -> 1637868400000

CodePudding user response:

You can get the list of times using this code:

// This will be a List<String>
val timeList = snapshot.data.values.map { (it as Map<*, *>)["time"] as String }
  • snapshot.data returns the MutableMap<String,Any>
  • .values returns the collection of map values Collection<Any>
  • .map transforms each value to get a List<String>
  • inside map we cast each value to a generic map Map<*,*>, fetch the value for key time and cast it to a String

CodePudding user response:

Try to cast chaplainAvailableTimes as val theData = chaplainAvailableTimes as? HashMap<*, *>. After that you will be able to iterate over it or get the data like this:

theData.values.first().get("time") // returns 1637868400000
  • Related