Android passing ArrayList<Model> to Fragment from Activity

If you want to pass an ArrayList to your fragment, then you need to make sure the Model class is implements Parcelable. Here i can show an example.

public class ObjectName implements Parcelable {


    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);
    }
}

then you can add ArrayList<ObjectName> to a Bundle object.

ArrayList<ObjectName> arraylist = new Arraylist<ObjectName>();  
Bundle bundle = new Bundle();  
bundle.putParcelableArrayList("arraylist", arraylist);
fragment.setArguments(bundle);

After this you can get back this data by using,

Bundle extras = getIntent().getExtras();  
ArrayList<ObjectName> arraylist  = extras.getParcelableArrayList("arraylist");

At last you can show list with these data in fragment. Hope this will help to get your expected answer.


I was also stuck with the same problem . You can try this. Intead of sending the arraylist as bundle to fragment.Make the arraylist to be passed,as public and static in the activity.

public static Arraylist<Division> arraylist;

Then after parsing and adding the data in the arraylist make the call to the fragment.In the fragment you can the use the arraylist as:

ArrayList<Division> list=MainActivity.arraylist;