无法读取另一个parcelable对象中的parcelable对象

时间:2015-03-16 03:30:50

标签: java android parcelable android-bundle

我有一个Prescription的课程,其中包含MedicationDoctorPharmacy的字段。这些类中的每一个都实现Parcelable,以便它们可以在Bundle内传递。

对于药物,医生和药房,我没有遇到任何麻烦。然而,Pharmacy的事情变得有点棘手,因为它的字段也是可以实现parcelable的对象。为了编写对象,我使用了以下从question获得的代码:

/**
 * 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字段。

1 个答案:

答案 0 :(得分:1)

您没有将id字段添加到Parcel。

修改writeToParcel()方法的第一行并添加:

dest.writeLong(getId());

因此,整个阅读都是错误的。