2015-03-16 3 views
0

У меня есть класс для Prescription s с полями для Medication, Doctor и Pharmacy. Каждый из этих классов реализует Parcelable, чтобы они могли быть переданы внутри Bundle.Невозможно прочитать приемлемый объект в другом интересном объекте

Для лечения, доктора и фармации у меня нет никаких проблем. Однако для Аптеки все становится немного сложнее, поскольку у него есть поля, которые также являются объектами, которые также реализуются. Для того, чтобы написать объект, я использовал следующий код, который я получил от этого 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]; 
    } 
}; 

Когда я пытаюсь прочитайте объект Prescription из Bundle, он возвращает объект 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. Я подозреваю, потому что у него есть поля с посылкой.

ответ

1

Вы не добавляете поле id в парцеллу.

Измените первую строку метода writeToParcel() и добавить:

dest.writeLong(getId()); 

Из-за этого, все чтение неправильно.

+0

Ничего себе, я смотрел это снова и снова, и я никогда бы не поймал этого. Отличная добыча! – AdamMc331

Смежные вопросы