【发布时间】:2015-06-03 20:38:06
【问题描述】:
在将自定义数据类型的数组写入包裹后,我遇到了重新创建数组的问题。
playerwear 是这样声明的:
private Wearable playerWear[] = new Wearable[5];
这是将它写入父类中的包裹的行。 它是一个具有 5 个元素的 Wearable 类型的数组
parcel.writeArray(playerWear);
这是从 Parcel 读取它的行(temp 是父级的空数据元素,所有元素都以与下面相同的方式填充。所有其他元素都在工作)
temp.playerWear = (Wearable[])source.readArray(Wearable.class.getClassLoader());
这是在可穿戴数据类型中定义的 Parcel 接口的代码:
@Override
public int describeContents()
{
return 0;
}
/**
* This is the main method of the Parcelable Interface. This packs everything
* up into the parcel that will be used in the next activity
* @param parcel the parcel that will be passed to the next activity
* @param i used to keep track of the size...I think
*/
@Override
public void writeToParcel(Parcel parcel, int i)
{
parcel.writeString(slotName);
parcel.writeParcelable(heldItem, i);
if (holdingItem)
parcel.writeString("True");
else
parcel.writeString("False");
}
/**
* This is the method that takes the passed parcel and rebuilds it so that it can be used
* @param source the passed parcel
* @return the reconstructed data type
*/
public static Wearable recreateParcel(Parcel source)
{
Wearable temp = new Wearable();
temp.slotName = source.readString();
temp.heldItem = (Item) source.readParcelable(Item.class.getClassLoader());
String bool = source.readString();
if(bool.equals("True"))
temp.holdingItem = true;
else
temp.holdingItem = false;
return temp;
}
/**
* Not truly sure what this is but I think this is similar to the classLoader
*/
public static final Parcelable.Creator CREATOR = new Parcelable.Creator()
{
/**
* Calls the method that I created to recreate the Data type
* @param in the passed parcel
* @return s the return of the recreateParcel method
*/
public Wearable createFromParcel(Parcel in)
{
return recreateParcel(in);
}
/**
* Called if the custom data type is in an array
* @param size the size of the array. Used to figure out how many elements are needed
* @return an Array of the Data type
*/
public Wearable[] newArray(int size)
{
return new Wearable[size];
}
};
最后这是它给我的错误,
原因:java.lang.ClassCastException:java.lang.Object[] 无法转换为 com.rtbd.storytime.Wearable[]
如果我忘记了解决此问题所需的任何重要信息,请发布。
谢谢!
【问题讨论】:
标签: android classcastexception parcelable parcel