我有一个 SparseArray<myObject>
并希望将其打包存储在 onSaveInstanceState
中我的 Activity 中的方法并在 oncreate
中恢复它.我找到了 putSparseParcelableArray
将 SparseArray 放入 bundle 的方法,并在 onSaveInstanceState
中执行此操作方法:
bundle.putSparseParcelableArray("mySparseArray", mySparseArray);
但是eclips显示这个错误:
The method putSparseParcelableArray(String, SparseArray<? extends Parcelable>) in the type Bundle is not applicable for the arguments (String, SparseArray<myObject>)
快速解决方法是转换参数 mySparsArray
至 SparseArray<? extends Parcelable>
,但如果我这样做并在 onCreate 方法中获取它:
mySparseArray = (SparseArray<myObject>) savedInstanceState.getSparseParcelableArray("mySparseArray");
它得到这个错误:
Cannot cast from SparseArray<Parcelable> to SparseArray<myObject>
如果这种方式不对,把mySparseArray in bundle的解决方法是什么? 任何帮助将非常感激。
最佳答案
您可以扩展 SparseArray 以在使用时实现可序列化:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import android.util.SparseArray;
/**
* @author Asaf Pinhassi www.mobiledev.co.il
* @param <E>
*
*/
public class SerializableSparseArray<E> extends SparseArray<E> implements Serializable{
private static final long serialVersionUID = 824056059663678000L;
public SerializableSparseArray(int capacity){
super(capacity);
}
public SerializableSparseArray(){
super();
}
/**
* This method is private but it is called using reflection by java
* serialization mechanism. It overwrites the default object serialization.
*
* <br/><br/><b>IMPORTANT</b>
* The access modifier for this method MUST be set to <b>private</b> otherwise {@link java.io.StreamCorruptedException}
* will be thrown.
*
* @param oos
* the stream the data is stored into
* @throws IOException
* an exception that might occur during data storing
*/
private void writeObject(ObjectOutputStream oos) throws IOException {
Object[] data = new Object[size()];
for (int i=data.length-1;i>=0;i--){
Object[] pair = {keyAt(i),valueAt(i)};
data[i] = pair;
}
oos.writeObject(data);
}
/**
* This method is private but it is called using reflection by java
* serialization mechanism. It overwrites the default object serialization.
*
* <br/><br/><b>IMPORTANT</b>
* The access modifier for this method MUST be set to <b>private</b> otherwise {@link java.io.StreamCorruptedException}
* will be thrown.
*
* @param oos
* the stream the data is read from
* @throws IOException
* an exception that might occur during data reading
* @throws ClassNotFoundException
* this exception will be raised when a class is read that is
* not known to the current ClassLoader
*/
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
Object[] data = (Object[]) ois.readObject();
for (int i=data.length-1;i>=0;i--){
Object[] pair = (Object[]) data[i];
this.append((Integer)pair[0],(E)pair[1]);
}
return;
}
}
关于android - 如何在包中存储稀疏数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14899718/