Search code examples
androidandroid-activitybundlesparse-array

How to store sparsearray in bundle


I have a SparseArray<myObject> and want to store it in bundle in onSaveInstanceState method in my activity and restore it in oncreate. I found putSparseParcelableArray method for put SparseArray in bundle and did this in onSaveInstanceState method:

bundle.putSparseParcelableArray("mySparseArray", mySparseArray);

But eclips shows this error:

The method putSparseParcelableArray(String, SparseArray<? extends Parcelable>) in the type Bundle is not applicable for the arguments (String, SparseArray<myObject>)

And the quick fix is casting argument mySparsArray to SparseArray<? extends Parcelable>, but if I do so and get it in onCreate method:

mySparseArray = (SparseArray<myObject>) savedInstanceState.getSparseParcelableArray("mySparseArray");

It gets this error:

Cannot cast from SparseArray<Parcelable> to SparseArray<myObject>

If this way is wrong, what is the solution for put mySparseArray in bundle? Any help would be much appreciated.


Solution

  • Your class should implement Parcelable and should have a static final member variable called CREATOR of type Parcelable.Creator<myObject>.