Please note: If you are using a AppCompatActivity, you will have to call the
protected void onSaveInstanceState(Bundle outState) {} (NOTpublic void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {}) method.
I am using my kotlin implementation of Parcelable to achieve that and so far it works for me.
It is useful if you want to avoid the heavy serializable.
Also in order for it to work, I recommend using it with these
Declaration
class ParcelableMap<K,V>(val map: MutableMap<K,V>) : Parcelable {
constructor(parcel: Parcel) : this(parcel.readMap(LinkedHashMap<K,V>()))
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeMap(map)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<ParcelableMap<Any?,Any?>> {
@JvmStatic
override fun createFromParcel(parcel: Parcel): ParcelableMap<Any?,Any?> {
return ParcelableMap(parcel)
}
@JvmStatic
override fun newArray(size: Int): Array<ParcelableMap<Any?,Any?>?> {
return arrayOfNulls(size)
}
}
}
Use
write
val map = LinkedHashMap<Int, String>()
val wrap = ParcelableMap<Int,String>(map)
Bundle().putParcelable("your_key", wrap)
read
val bundle = fragment.arguments ?: Bundle()
val wrap = bundle.getParcelable<ParcelableMap<Int,String>>("your_key")
val map = wrap.map
Don't forget that if your map K,V are not parceled by default they must implement Parcelable