0

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?

atish shimpi
  • 4,873
  • 2
  • 32
  • 50
Pitty
  • 329
  • 4
  • 15

1 Answers1

2

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;
}
Konrad Krakowiak
  • 12,285
  • 11
  • 58
  • 45