Question

The question is simple, if I make an object parcelable, and put it into a bundle and create a fragment using the bundle. Does the object get cloned or is it referenced.

The context.

I have got an object stored/referenced in an ArrayList. Depending on the type of object in the ArrayList (polymorphism is used). I create a fragment suitable for dealing with it.

I need to also pass this object to the fragment. The fragment is used within a custom view pager. I do not wish to have duplicate objects and it seems to me parcelable clones objects.

Another method is to pass the index of the object in the ArrayList. and then get a reference to the arraylist from the fragment using getActivity().myList.get(Integer passed to ). But it doesn't seem very safe to me (ArrayList contents may change, although I simply delete everything and start again). I have also read, that you should avoid passing arguments to a fragments constructor as it may be recreated using the default no-args constructor.

(Although I'm currently destroying any recreated fragments as there are some strange problem with reattaching to the correct view, another post).

New sub-question: is there a way to pass a value by reference to a fragment?

Was it helpful?

Solution

The question is simple, if I make an object parcelable, and put it into a bundle and create a fragment using the bundle. Does the object get cloned or is it referenced.

It may get cloned, if not immediately, at other points in time (e.g., when the fragment's arguments Bundle is included in the instance state).

I have also read, that you should avoid passing arguments to a fragments constructor as it may be recreated using the default no-args constructor.

Correct.

Another method is to pass the index of the object in the ArrayList. and then get a reference to the arraylist from the fragment using getActivity().myList.get(Integer passed to ). But it doesnt seem very safe to me (ArrayList contents may change, although I simply delete everything and start again).

Don't use an ArrayList. Use a HashMap with a durable key. Pass the key to the fragment. Have the fragment get the data via the key. Make sure anyone deleting this object (and thereby removing it from the HashMap) does so only when this fragment does not exist, or notifies this fragment so it knows how to handle this scenario.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top