Transferring object data from one activity to another activity

前端 未结 5 1290
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 08:30

I am having a class EmployeeInfo as the following:

 public class EmployeeInfo {
        private int id; // Employee ID
        private String name; // Employ         


        
5条回答
  •  情深已故
    2021-01-07 08:37

    Here is my implementation of Parceleble:

    public class ProfileData implements Parcelable {
    
    private int gender;
    private String name;
    private String birthDate;
    
    public ProfileData(Parcel source) {
        gender = source.readInt();
        name = source.readString();
        birthDate = source.readString();
    }
    
    public ProfileData(int dataGender, String dataName, String dataBDate) {
        gender = dataGender;
        name = dataName;
        birthDate = dataBDate;
    }
    
    // Getters and Setters are here
    
    @Override
    public int describeContents() {
    return 0;
    }
    
    @Override
    public void writeToParcel(Parcel out, int flags) {
    out.writeInt(gender);
    out.writeString(name);
    out.writeString(birthDate);
    }
    
    public static final Parcelable.Creator CREATOR
          = new Parcelable.Creator() {
    
    public ProfileData createFromParcel(Parcel in) {
        return new ProfileData(in);
    }
    
    public ProfileData[] newArray(int size) {
        return new ProfileData[size];
    }
    

    };

    }

    and how I transfer data:

    Intent parcelIntent = new Intent().setClass(ActivityA.this, ActivityB.class);
    ProfileData data = new ProfileData(profile.gender, profile.getFullName(), profile.birthDate);
    parcelIntent.putExtra("profile_details", data);
    startActivity(parcelIntent);
    

    and take data:

        Bundle data = getIntent().getExtras();
        ProfileData profile = data.getParcelable("profile_details");
    

提交回复
热议问题