从Bundle接收到空的Parcelable对象

3

我希望能向一个活动发送一个Parcelable对象的列表,但是当从活动捆绑中接收这些对象时,我得到了空对象。

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

    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;
}
}

当调用名为“activity”的活动时,我得到了:

@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());
    }       

}

问题在于当我分析报告数组时,我发现尽管大小为2,但第二个项目为空(项目位置= 1)。请注意,列表的第一个项目完美地出现了。怎么回事?

1个回答

6

我今天刚遇到了同样的问题,我通过以下方式解决:

写入数据:

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

读取数据:

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

希望这可以帮到您:)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接