简体   繁体   中英

How to send an object from one Android Activity to another using parcelable?

I'm trying to pass an object of type Team to another Activity in my app.

The Team class:

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());
    }
}

I get a RuntimeException when marshalling:

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

How can I pass the nested TreeMap along with the rest of the class?

String , TreeMap , and HashMap all implement the Serializable interface. You might consider implementing Serializable in your Team class and passing it between activities that way instead. Doing so would make it so you that you can just load the object straight from the Bundle or Intent without having to manually parse them out.

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;

No additional parsing code needed.

(Edit: ArrayList also implements Serializable so this solution is dependent on whether the Event class is Serializable or not.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM