[英]How to pass a Parcelable class which contains a list of another parcelable class?
[英]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
:
Transport
將RoutePoint
寫入Parcel
。 RoutePoint
寫入父Transport
的Parcel
。 Transport
將RoutePoint
寫入Parcel
。 我想知道如何解決此問題,並在活動之間傳遞Transport
類,並以某種方式在RoutePoint
類中傳遞parent
對象。
如果所有RoutePoint
實例始終包含在Transport
實例內,則可以通過不序列化RoutePoint.parent而是在反序列化Transport時進行設置來對其進行修復。
因此,在反序列化Transport實例時,反序列化RoutePoints,然后在這些RoutePoint實例上調用setTransport
方法並設置父對象。
從GC的角度來看,具有這樣的循環引用也不是一個好主意。 我建議您使用一種方法引用,並使用其他數據結構(如BiMap等)來定義這些關系。 一種方法是在RoutePoint中創建一個Empty構造函數,然后僅打包除父項以外的其他項。 在運輸中,從包裹中讀取時,請稍后設置其參考。 希望這是有道理的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.