读取和写入整数数组到parcel

时间:2012-08-25 11:28:05

标签: android parcelable

在parcel的情况下,我找不到任何有关如何处理整数数组的解决方案(我想使用这两个函数 dest.writeIntArray(storeId); in.readIntArray( STOREID);

这是我的代码

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

2 个答案:

答案 0 :(得分:58)

当我使用“in.readIntArray(storeID)”时,出现错误:

“引起:java.lang.NullPointerException     在android.os.Parcel.readIntArray(Parcel.java:672)“

我没有使用“readIntArray”,而是使用了以下内容:

storeID = in.createIntArray();

现在没有错误。

答案 1 :(得分:0)

我假设类MyObj实现了Parcelable并实现了所有必需的方法;我在这里只建议有关读/写包裹的详细信息。

如果预先知道数组大小:

public void writeToParcel(Parcel out, int flags) {
    super.writeToParcel(out, flags);
    out.writeIntArray(mMyIntArray);        // In this example array length is 4
}

protected MyObj(Parcel in) {
    super(in);
    mMyIntArray = new int[4];
    in.readIntArray(mMyIntArray);
}

否则:

public void writeToParcel(Parcel out, int flags) {
    super.writeToParcel(out, flags);
    out.writeInt(mMyArray.length);        // First write array length
    out.writeIntArray(mMyIntArray);       // Then array content
}

protected MyObj(Parcel in) {
    super(in);
    mMyIntArray = new int[in.readInt()];
    in.readIntArray(mMyIntArray);
}
相关问题