harism
harism

Reputation: 6073

Bundle.putParcelable / getParcelable pair returns same object instance

I spent quite a while debugging a parcelable object acting weird in my application. Eventually I noticed, luckily, that an object sent via Bundle, in this case Fragment arguments, might be the exact same object I pass to it.

Consider following code snippet in which r2 is not a copy, as I would have expected, but the same object r instead;

Rect r = new Rect();
Log.d("r", r.toString());     // Rect(0, 0 - 0, 0)
Bundle bundle = new Bundle();
bundle.putParcelable("KEY", r);
Rect r2 = bundle.getParcelable("KEY");
r2.set(100, 100, 100, 100);
Log.d("r", r.toString());     // Rect(100, 100 - 100, 100)
Log.d("r2", r2.toString());   // Rect(100, 100 - 100, 100)

Now the question would be is there documentation about this behaviour somewhere? I'm running into this behaviour on Android 5.1 on Nexus 5 and would be interested in knowing is this something that existed already in API 1 for example and in which situations it'll return a copy instead via creator.

I'm sure there is but I fail to find correct search keywords.

Upvotes: 3

Views: 2011

Answers (3)

frogatto
frogatto

Reputation: 29285

If you take a look at putParcelable source code, you will find that this method only saves its reference (i.e. memory address).

If you would need to store a copy/clone of that object, you should copy/clone that object manually and then pass its reference to this method.

Upvotes: 2

Orest Savchak
Orest Savchak

Reputation: 4569

public void More ...putParcelable(String key, Parcelable value) {
     unparcel();
     mMap.put(key, value);
     mFdsKnown = false;
 }

I don't know what magic does "unparcel()" method, but sources say that it is just Map with reference value.

Upvotes: 1

Bojan Kseneman
Bojan Kseneman

Reputation: 15668

You should be aware that data you put into a bundle gets passed by a reference, not a copy of object so in the same class this will be the same object. On the other end (in your fragment, upon creating it) tough, the object is deserialized (unmarshalled) so this makes a copy of your original data.

Upvotes: 3

Related Questions