0

I have this property in my class that the data type is ArrayList<MutableMap<String,Any>> , but I am confused what should I write in parcel constructor and also in writeToParcel method ?

class User() : Parcelable {
     var uid : String = ""
     var upcomingEvents : ArrayList<MutableMap<String,Any>> = ArrayList()

  constructor(parcel: Parcel) : this() {
     uid = parcel.readString() ?: ""
     upcomingEvents = ....... // <-- what should I write in here ?

  }   

  override fun writeToParcel(parcel: Parcel, flags: Int) {
     parcel.writeString(uid)
     parcel........ // <--- and also here ???

  }

java or kotlin is okay

Alexa289
  • 8,089
  • 10
  • 74
  • 178
  • you can use [@Parcelize](https://kotlinlang.org/docs/tutorials/android-plugin.html#parcelable-implementations-generator) it generates all the code unless you have a custom implementation you have to write it – Mohammed Alaa Jan 19 '20 at 07:46

1 Answers1

0

As Mohammed Alaa already mentioned, in Kotlin you can use the @Parcelize annotation to have all code generated automatically:

import android.os.Parcel
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize

@Parcelize
data class User(var uid: String, var upcomingEvents: List<MutableMap<String, Any>>) :
    Parcelable

If you use the Any class, this approach will not work. In that case you could go for changing from Any to a class that is supported by Parcelize or write the code yourself. Something like this:

data class User(var uid: String, var upcomingEvents: List<MutableMap<String, Any>>) :
    Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString() ?: "",
        readUpcomingEvents(parcel)
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(uid)
        parcel.writeList(upcomingEvents)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<User> {
        override fun createFromParcel(parcel: Parcel): User {
            return User(parcel)
        }

        override fun newArray(size: Int): Array<User?> {
            return arrayOfNulls(size)
        }

        private fun readUpcomingEvents(parcel: Parcel): List<MutableMap<String, Any>> {
            val list = mutableListOf<MutableMap<String, Any>>()
            parcel.readList(list as List<*>, MutableMap::class.java.classLoader)

            return list
        }
    }
}
Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28