从 Bundle 接收空 Parcelable 对象

IIR*_*hII 3 java android parcelable

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

我有一个方法可以启动一个活动,在包中发送一个 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);
    }
Run Code Online (Sandbox Code Playgroud)

我的 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;
}
}
Run Code Online (Sandbox Code Playgroud)

以及被称为的活动,我得到了:

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

}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*nés 6

我今天刚遇到同样的问题,我是通过这种方式解决的:

写入数据:

 Bundle data = new Bundle();
 data.putParcelableArrayList("reports", reports);
 intent.putExtra("bundle", data);
Run Code Online (Sandbox Code Playgroud)

读取数据:

Bundle data = intent.getBundleExtra("bundle");
ArrayList<ReportErrorVO> reports= data.getParcelableArrayList("reports");
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你 :)