Pass list of objects from one activity to other activity in android

后端 未结 7 1764
轻奢々
轻奢々 2020-12-01 01:35

I want to pass a list of objects from one activity from another activity. I have one class SharedBooking Below:

public class SharedBooking {         


        
7条回答
  •  囚心锁ツ
    2020-12-01 01:56

    Parcelable object class

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

提交回复
热议问题