How to pass an object from one activity to another on Android

后端 未结 30 4055
遇见更好的自我
遇见更好的自我 2020-11-21 04:03

I am trying to work on sending an object of my customer class from one Activity and display it in another Activity.

The code for t

30条回答
  •  时光说笑
    2020-11-21 04:46

    While calling an activity

    Intent intent = new Intent(fromClass.this,toClass.class).putExtra("myCustomerObj",customerObj);
    

    In toClass.java receive the activity by

    Customer customerObjInToClass = getIntent().getExtras().getParcelable("myCustomerObj");
    

    Please make sure that customer class implements parcelable

    public class Customer implements Parcelable {
    
        private String firstName, lastName, address;
        int age;
    
        /* all your getter and setter methods */
    
        public Customer(Parcel in ) {
            readFromParcel( in );
        }
    
        public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
            public LeadData createFromParcel(Parcel in ) {
                return new Customer( in );
            }
    
            public Customer[] newArray(int size) {
                return new Customer[size];
            }
        };
    
    
        @Override
        public void writeToParcel(Parcel dest, int flags) {
    
            dest.writeString(firstName);
            dest.writeString(lastName);
            dest.writeString(address);
            dest.writeInt(age);
        }
    
        private void readFromParcel(Parcel in ) {
    
            firstName = in .readString();
            lastName  = in .readString();
            address   = in .readString();
            age       = in .readInt();
        }
    

提交回复
热议问题