Search code examples
androidkotlinonsaveinstancestate

kotlin, how to make a hashMap parcelable


Having a variable is hashMap<IntRange, String>, and need to put in bundle as parcelable to be saved and restored in onSaveStateInstance()/onCreateView() :

val map: HashMap<IntRange, String>? = hashMapOf(IntRange(0, 4) to "x", IntRange(5, -1) to "y")

and do

//saving:
outState.putParcelable("saved_map", map)

...
//retrieving: 
val map = bundle.getParcelable("saved_map")

Solution

  • I would suggest using a wrapper class nonetheless, just because it's much simpler in Kotlin than in Java. @Parcelize supports HashMap, the problem is that it doesn't support IntRange (or at least it isn't listed). But based on the example there, it seems this should work:

    object IntRangeParceler : Parceler<IntRange> {
        override fun create(parcel: Parcel) = IntRange(parcel.readInt(), parcel.readInt())
    
        override fun IntRange.write(parcel: Parcel, flags: Int) {
            parcel.writeInt(value, start)
            parcel.writeInt(value, endInclusive)
        }
    }
    
    @Parcelize
    @TypeParceler<IntRange, IntRangeParceler>()
    class IntRangeStringMap(val value: HashMap<IntRange, String>)
    

    and your calls become

    outState.putParcelable("saved_map", IntRangeStringMap(map))
    val map = bundle.getParcelable("saved_map").value
    

    You can even get it looking the way you want by adding extension functions.