将整数数组读写到包中

29

在使用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个回答

60

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

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

我使用了以下代码代替"readIntArray":

storeID = in.createIntArray();

现在没有错误。


谢谢。我会尝试这个,然后再告诉你。 - Atul Bhardwaj
3
谢谢。我的readFloatArray(...)和createFloatArray()遇到了同样的问题,现在已经解决了。 - PeterVanPansen
6年过去了,仍然适用。我真的无法理解为什么readIntArray()会抛出NullPointerException异常。 - wFateem

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

使用上述答案会在三星设备上导致崩溃。 - HannahCarney

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接