Search code examples
androidandroid-fragmentspass-by-referenceparcelablepass-by-value

Passing Objects from Activity to Fragments is Pass by Reference


When we use Serializable and Parcelable to pass object between activities then a copy/value of the object is sent to the receiving activity(Typical Pass by value behaviour).

But why is it that when we pass objects to Fragments as Parcelable inside Bundle, for some reason they are sent as reference of object instead of copy/value of the object (Pass by Reference behaviour).I haven't checked this out for Serializable but i believe it would be the same.

The object is passed the same way so why is there a difference in how the Activity receives the object and how the Fragment receives it ?


Solution

  • But why is it that when we pass objects to Fragments as Parcelable inside Bundle, for some reason they are sent as reference of object instead of copy/value of the object

    That is not guaranteed. For example, if you undergo a configuration change, or your process is terminated but the user returns to your task quickly, you will get a copy.

    The object is passed the same way so why is there a difference in how the Activity receives the object and how the Fragment receives it ?

    Starting an activity always involves IPC, and therefore always involves copying data across process boundaries.