learningtech
learningtech

Reputation: 33715

Android - Passing object to activity when object is not serializable or parcelable

I want to pass an object to another activity. My object is not parcelable or serializeable because it contains properties that are objects that are themselves not parcelable or serializable. And the properties of these properties are not parcelable or serializable. And the properties of these properties of these properties etc... are not parcelable or serializable.

I do not have authorization to modify the code to these child objects that are properties. Thus, I do not have permission to make them implement serializable or parcelable.

What are other options I can consider to pass an object to another activity?

Upvotes: 3

Views: 1298

Answers (3)

Steve Benett
Steve Benett

Reputation: 12933

In addition to Trevors answer I want to give more details.

There are two recommanded ways to do this. Have a look at this question for a detailed discussion.

  • Use a Singelton class to save your data while switching Activities. Write your data to it from the caller and read from it by the callee.

  • Extend the Application class, which is the base class to save the global states of an App.

The general idea is to save the data to a place, which is independent from the Activity lifecycle and can be accessed global.

Here is a blog post how to use these approaches.

Upvotes: 0

Michal
Michal

Reputation: 998

Although it is a ugly solution, you can serialize them into JSON. If you have public access to these objects. Use e.g. Gson to do such a thing and then pass a JSON string as Intent extra. Another solution is to save them in Application object. (even more ugly)

If the object could not be serialized (e.g. object which holds persistent TCP connection) you need to store it in some singleton object or any other which can be referenced from Application perspective.

Upvotes: 0

Trevor
Trevor

Reputation: 10993

Pass your Activity a key string that it can use to retrieve the object from a singleton class such as an extended Application class. The Activity would retrieve the object from there again after configuration changes (e.g. rotation). Don't forget to ensure the Activity gracefully handles the situation where the object returned is null, in the case of the application being resumed after all data has been killed.

Upvotes: 1

Related Questions