2017-08-24 66 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); 
    } 

我希望这可以帮助别人。

相关问题