Is it possible to create a HashMap that is Parcelable on Android?

前端 未结 1 860
萌比男神i
萌比男神i 2020-12-31 07:35

I am trying to extend HashMap as a Parcelable and I got the syntax to compile, however, at runtime it throws an exception and returns a null pointer trying to un-marshal the

相关标签:
1条回答
  • 2020-12-31 07:41

    The way your class ContentItemContainer is implemented - as extending HashMap, your writeToParcel and Parcelable.Creator will never be called.

    The reason is that Map is a valid data type to be put in a Parcel, so that the class gets flattened using the logic of the HashMap class, and not yours. This is because the way Parcel is implemented, it checks whether the supplied values are descendants of certain classes in a specific order.

    When unparcelling the extras, a HashMap will be created from your object's data consequently.

    To work around this, you could hide the HashMap inside your class and expose getters/putters for the HashMap. This is exactly the same way that ContentValues is implemented, and parcelling/unparcelling it works without any problems.

    0 讨论(0)
提交回复
热议问题