Skip to content

Instantly share code, notes, and snippets.

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;
public class ParcelableSparseArray<T>
extends SparseArray<T>
implements Parcelable {
public static final Parcelable.Creator<ParcelableSparseArray> CREATOR = new Creator<ParcelableSparseArray>() {
public ParcelableSparseArray createFromParcel(Parcel source) {
return new ParcelableSparseArray(source);
public ParcelableSparseArray[] newArray(int size) {
return new ParcelableSparseArray[size];
private SparseArray<Object> sparseArray;
public ParcelableSparseArray(int size) {
public ParcelableSparseArray() {
// -----------------------------------------------------------------------
// 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));
public int describeContents() {
return 0;
public void writeToParcel(Parcel out, int flags) {
int size = size();
sparseArray = new SparseArray<>(size);
for (int i = 0; i < size; i++) {
sparseArray.put(keyAt(i), valueAt(i));

This comment has been minimized.

Copy link

jemshit 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.