2017-08-24 62 views
1

我有一個Parcelable對象,它有一個Parcelable對象列表。我想讀回來後,它已經從一個活動傳遞到下一個該列表,但只有第一個元素是「非捆綁」只有列表纔可以列表反序列化第一個元素

public class MyBundle implements Parcelable { 
    private List<Data> dataList; 

    public static final Parcelable.Creator<MyBundle> CREATOR = new Parcelable.Creator<MyBundle>() { 
     public MyBundle createFromParcel(Parcel in) { 
      return new MyBundle(in); 
     } 

     public MyBundle[] newArray(int size) { 
      return new MyBundle[size]; 
     } 
    }; 

    public MyBundle() { 
    } 

    public MyBundle(Parcel in) { 
     //dataList = new ArrayList<>(); 
     //in.readTypedList(dataList, Data.CREATOR); 
     dataList = in.createTypedArrayList(Data.CREATOR); 
     //BOTH have the same result 
    } 

    @Override 
    public int describeContents() { 
     return 0; 
    } 

    @Override 
    public void writeToParcel(Parcel dest, int flags) { 
     if (dataList != null && dataList.size() > 0) { 
      dest.writeTypedList(dataList); 
     } 
    } 
} 

數據對象:

/*BaseObject has the following properties: 
    UUID uuid; 
    long databaseId; 
    createdDate; 
    modifiedDate; 
*/ 
public class Data extends BaseObject implements Parcelable { 
    private String name; 
    private String serial; 
    private String location; 

    public Data() {} 

    private Data(Parcel in) { 
     String uuidString = in.readString(); 
     if (uuidString == null) return; //this is null! 
     uuid = UUID.fromString(idString); 
     databaseId = in.readLong(); 
     createdDate = new Date(in.readLong()); 
     modifiedDate = new Date(in.readLong()); 
     location = in.readString(); 

     name = in.readString(); 
     serial = in.readString(); 
    } 

    @Override 
    public int describeContents() { 
     return 0; 
    } 

    @Override 
    public void writeToParcel(Parcel dest, int flags) { 
     dest.writeString(uuid.toString()); 
     dest.writeLong(databaseId); 
     dest.writeLong(createdDate.getTime()); 
     dest.writeLong(modifiedDate.getTime()); 

     dest.writeString(name); 
     dest.writeString(serial); 
    } 

    public static final Parcelable.Creator<Data> CREATOR 
      = new Parcelable.Creator<Data>() { 
     public Data createFromParcel(Parcel in) { 
      return new Data(in); 
     } 

     public Data[] newArray(int size) { 
      return new Data[size]; 
     } 
    }; 
} 

什麼我曾嘗試:

回答

0

所以這就是答案:我的數據parcelable錯過了位置元素時,它創建的包裹。發生READING時,這顯然會導致某種偏移錯誤。所以編碼方案如下:

@Override 
    public void writeToParcel(Parcel dest, int flags) { 
     dest.writeString(uuid.toString()); 
     dest.writeLong(databaseId); 
     dest.writeLong(createdDate.getTime()); 
     dest.writeLong(modifiedDate.getTime()); 
     dest.writeString(location); /*HERE!*/ 
     dest.writeString(name); 
     dest.writeString(serial); 
    } 

我希望這可以幫助別人。

相關問題