我有两个可怜的人:
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或Geography受保护的构造函数,但我不知道如何。任何人都可以帮助我吗?谢谢你的时间。
答案 0 :(得分:1)
您正在编写Geography
的实例:
dest.writeParcelable(LastLocalization.get("Geography"), 0);
您正在尝试阅读Map<String, Geography>
:
LastLocalization = in.readParcelable(Geography.class.getClassLoader());
这些不是一回事。
如果您希望已恢复的MyDevice
包含完整的LastLocalization
地图,则应该:
dest.writeParcelable(LastLocalization, 0);
答案 1 :(得分:1)
你的问题就在这一行:
LastLocalization = in.readParcelable(Geography.class.getClassLoader());
您正在阅读Geography
类型的parcelable并尝试将其分配到Map
类型的字段。
您应该将其修改为以下内容:
Geography geography = in.readParcelable(Georgraphy.class.getClassLoader());
LastLocalization = new HashMap<>();
LastLocalization.put("Geography", geography);
它基本上将您的行为从writeToParcel()
撤消。