Transferring ByteArray through Parcel returns NullPointerException

后端 未结 2 1602
一向
一向 2020-12-30 01:10
import android.os.Parcel;
import android.os.Parcelable;

public class MClass implements Parcelable {
    private byte[] _byte;

    public MClass() {
    }

    publ         


        
相关标签:
2条回答
  • 2020-12-30 02:01

    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);
    
    0 讨论(0)
  • 2020-12-30 02:11

    A shorter solution without storing the byte arrays length:

    dest.writeByteArray(byteArray);
    byteArray = in.createByteArray();
    
    0 讨论(0)
提交回复
热议问题