Transferring ByteArray through Parcel returns NullPointerException

17,126

Solution 1

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

Solution 2

A shorter solution without storing the byte arrays length:

dest.writeByteArray(byteArray);
byteArray = in.createByteArray();
Share:
17,126
Debopam Mitra
Author by

Debopam Mitra

5.5 years of experience in enterprise web application development.

Updated on June 15, 2022

Comments

  • Debopam Mitra
    Debopam Mitra about 2 years
    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.