Reading and writing integer array to parcel

Atul Bhardwaj picture Atul Bhardwaj · Aug 25, 2012 · Viewed 16.5k times · Source

I could not find any solution for how to treat with integer array in case of parcel (I want to use these two functions dest.writeIntArray(storeId); and in.readIntArray(storeId);).

Here is my code

public class ResponseWholeAppData implements Parcelable {
    private int storeId[];

    public int[] getStoreId() {
        return storeId;
    }

    public void setStoreId(int[] storeId) {
        this.storeId = storeId;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public ResponseWholeAppData(){
        storeId = new int[2];
        storeId[0] = 5;
        storeId[1] = 10;
    }

    public ResponseWholeAppData(Parcel in) {

        if(in.readByte() == (byte)1) 
             in.readIntArray(storeId);  //how to do this storeId=in.readIntArray();  ?                          
        }

    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        if(storeId!=null&&storeId.length>0)                   
        {
            dest.writeByte((byte)1);
            dest.writeIntArray(storeId);
        }
        else
            dest.writeByte((byte)0);

    }
    public static Parcelable.Creator<ResponseWholeAppData> getCreator() {
        return CREATOR;
    }

    public static void setCreator(Parcelable.Creator<ResponseWholeAppData> creator) {
        CREATOR = creator;
    }

    public static Parcelable.Creator<ResponseWholeAppData> CREATOR = new Parcelable.Creator<ResponseWholeAppData>()
            {
        public ResponseWholeAppData createFromParcel(Parcel in)
        {
            return new ResponseWholeAppData(in);
        }
        public ResponseWholeAppData[] newArray(int size)
        {
            return new ResponseWholeAppData[size];
        }
            };      
}

Answer

LionKing picture LionKing · Nov 22, 2012

When I use "in.readIntArray(storeID)", I get an error:

"Caused by: java.lang.NullPointerException at android.os.Parcel.readIntArray(Parcel.java:672)".

Instead of using "readIntArray" I used the following:

storeID = in.createIntArray();

Now there are no errors.