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

时间:2012-07-06 20:10:10

标签: android serialization parcelable

我正在尝试将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与其他类一起传递?

1 个答案:

答案 0 :(得分:1)

StringTreeMapHashMap都实现了Serializable界面。您可以考虑在Serializable类中实现Team,并将其传递给活动。这样做可以让您直接从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类是否可序列化。)