Parcelable class 异常作为属性 (Android)

Parcelable class with exception as attribute (Android)

我想使用 class 中的 Parcelable 将对象从 activity 发送到另一个对象。我有一个 Parcelable class,它有两个字符串和一个异常作为属性。

public class ReportErrorVO implements Parcelable {

    private String titleError;
    private String descriptionError;
    private Exception exceptionError;

    public ReporteErrorVO(Parcel in) {
        titleError = in.readString();
        descriptionError = in.readString();
        exceptionError = ????; //What do I put here?
    }

    public ReporteErrorVO() {
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {    
        dest.writeString(titleError);
        dest.writeString(descriptionError);
        dest.writeException(exceptionError);
    }

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

    //Getter and setters atributes...
}

如何在 parcelable 属性中设置异常?

您可以使用 readException 方法 in.readException() 如果异常已写入包裹,此方法将抛出异常,因此您可以捕获它并保存到您的变量中。

    try {
        in.readException();
    } catch (Exception e){
        exceptionError = e;
    }

请注意,此方法仅支持有限类型的异常

The supported exception types are:
     * BadParcelableException
     * IllegalArgumentException
     * IllegalStateException
     * NullPointerException
     * SecurityException
     * NetworkOnMainThreadException

好的,这样做有助于我使事情正常进行:在数组上发送异常。

@Override
    public void writeToParcel(Parcel dest, int flags) {    
        dest.writeString(mTitleError);
        dest.writeString(mDescriptionError);
        Exception[] exceptions = new Exception[1];
        exceptions[0] = mExceptionError;
        dest.writeArray(exceptions);
    }

public ReportErrorVO(Parcel in) {
        mTitleError = in.readString();
        mDescriptionError = in.readString();
        Object[] exceptions = in.readArray(Exception.class.getClassLoader());
        mExceptionError = (Exception) exceptions[0];
    }