Passing a List from one Activity to another

后端 未结 5 2132
花落未央
花落未央 2020-12-01 13:09

How to pass Collections like ArrayList, etc from one Activity to another as we used to pass Strings, int with help of put

5条回答
  •  天涯浪人
    2020-12-01 13:42

    First you need to create a Parcelable object class, see the example

    public class Student implements Parcelable {
    
            int id;
            String name;
    
            public Student(int id, String name) {
                this.id = id;
                this.name = name;
    
            }
    
            public int getId() {
                return id;
            }
    
            public String getName() {
                return name;
            }
    
    
            @Override
            public int describeContents() {
                // TODO Auto-generated method stub
                return 0;
            }
    
            @Override
            public void writeToParcel(Parcel dest, int arg1) {
                // TODO Auto-generated method stub
                dest.writeInt(id);
                dest.writeString(name);
            }
    
            public Student(Parcel in) {
                id = in.readInt();
                name = in.readString();
            }
    
            public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
                public Student createFromParcel(Parcel in) {
                    return new Student(in);
                }
    
                public Student[] newArray(int size) {
                    return new Student[size];
                }
            };
        }
    

    And the list

    ArrayList arraylist = new ArrayList();
    

    Code from Calling activity

    Intent intent = new Intent(this, SecondActivity.class);
    Bundle bundle = new Bundle();
    bundle.putParcelableArrayList("mylist", arraylist);
    intent.putExtras(bundle);       
    this.startActivity(intent);
    

    Code on called activity

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);   
    
        Bundle bundle = getIntent().getExtras();
        ArrayList arraylist = bundle.getParcelableArrayList("mylist");
    }
    

提交回复
热议问题