输ByteArray返回NullPointerException

输ByteArray返回NullPointerException

本文介绍了通过Parcel传输ByteArray返回NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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数组,因此它为null.

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.

代码已从注释中移出

写中...

In write...

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

和已读...

and in read...

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

这篇关于通过Parcel传输ByteArray返回NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 10:17