Passing objects from one Activity to another

When you want to transfer some parameters (String, int, whatever) in Android you can pass it via one of the Intent.putExtra methods. It’s simple as that. You can say:

int parameter = 42; // just an example

Intent intent = new Intent(currentActivity, newActivity.class);
intent.putExtra("myParameter", parameter);
startActivity(intent);

But what happens when you want a pass your custom made class instance? You can pass:

  1. it’s id and gather it from db or web service for example. That’s OK, but it’s a bummer if you have already have it, why do the same thing again?
  2. your class could implement Serializable interface. This is a perfectly working solution, but as many people said, it’s not an optimal solution (just take a look at stackoverflow)
  3. or use android’s Parcelable interface :)

Just to be clear, I don’t like implementing additional serializing/deserializing code, but as it turns out, it’s pretty simple to implement it, and it improves performance. So why not? :)

To make your class Parcelable, you have to implement the following methods:

int describeContents();
void writeToParcel(Parcel dest, int flags);

And you have to define a public static field named CREATOR (that implements Parcelable.Creator<T>)

Just take a look this example:

import android.os.Parcel;
import android.os.Parcelable;

import java.util.Date;

public class ExampleParcelable implements Parcelable {

   private String stringValue;
   private Integer integerValue;
   private char charValue;
   private boolean boolValue;
   private Date dateValue;

   @Override
   public int describeContents() {
      return 0;
   }

   @Override
   public void writeToParcel(Parcel dest, int flags) {
      dest.writeString(stringValue);
      dest.writeInt(integerValue);
      dest.writeInt(charValue); // yup, it's actually a char
      dest.writeInt(boolValue ? 1 : 0); // can't store bools, but we can do it this way
      dest.writeLong(dateValue.getTime()); // same here, can't write date's, but we can get time in long
    }

    // Added this default constructor in case you are using some JSON/XML whatever parsers that require no-arg constructor
    public ExampleParcelable() { }

    /**
    Just to make life easier, I've added a constructor that creates our ExampleParcelable from a Parcel (of course, you don't have to do it that way)
    */
   public ExampleParcelable(Parcel parcel) {
       // The only important thing is to read them in the same
       // order as you wrote them (take a look at writeToParcel)
       stringValue = parcel.readString();
       integerValue = parcel.readInt();
       charValue = (char) parcel.readInt();
       dateValue = new Date(parcel.readLong());
   }

   public static final Parcelable.Creator CREATOR = new Creator<UserContentInfo>() {

    @Override
    public ExampleParcelable createFromParcel(Parcel source) {
       return new ExampleParcelable(source);
    }

   @Override
   public ExampleParcelable[] newArray(int size) {
      return new ExampleParcelable[0];
   }
};

}

It’s pretty much straight forward. In writeToParcel method you need to write fields that you need (in case you don’t want to pass every field), and later in CREATOR’s createFromParcel read every field in the same order you’ve written to Parcel in the first place.

I’ve added an example how can you write, and later read char and date types. Because can’t write everything (but it can write other Parcelables in case you need it).

Using it is the same thing as in the first example

ExampleParcelable test = new ExampleParcelable(); // just an example, set fields you need

Intent intent = new Intent(currentActivity, newActivity.class);
intent.putExtra("myParameter", test);
startActivity(intent);

Also, in case you are super-lazy to implement your own Parcelables, I’ve found this awesome project (source code: https://github.com/dallasgutauckis/parcelabler).
It creates them for you :)

Advertisements

3 comments

  1. Hi,

    I am a newbie for Android and i have just started learning Android and i came across you tutorials. We have a website where we used to combine lot useful tutorials related to Java. Just want to know if you are interested in sharing your knowledge with us?

    Please reply to mail given.

    Thanks

  2. Pingback: FrAndroid DevSharing #10 - FrAndroid - Android

  3. Pingback: FrAndroid DevSharing #10 : Freamware


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s