Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transferring ByteArray through Parcel returns NullPointerException

Tags:

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];
        }
    };

}

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.

like image 333
Debopam Mitra Avatar asked Jul 29 '12 11:07

Debopam Mitra


1 Answers

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

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 moved from comment

In write...

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

and in read...

_byte = new byte[in.readInt()]; 
in.readByteArray(_byte);
like image 155
nEx.Software Avatar answered Sep 27 '22 20:09

nEx.Software