【问题标题】:How to send an object from one Android Activity to another using parcelable?如何使用 parcelable 将对象从一个 Android Activity 发送到另一个?
【发布时间】:2012-07-06 20:10:09
【问题描述】:

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

Team 类:

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 与类的其余部分一起传递?

【问题讨论】:

  • 什么是事件? Event 类是否可序列化?

标签: android serialization parcelable


【解决方案1】:

StringTreeMapHashMap 都实现了Serializable 接口。您可以考虑在您的 Team 类中实现 Serializable 并以这种方式在活动之间传递它。这样做可以让您直接从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 类是否可序列化。)

【讨论】:

  • 我会试试的。谢谢.. 我使用 parcelable 是因为在其他一些线程中他们提到 Serializable 是一个相当肮脏的解决方案。
  • 太棒了!!即使我使用可序列化,也能很好地工作并且并不慢。谢谢!
猜你喜欢
  • 2011-01-09
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多