Passing custom objects between android activities

Read Time < 1 minute
Passing primitive datatypes between activities is straight froward, you can use intent.putExtra() and put anything like boolean,strings and integers etc. However you can’t pass custom objects  between activities in this way.
To pass custom objects between activities/services, we  must implement  parcelable or serializable interface to custom class. However parcelable is specifically designed for android and is advised for best performance.
Lets start with simple class:

public class User {
String UserName;
String  Password;
int Action;

public User(String name,String pass,int ac){
UserName=name;
Password=pass;
Action=ac;
}

}

above is a simple User class with three private fields and getters and setters.
We can’t pass objects of this class between activities/services. To do this we need to make this class parcelable. Lets see:

public class User implements Parcelable{

String UserName;
String  Password;
int Action;


public User(String name,String pass,int ac){
UserName=name;
Password=pass;
Action=ac;
}


//parcel part
public User(Parcel in){
String[] data= new String[3];

in.readStringArray(data);
this.UserName= data[0];
this.Password= data[1];
this.Action= Integer.parseInt(data[2]);
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub

dest.writeStringArray(new String[]{this.UserName,this.Password,String.valueOf(this.Action)});
}

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

@Override
public User createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new User(source);  //using parcelable constructor
}

@Override
public User[] newArray(int size) {
// TODO Auto-generated method stub
return new User[size];
}
};

}

Note that order of variable writing and reading is important, you should read and write variable in same order. One thing more pay attention to CREATOR its capital( It wasted my entire day 🙁 ).
Now you can send and receive User objects by putting as parcelableExtra. For example in sender activity

User obj= new User("sohail","1234",1);

Intent i=new Intent(this,receiverActivity.class);

i.putExtra("userTag",obj);

startActivity(i);

and on receiverActivity, probably in onCreate receive object by getparcelableExtra.

User uobj= getIntent().getParcelableExtra("userTag"); 

Browse and download source parcelableIntentServiceExample.

7 thoughts on “Passing custom objects between android activities”

Leave a Comment

Your email address will not be published. Required fields are marked *