Search code examples
androidkotlinparcelable

how to implement parcelable to ArrayList of Mutable Map?


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


Solution

  • 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
            }
        }
    }