我有一个如下类的EmployeeInfo:

 public class EmployeeInfo {
        private int id; // Employee ID
        private String name; // Employee Name
        private int age;// Employee Age

        public int getEmployeeID() {
            return id;
        }

        public void setEmployeeID(int id) {
            this.id = id;
        }

        public String getEmployeeName() {
            return name;
        }

        public void setEmployeeName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age= age;
        }
    }


ArrayList<EmployeeInfo> employeeInfo object contains the emplyoyee info data for multiple employees.


我想将数据(ArrayList employeeInfo)从Activity1传输到Activity2。

使用Parcelable是将数据从Activity1传输到Activity2的唯一方法吗?
如果没有,有什么替代方案。

如果是,请提供Parcelable的原型代码以及有关如何将对象数据从Activity1传输到Activity2的示例代码。

最佳答案

这是我的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<ProfileData> CREATOR
      = new Parcelable.Creator<ProfileData>() {

public ProfileData createFromParcel(Parcel in) {
    return new ProfileData(in);
}

public ProfileData[] newArray(int size) {
    return new ProfileData[size];
}


};

}

以及我如何传输数据:

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


并获取数据:

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

10-05 18:05
查看更多