簡體   English   中英

如何將包含可包裹類“ B”的實例的可包裹類“ A”的實例寫入類“ B”的包裹

[英]How to write an instance of Parcelable class 'A' which contains an instance of parcelable class 'B', to Parcel from class 'B'

我在Android應用程序中使用可包裹貨物時遇到一些問題。
我有一個名為Transport的自定義類,其中包含一堆RoutePoint ,這些RoutePoint已從文件加載並保存在數組中。

這兩個類都implements Parcelable ,因為我想在多個活動之間傳遞包含RoutePoint對象的Transport對象。

這就帶來了一個問題,因為在每個RoutePoint對象的內部,都有一個Transport對象,該對象用於告訴哪個傳輸是RoutePoint的父RoutePoint

假設我有這些課程:

Transport

public class Transport implements Parcelable
{
    private RoutePoint[] points;

    public Transport()
    {
        // Here the array is initialized
    }

    // Methods needed because of the Parcelable interface
}

RoutePoint

public class RoutePoint implements Parcelable
{
    private Transport parent;

    public RoutePoint(Transport parent)
    {
        this.parent = parent;
    }

    // Methods needed because of the Parcelable interface
}

當將Transport類寫入Parcel ,我也將數組中的所有RoutePoint都寫入了包裹。

RoutePoint類被寫入到一個Parcel ,我寫的父Transport的包裹了。

這將導致“遞歸調用”和StackOverflowException

  1. TransportRoutePoint寫入Parcel
  2. RoutePoint寫入父TransportParcel
  3. TransportRoutePoint寫入Parcel
  4. 返回步驟2。

我想知道如何解決此問題,並在活動之間傳遞Transport類,並以某種方式在RoutePoint類中傳遞parent對象。

如果所有RoutePoint實例始終包含在Transport實例內,則可以通過不序列化RoutePoint.parent而是在反序列化Transport時進行設置來對其進行修復。

因此,在反序列化Transport實例時,反序列化RoutePoints,然后在這些RoutePoint實例上調用setTransport方法並設置父對象。

從GC的角度來看,具有這樣的循環引用也不是一個好主意。 我建議您使用一種方法引用,並使用其他數據結構(如BiMap等)來定義這些關系。 一種方法是在RoutePoint中創建一個Empty構造函數,然后僅打包除父項以外的其他項。 在運輸中,從包裹中讀取時,請稍后設置其參考。 希望這是有道理的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM