How can I pass an object of a custom type from one Activity to another using the
putExtra()
method of the class Intent?
Another way to do this is to use the Application
object (android.app.Application). You define this in you AndroidManifest.xml
file as:
You can then call this from any activity and save the object to the Application
class.
In the FirstActivity:
MyObject myObject = new MyObject();
MyApplication app = (MyApplication) getApplication();
app.setMyObject(myObject);
In the SecondActivity, do :
MyApplication app = (MyApplication) getApplication();
MyObject retrievedObject = app.getMyObject(myObject);
This is handy if you have objects that have application level scope i.e. they have to be used throughout the application. The Parcelable
method is still better if you want explicit control over the object scope or if the scope is limited.
This avoid the use of Intents
altogether, though. I don't know if they suits you. Another way I used this is to have int
identifiers of objects send through intents and retrieve objects that I have in Maps in the Application
object.