gpt4 book ai didi

android - 如何使 LocalDate 和 LocalTime 可打包?

转载 作者:行者123 更新时间:2023-12-05 00:20:50 27 4
gpt4 key购买 nike

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

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

我不想改变逻辑来处理不同的类,甚至是原语;因为这些类在整个应用程序中被广泛使用。当然,这些属性不会自动放入 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() 就像其他属性一样,但它说参数类型错误:

Wrong 1st argument type. Found: 'org.threeten.bp.LocalDate', required: 'android.os.Parcelable'

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

求助

最佳答案

@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,同时写入包裹并在从包裹读取时将它们转换回相关的日期对象。

关于android - 如何使 LocalDate 和 LocalTime 可打包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57545933/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com