如何使 LocalDate 和 LocalTime 可包裹?

How to make LocalDate and LocalTime parcelable?

提问人:Marianne Rojas 提问时间:8/18/2019 更新时间:3/30/2020 访问量:1823

问:

我是 android 的新手,并使用 ThreeTenABP(因此它与更多设备兼容)LocalDate 和 LocalTime 预约管理 android 应用程序,我需要使它们可包裹。

我有可分包的复杂类 Appointment,它有 LocalDate 和 LocalTime 的实例作为属性;我认为默认情况下不是可打包的类。

我不想改变逻辑来处理不同的类,甚至基元;因为这些类在整个应用程序中被广泛使用。 当然,这些属性不会自动放入 Appointment(Parcel in) 方法中,我不知道如何包含它们,或者是否可能。

性能非常重要,所以我也不考虑将 Serializable 作为一个选项。

这是 Appointment 类(此外,我确保使所有其他自定义对象都可打包):

public class Appointment implements Parcelable{

    private Patient patient;
    private LocalDate date;
    private LocalTime time;
    private Doctor doctor;
    private Prescription prescription;

    public Appointment(Patient patient, LocalDate date, LocalTime time, Doctor doctor, Prescription prescription) {

        this.patient = patient
        this.date = date;
        this.time = time;
        this.doctor = doctor;
        this.prescription = prescription;
    }

    protected Appointment(Parcel in) {
        patient = in.readParcelable(Patient.class.getClassLoader());
        doctor = in.readParcelable(Doctor.class.getClassLoader());
        prescription = in.readParcelable(Prescription.class.getClassLoader());
    }

    public static final Creator<Appointment> CREATOR = new Creator<Appointment>() {

        @Override
        public Appointment createFromParcel(Parcel in) {
            return new Appointment(in);
        }

        @Override
        public Appointment[] newArray(int size) {
            return new Appointment[size];
        }
    };

    //Class methods

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeParcelable(patient, flags);
        dest.writeParcelable(doctor, flags);
        dest.writeParcelable(prescription, flags);
    }
}

我已经尝试像其他属性一样向 Appointment(Parcel in) 和 writeToParcel() 添加日期和时间,但它说参数是错误的类型:

错误的第一个参数类型。找到:“org.threeten.bp.LocalDate”,必填: 'android.os.Parcelable'

如果我保留它保留日期和时间,我不会收到任何错误消息,但是当应用程序到达 intent.putExtra() 方法将对象传递给相应的活动时,应用程序会崩溃。

请帮忙

Android 可包裹 localdate threetenabp

评论

1赞 laalto 8/18/2019
“性能非常重要,所以我也不考虑将 Serializable 作为一种选择” 你是否真正衡量了它对你的代码是否有重大影响?将 Serializable 写入/读取将是这里的简单方法。
0赞 Marianne Rojas 8/18/2019
老实说,我没有尝试过 Serializable,它有效。谢谢!不过,如果可能的话,我想在将来将其更改为可包裹。
0赞 laalto 8/19/2019
您只需要在 Parcel 中使用这些字段进行 Serializable,而不是到处都是

答:

4赞 Johnz 3/30/2020 #1
@Override
protected Appointment(Parcel in) {
    // Read objects
    date = (LocalDate) in.readSerializable();
    time = (LocalTime) in.readSerializable();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    // Write objects 
    dest.writeSerializable(date);
    dest.writeSerializable(time);
}

这篇文章很好地解释了性能细节。我不必在这里重复它们。

一种性能更高的方法是将日期对象转换为写入宗地时,并在从宗地读取时将其转换回相关的日期对象。long

评论

0赞 d0rf47 10/23/2020
链接方法不适用于 LocalDate/LocalTime 对象,您知道使用这些较新的日期/时间类型执行可包裹方法的方法吗?