Created
July 15, 2015 06:59
-
-
Save laaptu/f55666e11c8911d28d70 to your computer and use it in GitHub Desktop.
Parcelable Sparse Array Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does not work when process is killed.
_sparseArray = in.readSparseArray(ParcelableSparseArray.class.getClassLoader());
is always empty. But it can store and restore other valuesize
successfully.