Search code examples
androidsparse-matrixparcelable

Write a SparseArray of Double to Parcel


I have a SparseArray of Double and I have to write it to the Parcel.

Here is my code :

@Override
public void writeToParcel(Parcel dest, int flags) {
    SparseArray<Double> spa = new SparseArray<>();
    spa.put(1, 0.8d);
    spa.put(5, 6.4d);
    spa.put(89, 0.8d);
    dest.writeSparseArray(spa);
}

This won't compile, with this error :

writeSparseArray (android.util.SparseArray<java.lang.Object>) in Parcel cannot be applied to (android.util.SparseArray<java.lang.Double>)

Android Studio javadoc for writeSparseArray() tells me that it use Parcel's writeValue(), and the doc at this method says that it should work :

The given Object value may currently be one of the following types: ..., Double, ...

For now, I have to copy my SparseArray to a HashMap an use putSerializable(), which I know is nearly an insult to sanity.

How can I efficiently copy my Double SparseArray to the Parcel ?


Solution

  • You just need to change from SparseArray<Double> to SparseArray<Object>.

    Although Double is a descendant of Object, SparseArray<Double> is not considered a descendant of SparseArray<Object>, that's why you get compile time error.