Thursday, June 17, 2010

Parcelable - How to do that in Android

Passing data between activities is quite easy. You would normally do that using the Bundle packed into an intent. But sometimes you need to pass complex objects from one activity to another. One workaround would be to keep a static instance of the object int your Activity and access it from you new Activity. This might help, but it's definitely not a good way to do this. To pass such objects directly through the Bundle, your class would need to implement the Parcelable interface.

For example you have a class called Student, which has three fields.
1. id
2. name
3. grade

You can create a POJO class for this, but you need to add some extra code to make it Parcelable. Have a look at the implementation.

   1: public class Student implements Parcelable{
   2:     private String id;
   3:     private String name;
   4:     private String grade;
   5:  
   6:     // Constructor
   7:     public Student(String id, String name, String grade){
   8:         this.id = id;
   9:         this.name = name;
  10:         this.grade = grade;
  11:     }
  12:     // Getter and setter methods
  13:     .........
  14:     .........
  15:     
  16:     // Parcelling part
  17:     public Student(Parcel in){
  18:         String[] data = new String[3];
  19:  
  20:         in.readStringArray(data);
  21:         this.id = data[0];
  22:         this.name = data[1];
  23:         this.grade = data[2];
  24:     }
  25:  
  26:     @override
  27:     public int describeContents(){
  28:         return 0;
  29:     }
  30:  
  31:     @Override
  32:     public void writeToParcel(Parcel dest, int flags) {
  33:         dest.writeStringArray(new String[] {this.id,
  34:                                             this.name,
  35:                                             this.grade});
  36:     }
  37:     public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
  38:         public Student createFromParcel(Parcel in) {
  39:             return new Student(in); 
  40:         }
  41:  
  42:         public Student[] newArray(int size) {
  43:             return new Student[size];
  44:         }
  45:     };
  46: }


Once you have created this class, you can easily pass objects of this class through the Intent like this, and recover this object in the target activity.

   1: intent.putExtra("student", new Student("1","Mike","6"));

Here, the student is the key which you would require to unparcel the data from the bundle.

   1: Bundle data = getIntent().getExtras();
   2: Student student = data.getParcelable("student");

This example shows only String types. But, you can parcel any kind of data you want. Try it out.