【问题标题】:How to make LocalDate and LocalTime parcelable?如何使 LocalDate 和 LocalTime 可打包?
【发布时间】:2019-08-18 15:23:51
【问题描述】:

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

我有 Parcelable 复杂类 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() 方法以将对象传递给相应的活动时会崩溃。

请帮忙

【问题讨论】:

  • “性能非常重要,所以我也不考虑将 Serializable 作为一个选项” 您是否真正衡量过它是否对您的代码有重大影响?写/读为可序列化将是这里的简单方法。
  • 老实说,我没有尝试过 Serializable 并且它有效。谢谢!不过,如果可能的话,我想在将来将其更改为 parcelable。
  • 您只需要在 Parcel 中使用这些字段进行 Serializable,而不是到处都是

标签: android parcelable localdate threetenabp


【解决方案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);
}

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

一种更高效的方法是将您的日期对象转换为long,并在写入包裹时将它们转换回相关的日期对象,然后再从包裹中读取。

【讨论】:

  • 链接方法不适用于 LocalDate/LocalTime 对象您知道使用这些较新的日期/时间类型执行可打包方法的方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 2023-03-03
  • 2020-10-05
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多