Question

I have a few objects I want to pass to other activities through intents. However, they only need to be shallow copies of the other object, as they are only going to be read (and even if they were going to be modified, I would want them modified in the original activity too), so there's no point in making the object a serializable, also because not all of the fields in the object are serializable, I can't even do it.

Also, it seems like making it parcelable would run into the same problems. Sure, it seems like I can add some of the fields in it as active objects, but I can't make the whole thing just a shallow copy.

So is there any way I can make a shallow copy of an object in an intent, or any other way of passing a shallow copy of data to another activity, like you would normally pass a parameter in java? Thank you.

Was it helpful?

Solution

JesusFreke is correct that you cannot pass a reference (pointer) to an object via an Intent. An Intent is meant to be serialized data not a reference to that data. However, I would recommend against the static map technique as it is often a source of memory leakage. Instead I would recommend creating a subclass of android.app.Application and using it to store references to whatever data structures that you need to share across Activities.

OTHER TIPS

When you send an intent, the intent and all the data associated with it has to be marshaled across process boundaries. The only way this can occur is if the object is parcelable.

However, if the code that is sending the new intent is in the same process as the activity that is being started by the intent, you could do something like create a static map to hold the data that you want to send to the new activity, and then pass a key to that data in the intent, with which the new activity can look up the data from the map.

However, my only concern with this type of an approach is that it is possible that you send an intent, and then the process dies before the new activity is started. And then the process is restarted for the new intent, but then the data you had stored in the map is obviously gone. I would guess that this would likely be a very rare occurrence though.

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