2012-07-06 53 views
1

我想在我的应用程序中将Team类型的对象传递给另一个Activity如何使用parcelable将对象从一个Android活动发送到另一个活动?

Team类:

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

如何传递嵌套TreeMap中与班上其他同学一起:

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?

+0

什么是事件? Event类是可序列化的吗? – kosa 2012-07-06 20:23:10

回答

1

String,TreeMapHashMap全部实现了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类是可序列化与否)。

+0

我会尝试。谢谢..我使用parcelable,因为在其他一些线程中,他们提到Serializable是一个相当脏的解决方案。 – Ben 2012-07-06 20:29:38

+0

真棒!即使我使用Serializable,它工作得很好,而且速度并不慢。谢谢! – Ben 2012-07-06 20:36:34

相关问题