2013-02-13 48 views
0

我基於snippet創建了自己的Parcelable類,以通過Intent發送自定義數據。使用它,Android(Min。API 10)給了我一個例外,它下面的那段代碼有什麼問題?我把它分解到最低限度。那就是:如何在Android Parcelable中使用類字段數組

public class MyParcelable implements Parcelable { 
private float[] data = null; 

public MyParcelable(float[] data) { 
    this.data = data; 
} 

public MyParcelable(Parcel in) { 
    /* After this line the exception is thrown */ 
    in.readFloatArray(data); 
} 

public static final Creator<MyParcelable> CREATOR = new Creator<MyParcelable>() { 
    public MyParcelable createFromParcel(Parcel in) { 
     return new MyParcelable(in); 
    } 

    public MyParcelable[] newArray(int size) { 
     return new MyParcelable[size]; 
    } 
}; 

public int describeContents() { 
    return this.hashCode(); 
} 

public void writeToParcel(Parcel out, int flags) { 
    out.writeFloatArray(data); 
} 

public float[] getData() { 
    return data; 
} 
} 
+0

describeContents()返回位掩碼,而不是hashCode! – 2013-05-01 10:08:11

回答

0

尋找解決的辦法很長一段時間,我偶然發現這個post,其中獅王給工作提示後。

的Parcelable類現在看起來是這樣的:

public class MyParcelable implements Parcelable { 
private float[] data = null; 

public MyParcelable(float[] data) { 
    this.data = data; 
} 

public MyParcelable(Parcel in) { 
    /* The exception is gone */ 
    data = in.createFloatArray(); 
} 

public static final Creator<MyParcelable> CREATOR = new Creator<MyParcelable>() { 
    public MyParcelable createFromParcel(Parcel in) { 
     return new MyParcelable(in); 
    } 

    public MyParcelable[] newArray(int size) { 
     return new MyParcelable[size]; 
    } 
}; 

public int describeContents() { 
    return this.hashCode(); 
} 

public void writeToParcel(Parcel out, int flags) { 
    out.writeFloatArray(data); 
} 

public float[] getData() { 
    return data; 
} 
} 

該解決方案還與其他基本類型的數組。