Passing an ArrayList of Objects to the 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.

Leave a Comment