【问题标题】:How to use a class field array in a Android Parcelable如何在 Android Parcelable 中使用类字段数组
【发布时间】:2013-02-13 22:01:06
【问题描述】:

我基于 snippet 创建了自己的 Parcelable 类,以通过 Intent 发送自定义数据。使用它,Android(最低 API 10)给了我一个例外,下面的那段代码有什么问题?我把它分解到最低限度。这里是:

public class MyParcelable implements Parcelable {
private float[] data = null;

public MyParcelable(float[] data) {
    this.data = data;
}

public MyParcelable(Parcel in) {
    /* After this line the exception is thrown */
    in.readFloatArray(data);
}

public static final Creator<MyParcelable> CREATOR = new Creator<MyParcelable>() {
    public MyParcelable createFromParcel(Parcel in) {
        return new MyParcelable(in);
    }

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

public int describeContents() {
    return this.hashCode();
}

public void writeToParcel(Parcel out, int flags) {
    out.writeFloatArray(data);
}

public float[] getData() {
    return data;
}
}

【问题讨论】:

  • describeContents() 返回位掩码,而不是 hashCode!

标签: android exception nullpointerexception parcelable


【解决方案1】:

在寻找解决方案很长一段时间后,我偶然发现了这个 post,LionKing 给出了一个有效的提示。

Parcelable 类现在看起来像这样:

public class MyParcelable implements Parcelable {
private float[] data = null;

public MyParcelable(float[] data) {
    this.data = data;
}

public MyParcelable(Parcel in) {
    /* The exception is gone */
    data = in.createFloatArray();
}

public static final Creator<MyParcelable> CREATOR = new Creator<MyParcelable>() {
    public MyParcelable createFromParcel(Parcel in) {
        return new MyParcelable(in);
    }

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

public int describeContents() {
    return this.hashCode();
}

public void writeToParcel(Parcel out, int flags) {
    out.writeFloatArray(data);
}

public float[] getData() {
    return data;
}
}

此解决方案也适用于其他基本类型数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 2011-10-10
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    相关资源
    最近更新 更多