Tranfering的ByteArray通过包裹返回NullPointerException异常 [英] Tranfering ByteArray through Parcel returns NullPointerException

查看:152
本文介绍了Tranfering的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阵列,因此它是空。

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

这篇关于Tranfering的ByteArray通过包裹返回NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆