2012-07-06 52 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

相關問題