从Bundle接收null Parcelable对象

时间:2015-08-24 14:00:57

标签: java android parcelable

我想将一个Parcelable对象列表发送给一个活动,但是当从活动包中接收对象时我得到了空对象

我有一个启动活动的方法,在bundle中发送Parcelable对象列表:

    public void openActivity(){
        ArrayList<ReportErrorVO> reports = new ArrayList<>();

        ReporteErrorVO reportError = new ReporteErrorVO();
        reportError.setTituloError("Error title 1");
        reportError.setDescripcionError("Error description 1");
        reports.add(reportError);

        reportError = new ReporteErrorVO();
        reportError.setTituloError("Error title 2");
        reportError.setDescripcionError("Error description 2");
        reports.add(reportError);

        Intent intent = new Intent(this, ReporteErrorActivity.class);
        Bundle args = new Bundle();
        args.putParcelableArrayList("reports", reports);
        intent.putExtras(args);
        startActivity(intent);
    }

我的Parcelable课程:

public class ReportErrorVO implements Parcelable {

private String titleError;
private String descriptionError;

public ReportErrorVO(Parcel in) {
    titleError = in.readString();
    descriptionError = in.readString();
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeString(titleError);
    dest.writeString(descriptionError);
}

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

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

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

所谓的活动,我得到了:

@Override
    protected void onCreate(Bundle savedInstanceState) {

    ...//Activity initializer code..

    Bundle bundle = getIntent().getExtras();
    ArrayList<ReportErrorVO> reports = new ArrayList<>();
    try {
        reports = bundle.getParcelableArrayList("reports");
    }catch (Exception ex){
        System.out.println(ex.getMessage());
    }       

}

问题在于,当我分析报告数组时,我发现当我得到size = 2时,我得到了第二个项目null(项目位置= 1)。请注意,列表中的第一个词是完美的。怎么了?

1 个答案:

答案 0 :(得分:4)

我今天刚遇到同样的问题而且我已经通过这种方式解决了问题:

写数据:

 Bundle data = new Bundle();
 data.putParcelableArrayList("reports", reports);
 intent.putExtra("bundle", data);

阅读数据:

Bundle data = intent.getBundleExtra("bundle");
ArrayList<ReportErrorVO> reports= data.getParcelableArrayList("reports");

希望有所帮助:)