2013-02-15 1 views
4

나는 SparseArray<myObject>이며, 내 활동에 onSaveInstanceState 방법으로 번들로 저장하고 oncreate에 복원하고 싶습니다.sparsearray를 묶음으로 저장하는 방법

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>) 

그리고 빠른 수정이 SparseArray<? extends Parcelable>에 인수 mySparsArray 캐스팅되어 있지만 경우에 나는 번들에 SparseArray 넣어위한 putSparseParcelableArray 방법을 발견하고 onSaveInstanceState 방법으로 이런 짓을 그렇게와에서 onCreate 방법으로 그것을 얻을 :

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

는이 오류를 가져옵니다

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

이 방법이 잘못되면 mySparseArray를 번들에 넣기위한 해결책은 무엇입니까? 도움을 주시면 감사하겠습니다.

+0

'myObject' 무엇입니까? 'Parcelable'을 구현합니까? – Wenhui

+0

정의한 클래스이며 아무 것도 구현하지 않은 사용자 정의 클래스입니다. Parcelable을 구현해야합니까? – Ehsan

+2

예,'putSparseParcelableArray' 인수를 살펴보면, 그것은'SparseArray '을 확장하므로 Parcelable을 구현하는 객체 만 번들에 넣을 수 있습니다. 'Parcelable '을 구현하는 방법에 대한 도움이 필요합니까? 매우 간단합니다. – Wenhui

답변

5

클래스에는 Parcelable을 구현해야하며 Parcelable.Creator<myObject> 유형의 CREATOR이라는 정적 최종 멤버 변수가 있어야합니다.

+0

@Adrian 감사합니다. – Ehsan

8

당신은 SparsArray 그것을 사용으로 직렬화를 imlement을 확장 할 수

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; 
    } 


} 
+1

for 루프가 앞뒤로 작동하는 좋은 이유는 무엇입니까? 그것은 단지 (int i = 0; i Diederik

+1

@Diederik [카운트하는 것보다 빠르게 카운트 다운합니까?] (http://stackoverflow.com/questions/2823043/is-it-faster-to-count-down-than-it-is-to) -count-up) – Sufian

+1

@Sufian 마이크로 최적화보다 더 읽기 쉬운 코드를 선호합니다. – Diederik