androidbundle

Data class serialization to store it in Android bundle


Question like why does it work? When I use standalone Customer object, storing it to bundle throws an exception and of course, it requires Serializable or Parcelable implementation. On the other hand, when I wrap Customer object to List, it starts working without any further changes. How it is possible, that classes wrapped in List can be stored in Bundle and are serialized automatically?

data class Customer(
    val id: Long,
    val name: String
)

bundleOf("CUSTOMER" to Customer(1, "John")) // throws IllegalArgumentException

bundleOf("CUSTOMERS" to listOf(Customer(1, "John"))) // works

I expect, that storing list of non serializable or non parcelable objects would also lead to crash while trying to store them to Android bundle.


Solution

  • The bundleOf doesn't know how to handle the Customer type, while listOf() produces a Serializable. That's the only reason why you're able to create a bundle when using the list.

    But since you're not doing anything parcelable related with the bundle, even when you change the oritientation, there's no error with it. It just persists in memory.

    Once you actually parcel the bundle, you'll receive the following error from writeValue:

    java.lang.RuntimeException: Parcel: unable to marshal value Customer(id=1, name=John)