Tranfering的ByteArray通过包裹返回NullPointerException异常包裹、异常、Tranfering、ByteArray

2023-09-05 11:11:51 作者:葬心葬爱葬灵魂

import android.os.Parcel;
import android.os.Parcelable;

public class MClass implements Parcelable {
    private byte[] _byte;

    public MClass() {
    }

    public MClass(Parcel in) {
        readFromParcel(in);
    }


    public byte[] get_byte() {
        return _byte;
    }

    public void set_byte(byte[] _byte) {
        this._byte = _byte;
    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeByteArray(_byte);
    }

    public void readFromParcel(Parcel in) {
        in.readByteArray(_byte); //LOE - Line Of Exception
    }

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

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

}

每当我要找回我在下面的数组它返回异常NullPointerException异常的字节。任何一个可以说的是什么问题?我所试图做的是从一个活动下载的映像个字节传送到另一台。

Whenever I am going to retrieve the bytes in my following array it is returning exception of NullPointerException. Can any one say what is the problem? What I am trying to do is to transfer a downloaded image bytes from one activity to another.

推荐答案

在阅读的包裹你永远不会初始化_byte阵列,因此它是空。

You never initialize the _byte array upon reading the parcel, therefore it is null.

我会做的是,当你写你的包裹,存储字节数组后跟实际字节数组的长度。当你读了包裹,先读长度和初始化_byte数组的大小的新数组,然后字节数组中读取。

What I'd do is, when you write your parcel, store the length of the byte array followed by the actual byte array. When you read the parcel, first read the length and initialize your _byte array to a new array of that size, then read in the byte array.

code从评论移动

在写... 的

In write...

dest.writeInt(_byte.length); 
dest.writeByteArray(_byte); 

,并在读... 的

and in read...

_byte = new byte[in.readInt()]; 
in.readByteArray(_byte);