Reputation: 68
Is it any different that we refer to a class object that doesn't use parcelable?
When we value a Parcel, we have to make an object of that class. The same is true when reading it.
If we are actually referring to a class object when reading and writing, what difference does it make to using Parcelable that class?
Upvotes: 1
Views: 775
Reputation: 13019
While it takes a little effort to make a custom class implement Parcelable
, the reward is that one can easily pass them as extras to a Bundle
. A Bundle
is a data container used for communication between various components in the Android universe, see also this guide on Parcelables and Bundles.
Consider the case where you want to pass an instance of a custom class from an Activity
to a Fragment
. A Fragment
has an arguments Bundle
which is customarily used for initializing the Fragment
. (I suppose because the Bundle
will still accessible if the user navigates away from the app and the whole app is stopped and restored from the back stack an hour later. On the other hand, any values passed in via the constructor will be lost if the Fragment
did not save them in yet another Bundle
in onSaveInstanceState()
)
So it's good if a value can be stored in an Bundle
. Objects belonging to classes which implement Parcelable
are of this type, together with primitive data types, some arrays, lists and serializable objects.
It's even more convenient if the value can be retrieved without having to do a class cast, that's why I prefer Parcelable
over Serializable
whenever possible:
Suppose we have two classes which implement Serializable
respectively Parcelable
.
And suppose we have a Bundle b = getArguments();
To retrieve the Serializable
value, you need the following statement
SomeSerializableClass instanceOfSerializableClass = (SomeSerializableClass)b.getSerializable("keyForSerializableValue");
whereas for the Parcelable
value you can write
SomeParcelableClass instanceOfParcelableClass = b.getParcelable("keyForParcelableValue");
In Kotlin we have one of the rare cases where the statement is longer than its Java counterpart:
val instanceOfSerializableClass: SomeSerializableClass? = b.getSerializable("keyForSerializableValue") as SomeSerializableClass
compared to
val instanceOfParcelableClass = b.getParcelable<SomeParcelableClass>("keyForParcelableValue");
Upvotes: 2