I have a class called Service, which is used to create Service objects using this constructor
public Service(int id, String service_name, String service_code) {
this.id = id;
this.service_name = service_name;
this.service_code = service_code;
}
then I create a list call service list as with the following signature
List<Service> serviceList = new ArrayList<Service>
I have try to pass this ArrayList through Intent
Object like this
Intent i = new Intent(Classname.this, anotherClass.class);
i.putExtras("serviceList",serviceList);
startActivity(i);
But it fails. What is the way I pass through intent with ArrayList object.
Your custom class has to implement Parcelable
or Serializable
in order to serialize/de-serialize within an Intent.
Your class Service
has to look like this for example (used a generator http://www.parcelabler.com/)
public class Service implements Parcelable {
private int id;
private String service_name;
private String service_code;
public Service(int id, String service_name, String service_code) {
this.id = id;
this.service_name = service_name;
this.service_code = service_code;
}
protected Service(Parcel in) {
id = in.readInt();
service_name = in.readString();
service_code = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(service_name);
dest.writeString(service_code);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<Service> CREATOR = new Parcelable.Creator<Service>() {
@Override
public Service createFromParcel(Parcel in) {
return new Service(in);
}
@Override
public Service[] newArray(int size) {
return new Service[size];
}
};
}
Then you can use getIntent().getParcelableArrayListExtra()
with casting
ArrayList<Service> serviceList= intent.<Service>getParcelableArrayList("list"));
For sending you use it like this
intent.putParcelableArrayListExtra("list", yourServiceArrayList);
Note that the yourServiceArrayList
should be an ArrayList
if it is List the you can pass through
intent.putParcelableArrayListExtra("list", (ArrayList<? extends Parcelable>) yourServiceArrayList);
You can use parcelable interface for 'Service' class, and send object through
intent using 'putParcelableArrayListExtra' method and to retrive data you can use
'getParcelableArrayListExtra'.
For your reference
refer this link
Implement object class with Serializable .
eg.
class abc implements Serializable{
//your code
}
then try this code
ArrayList<abc> fileList = new ArrayList<abc>();
Intent intent = new Intent(MainActivity.this, secondActivity.class);
intent.putSerializable("arraylisty",filelist);
startActivity(intent);
and on other side receive intent like
your arraylist objact=intent.getSerializableExtra(String name)