Home > Net >  How implement new `.getSerializable()` method to deserialize data into hashmap from saved instance b
How implement new `.getSerializable()` method to deserialize data into hashmap from saved instance b

Time:07-27

I was using bundle.getSerializable("data") as HashMap<Int, Int>

but after changing sdkVersion to 33 .getSerializable() API is updated.

I am unable to implement it for HashMap<Int, Int>

I tried -

savedInstanceState.getSerializable("answer", HashMap<Int, Int>::class.java)!!

but it gives warning -

Only classes are allowed on the left hand side of a class literal

After some searching I found this stack post

The respective answer(above cited) quote -

You can't use generics with class

Now I am not getting the solution of this problem. Any suggestion?

CodePudding user response:

You should use HashMap::class.java and cast it to HashMap<Int, Int>.

val map = HashMap<Int, Int>()
map[1] = 123

val bundle  = Bundle()
bundle.putSerializable("answer", map)

val serializedMap = bundle.getSerializable("answer", HashMap::class.java) as HashMap<Int, Int>
println(serializedMap[1])
  • Related