I'm passing a parcelable object to a fragment by adding into a bundle while creating the fragment. In onc instance modification to this parcelled object reflects modification in original object and in another case it is not. I'm a little baffled by this behaviour. Till now I have assumed retrieving a parcelled objects through a bundle always create new object[no sure whether it's shallow copy or deep copy].
Someone please clarify parcelable behaviour.
I was struggling with a similar issue. At the first glance it seems that we always obtain a new deep copy from the parcelled objects. Moreover, there are even some StackOverflow answers which suggest to use
Parcelable
interface to clone objects. All this just increases confusion regarding the subject.Here is what I've found after a lot of searching and googling:
Parcel
documentation. Here is the important quote:Ok, as you can see, there are some special objects that are not being copyed during unparceling. But this is still a bit confusing. Does it mean we have another strong reference to the original object which prevents its garbage collection? And what are the use-cases for such objects?
To answer the aforementioned questions I decided to look through the Android source code. The methods I was looking for are
readStrongBinder
andwriteStrongBinder
which according to the docs do not cause a new object creation when the parcels are sent/received. And I think I found the desired answer in the ResultReceiver.java class. Here is the interesting line:To understand what is this line actually doing we should go to the official AIDL documentation. Here are the most important parts:
So let's put all things together:
readStrongBinder
method no new instances are being created. We just objtain a new reference to the original object and this reference can prevent its dealllocation.Parcelable
interface implementation.Hope this info will help you.
If you want to read about a real-world example when the confusion regarding
Parcelable
objects can cause serious problems check out my blog post.