writeSparseArray support SparseArray<int[]>?

和自甴很熟 提交于 2019-12-11 18:41:46

问题


I have a param in SparseArray<int[]> , and want to serialize it.

But the writeSparseArray(Object) for Parcelable seems not support int[]. Is there any other way to serialize the SparseArray<int[]>,Or only change int[] to Object?


回答1:


I checked Parcel.writeSparseArray() method and in my opinion there is some issue because this method should be generic like writeList(). It looks like:

public final void writeSparseArray(SparseArray<Object> val)

and should be

public final void writeSparseArray(SparseArray<? extends Object> val)

or

public final <T> void writeSparseArray(SparseArray<T> val)

or

public final void writeSparseArray(SparseArray val)

So you have to implement your own implementation of this method for SparseArray object. I am not sure that it is the best solution but you can try this:

public void writeSparseArray(Parcel dest, SparseArray<int[]> sparseArray) {
    if (sparseArray == null) {
        dest.writeInt(-1);
        return;
    }
    int size = sparseArray.size();
    dest.writeInt(size);
    int i=0;
    while (i < size) {
        dest.writeInt(sparseArray.keyAt(i));
        dest.writeIntArray(sparseArray.valueAt(i));
        i++;
    }
}

private SparseArray<int[]> readSparseArrayFromParcel(Parcel source){
    int size = source.readInt();
    if (size < 0) {
        return null;
    }
    SparseArray sa = new SparseArray(size);
    while (size > 0) {
        int key = source.readInt();
        int[] value = source.createIntArray();
        sa.put(key, value);
        size--;
    }
    return sa;
}


来源:https://stackoverflow.com/questions/27897331/writesparsearray-support-sparsearrayint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!