通过Parcel传输ByteArray返回NullPointerException

22
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异常。有人能说一下问题是什么吗?我的目的是将从一个活动下载的图像字节传输到另一个活动中。
2个回答

70
你在读取包裹时从未初始化_byte数组,因此它为空。
我建议的是,在写入包裹时,将字节数组的长度和实际字节数组一起存储。在读取包裹时,首先读取长度并将_byte数组初始化为该大小的新数组,然后读入字节数组。

从评论移动的代码

在写入中...

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

在读取和写入文件时,处理文本数据是 IT 技术中的一个重要方面。
_byte = new byte[in.readInt()]; 
in.readByteArray(_byte);

你是不是指像这样的东西: public void readFromParcel(Parcel in) { _byte = new byte[length_of_byte]; in.readByteArray(_byte); } - Debopam Mitra
2
在写入时... dest.writeInt(_byte.length); dest.writeByteArray(_byte); ,在读取时... _byte = new byte[in.readInt()]; in.readByteArray(_byte); - nEx.Software
1
writeByteArray的实现已经在其前面存储了byteArray的长度,因此您不需要再次写入它。相反,读取int以初始化字节数组,然后使用“dest.setDataPosition(dest.dataPosition()-4);”将指针移回。 - Piaf

19

不使用存储字节数组长度的更短解决方案:

dest.writeByteArray(byteArray);
byteArray = in.createByteArray();

4
这确实应该是答案,它可行并且很简单,你只需用另一行代码替换一行即可。我在 Android Studio 中看到它时想使用它,但我不禁想这看起来非常奇怪,这是典型的 Java 编码吗?如果有多个 byte[],Parceling 过程会如何确定哪一个是哪一个?我猜我不理解 Parceling 过程...我以为我理解了.... - JamisonMan111

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