Help passing an ArrayList of Objects to a new Activity
Your object class should implement parcelable. The code below should get you started.
public class ObjectName implements Parcelable {
// Your existing code
public ObjectName(Parcel in) {
super();
readFromParcel(in);
}
public static final Parcelable.Creator<ObjectName> CREATOR = new Parcelable.Creator<ObjectName>() {
public ObjectName createFromParcel(Parcel in) {
return new ObjectName(in);
}
public ObjectName[] newArray(int size) {
return new ObjectName[size];
}
};
public void readFromParcel(Parcel in) {
Value1 = in.readInt();
Value2 = in.readInt();
Value3 = in.readInt();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(Value1);
dest.writeInt(Value2);
dest.writeInt(Value3);
}
}
To use the above do this:
In 'sending' activity use:
ArrayList<ObjectName> arraylist = new Arraylist<ObjectName>();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", arraylist);
In 'receiving' activity use:
Bundle extras = getIntent().getExtras();
ArrayList<ObjectName> arraylist = extras.getParcelableArrayList("arraylist");
ObjectName object1 = arrayList[0];
and so on.
Very Easy way, try the following:
bundle.putSerializable("lstContact", (Serializable) lstObject);
lstObj = (List<Contacts>) bundle.getSerializable("lstContact");
and also you will need to implement your Contact class from Serializable interface. ex :
public class Contact implements Serializable{
...
...
...
}
You have two options:
Objects in the ArrayList put implement
Parceable
as required by the methodputParcelableArrayList ()
Or the objects can implement
Serializable
and use the methodputSerializable()
to add the ArrayList, iebundle.putSerializable("arraylist", arraylist);
Android passes Object in Bundle by serializing and deserializing (via Serializable or Parcelable). So all of your Objects you want to pass in a Bundle must implement one of those two interfaces.
Most Object serialize easily with Serializable
and it is much simpler to implement Serializable
and add a static UID to the class than to write all the methods/classes required for Parcelable
.