我有一个Prescription
s 类,其中包含Medication
、Doctor
和Pharmacy
. 这些类中的每一个都实现Parcelable
了,以便它们可以在Bundle
.
对于药物,医生和药房,我没有任何麻烦。然而,对于 Pharmacy 来说,事情变得有点棘手,因为它的字段是对象,这些对象也实现了 parcelable。为了编写对象,我使用了从这个问题中获得的以下代码:
/**
* Bundles all the fields of a pharmacy object to be passed in a `Bundle`.
* @param dest The parcel that will hold the information.
* @param flags Any necessary flags for the parcel.
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(getMedication(), 0);
dest.writeParcelable(getDoctor(), 0);
dest.writeParcelable(getPharmacy(), 0);
dest.writeInt(getQuantity());
dest.writeSerializable(getStartDate());
dest.writeString(getNotes());
dest.writeString(getInstructions());
}
而Creator
用于阅读处方的写法是这样的:
public static final Creator<Prescription> CREATOR = new Creator<Prescription>() {
@Override
public Prescription createFromParcel(Parcel source) {
return new Prescription(
source.readLong(), // Id
(Medication) source.readParcelable(Medication.class.getClassLoader()), // Medication
(Doctor) source.readParcelable(Doctor.class.getClassLoader()), // Doctor
(Pharmacy) source.readParcelable(Pharmacy.class.getClassLoader()), // Pharmacy
source.readInt(), // Quantity
(Date) source.readSerializable(), // Start Date
source.readString(), // Notes
source.readString() // Instructions
);
}
@Override
public Prescription[] newArray(int size) {
return new Prescription[size];
}
};
当我尝试从 Bundle 中读取 Prescription 对象时,它会返回一个 Prescription 对象,其中 Med/Doctor/Pharm 的值为空,并且非常模糊的 Id 和 Quantity 值。我不知道为什么。什么会导致这些值为空?
这是实现:
// Inside the NewPrescriptionActivity
Intent data = new Intent();
data.putExtra(PrescriptionBinderActivity.ARG_PRESCRIPTION, prescription);
setResult(RESULT_OK, data);
// Inside the Activity that calls it.
if(requestCode == ADD_SCRIPT_REQUEST && resultCode == RESULT_OK){
Prescription p = data.getParcelableExtra(ARG_PRESCRIPTION);
mAdapter.addPrescription(p);
}else{
super.onActivityResult(requestCode, resultCode, data);
}
同样,我在其他类上使用了相同的方法,没有任何问题,但这不适用于Prescription
. 我怀疑是因为它有 Parcelable 字段。