Monday 16 January 2012

Android Intents - Passing Serializable Custom Objects to an Activity

The passing of custom objects to an Activity using Intents can seem very confusing - honestly I never quite worked out how to use Parcelable. It seemed like a lot of code for passing a custom object to one of my activities. The method of passing objects I settled for was one that required the least amount of code and did the job.

That method is to implement Serializable for the object's class you want to pass to an activity. Then simply pass that serialized object into the intent and grab it when the activity is started. This stackoverflow question does point out its downfalls however, so beware, the most important downfalls for me would be that its slow and can cause increased gc activity. I promise I will spend time with Parcelable and write a blog post on it, and make it as easy as possible to understand!

Here is our custom object we are going to pass to another activity, notice it implements Serializable, this is very important as when we use putExtra(String name, Serializable value) in our intent it takes a Serializable parameter.
import java.io.Serializable;

public class Present implements Serializable
{

 private final String text;

 public Present(String text)
 {
  this.text = text;
 }

 public String getText()
 {
  return text;
 }

}
Now in the activity class where you start another activity using an intent, use this code.
Present myPresent = new Present ("Red Bike");
Intent intent = new Intent(this, SecondActivity.class); // replace with own Activity class
intent.putExtra("present", myPresent);
startActivity(intent);
From the 'SecondActivity' class you can get the object back by doing this:
Intent intent = getIntent();
Present myPresent = (Present)intent.getSerializableExtra("present");
Log.v("Tag", "My Present is: " + myPresent.getText());
Now you should be able to send and receive custom objects to other activities!

No comments:

Post a Comment