Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Parcelable Sparse Array Implementation
package com.zala.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.SparseArray;
/**
* https://gist.github.com/kaushikgopal/9eea148a2188dc58fe37
*/
public class ParcelableSparseArray<T>
extends SparseArray<T>
implements Parcelable {
public static final Parcelable.Creator<ParcelableSparseArray> CREATOR = new Creator<ParcelableSparseArray>() {
@Override
public ParcelableSparseArray createFromParcel(Parcel source) {
return new ParcelableSparseArray(source);
}
@Override
public ParcelableSparseArray[] newArray(int size) {
return new ParcelableSparseArray[size];
}
};
private SparseArray<Object> sparseArray;
public ParcelableSparseArray(int size) {
super(size);
}
public ParcelableSparseArray() {
super();
}
// -----------------------------------------------------------------------
// Parcelable implementation
private ParcelableSparseArray(Parcel in) {
int size = in.readInt();
//sparseArray = new SparseArray<>(size);
sparseArray = in.readSparseArray(ParcelableSparseArray.class.getClassLoader());
for (int i = 0; i < size; i++) {
int key = sparseArray.keyAt(i);
put(key, (T) sparseArray.valueAt(i));
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
int size = size();
out.writeInt(size);
sparseArray = new SparseArray<>(size);
for (int i = 0; i < size; i++) {
sparseArray.put(keyAt(i), valueAt(i));
}
out.writeSparseArray(sparseArray);
}
}
@jemshit

This comment has been minimized.

Copy link

commented Feb 20, 2017

Does not work when process is killed. _sparseArray = in.readSparseArray(ParcelableSparseArray.class.getClassLoader()); is always empty. But it can store and restore other value size successfully.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.