我有两个可包裹的 clsses:
class MyDevice implements Parcelable{
@SerializedName("DeviceName")
public String DeviceName;
@SerializedName("StolenFlag")
public Boolean StolenFlag;
@SerializedName("BatteryLevel")
public int BatteryLevel;
@SerializedName("LastLocalization")
public Map<String,Geography> LastLocalization;
protected MyDevice(Parcel in) {
DeviceName = in.readString();
BatteryLevel = in.readInt();
StolenFlag = in.readByte() !=0;
LastLocalization = in.readParcelable(Geography.class.getClassLoader());
}
....
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(DeviceName);
dest.writeByte((byte) (StolenFlag ? 1 : 0));
dest.writeInt(BatteryLevel);
dest.writeParcelable(LastLocalization.get("Geography"), 0);
}
}
第二:
class Geography implements Parcelable{
@SerializedName("CoordinateSystemId")
public int CoordinateSystemId;
@SerializedName("WellKnownText")
public String WellKnownText;
protected Geography(Parcel in) {
CoordinateSystemId = in.readInt();
WellKnownText = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(CoordinateSystemId);
dest.writeString(WellKnownText);
}
}
把它放在意图中是可以的。当我尝试从意图中获取它时:
Intent intent = getIntent();
ArrayList<MyDevice> MyDevicesList = intent.getParcelableArrayListExtra("data");
我的应用崩溃并给出错误:java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.andrev.lab3/com.example.andrev.lab3.SecondActivity}: java.lang.ClassCastException: com.example.andrev.lab3.Geography cannot be cast to java.util.Map
我想我应该修改MyDevice或受地理保护的构造函数,但我不知道如何修改。谁能帮我?谢谢你的时间。
你的问题是这一行:
LastLocalization = in.readParcelable(Geography.class.getClassLoader());
您正在读取类型为 Geography
的包裹对象,并尝试将其分配给类型为 Map
的字段。
您应该将其修改为如下所示的内容:
Geography geography = in.readParcelable(Georgraphy.class.getClassLoader());
LastLocalization = new HashMap<>();
LastLocalization.put("Geography", geography);
它基本上是将你的行为从writeToParcel()
中逆转。
您正在编写 Geography
的实例:
dest.writeParcelable(LastLocalization.get("Geography"), 0);
您正在尝试读取Map<String, Geography>
:
LastLocalization = in.readParcelable(Geography.class.getClassLoader());
这些不是一回事。
如果希望还原的MyDevice
包含完整的LastLocalization
映射,则应具有:
dest.writeParcelable(LastLocalization, 0);