Android passing ArrayList to Fragment from Activity

前端 未结 2 1461
抹茶落季
抹茶落季 2020-12-17 01:11

Hi I want to send the data ArrayList to Fragment class ListContentFragment.

In MainActivity I am making a netw

相关标签:
2条回答
  • 2020-12-17 01:39

    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;
    
    0 讨论(0)
  • 2020-12-17 01:44

    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.

    0 讨论(0)
提交回复
热议问题