android - 如何使用 parcelable 将对象从一个 Android Activity 发送到另一个?

标签 android serialization parcelable

我正在尝试将类型为 Team 的对象传递到我应用中的另一个 Activity

团队类:

public class Team implements Parcelable {

    String teamName;

    //Name and Link to competition of Team
    TreeMap<String, String> competitions;
    //Name of competition with a map of matchdays with all games to a matchday
    TreeMap<String, HashMap<Integer, ArrayList<Event>>> matchDays;

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(teamName);
        dest.writeMap(competitions);    
    }

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

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

    private Team(Parcel in) {
        teamName = in.readString();

        in.readMap(competitions, Team.class.getClassLoader());
    }
}

我在编码时得到一个 RuntimeException:

TreeMap<String, HashMap<Integer, ArrayList<Event>>> matchDays;

如何将嵌套的 TreeMap 与类的其余部分一起传递?

最佳答案

StringTreeMapHashMap 都实现了Serializable 接口(interface)。您可能会考虑在您的 Team 类中实现 Serializable 并以这种方式在 Activity 之间传递它。这样做将使您可以直接从 BundleIntent 加载对象,而无需手动解析它们。

public class Team implements Serializable {

    String teamName;

    //Name and Link to competition of Team
    TreeMap<String, String> competitions;
    //Name of competition with a map of matchdays with all games to a matchday
    TreeMap<String, HashMap<Integer, ArrayList<Event>>> matchDays;

不需要额外的解析代码。

(编辑:ArrayList 还实现了 Serializable,因此此解决方案取决于 Event 类是否可序列化。)

关于android - 如何使用 parcelable 将对象从一个 Android Activity 发送到另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11369029/

相关文章:

android - WiFiDirectActivity 是什么/在哪里

c# - 在哪些情况下我必须在 WPF 中序列化命令的对象?

java - 在 Java 中使用序列化实现克隆方法是一种好习惯吗?

android - 如何将 Parcelable 传递给两个或多个 Activity 或 Fragments?

android - 使类可打包错误

Android WIFI如何检测特定的WIFI连接何时可用

java - LibGDX 将文本绘制到左上角

javascript - 以 jquery 形式序列化变量设置 jquery 延迟

android - 如何使用以下 JSON 数据创建 Parcelable 类?

java - Android 无法解析导入的符号