我有一个SparseArray<myObject>
并想将其存储在捆绑中onSaveInstanceState
我的活动中的方法并将其恢复到oncreate
。我发现putSparseParcelableArray
将 SparseArray 放入捆绑包中的方法,并在onSaveInstanceState
method:
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
to SparseArray<? extends Parcelable>
,但如果我这样做并在 onCreate 方法中获取它:
mySparseArray = (SparseArray<myObject>) savedInstanceState.getSparseParcelableArray("mySparseArray");
它得到这个错误:
Cannot cast from SparseArray<Parcelable> to SparseArray<myObject>
如果这种方式是错误的,将 mySparseArray 放入捆绑包中的解决方案是什么?
任何帮助将非常感激。
您可以扩展 SparseArray 来实现 Serialized 并使用它:
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)