26-Mar-13 (Created: 26-Mar-13) | More in 'Android Public'

Passing an Object as a Parameter in Intent


I was dealing with a project where I have multiple pages and they both deal with the same object. The object was saved in the cloud. I could retrieve this object from cloud anytime I want and in any page. But I wanted to reduce the number of calls I make to the cloud backend. Here is what I need to do

  • 1)Retrieve the object from cloud once
  • 2)Create my own domain model and transfer the data from the cloud object to it.
  • 3)Make modification to the domain model based on user input in page 1.
  • 4)When user action takes them to page 2, pass the domain model object to page 2.
  • 5)Make modification to the same domain model in page 2
  • 6)Then save the object back to cloud.

To achieve the object transfer from page 1 to page 2(or activity 1 to activity 2) we need to follow the below steps
  • 1) Create a domain model which is serializable
  • 2) Add the object to the intent
  • 3) Retrieve the object from intent


Step 1: Creating Serializable Object


public class Event implements  Serializable {
	
	
	private String eventId;
	
	private String eventName;
	
	private String category;
}

You can implements the Serializable interface to make any object serializable.

Step 2: Add the Object to Intent


Event eventObj  = new Event();
Intent i = 	 Intent(Context packageContext, Class cls)
i.putExtra("Event", eventObj); 							
startActivity(i);


Step 3: Retrieve the object from Intent



Intent i = getIntent();
		
Event event = (Event) i.getSerializableExtra("Event");