2012-04-30 51 views
2

我想將一個類的數組從一個活動傳遞到另一個。爲了做到這一點,該類正在實現Parcelable。問題是類中的幾個字段爲null。如何檢查並僅發送值不爲null。我認爲這可以通過writeToParcel()中的簡單if/else輕鬆完成,但是如何在將參數作爲Parcel參數的類的構造函數中執行相同操作。就像如下類實現Parcelable

private Student(Parcel in) { 
} 

有一些問題,同時發送空值..

編輯:添加代碼

@Override 
     public void writeToParcel(Parcel dest, int flags) { 
      dest.writeString(id); 
      dest.writeString(name); 
      dest.writeString(grade); 
      dest.writeString(dateOfBirth); 
      dest.writeString(place); 
       //Like wise there are many other fields 
       //We have to write only values which are not null 
} 

     private Student(Parcel in) { 
      id=in.readString(); 
      name=in.readString(); 
      grade=in.readString(); 
      dateOfBirth=in.readString(); 
      place=in.readString(); 
      //like wise have to read all other fields 
      //we have to make sure we read only values which are not null 
} 
+0

你怎麼不執行'Serializable'而不是通過? – Jave

+0

你試圖達到什麼沒有任何意義。您已經分析了您的問題並封裝了您的域對象,在學生層面以OO方式思考更多。沒有必要關心和做外部的域對象的內部值的特殊條件代碼。 – yorkw

+0

粘貼你的代碼......它應該不是一個問題來處理空值 – waqaslam

回答

-1

Simpest的方法是創建一個Globalclass.java和聲明靜態的ArrayList像公共靜態ArrayList<String> arrayList = new ArrayList<String>(); 當你想使用Globalclass.arrayList = value;並在項目中使用任何軟件。

另一種方式使用意圖

Intent i =new Intent(this,2activity.class); 
i.putStringArrayListExtra(name, arrayList); 
+0

以及我真的不想創建任何靜態ArrayList,最終可能導致內存崩潰在我的project.ArrayList中我的項目可能有多達300個類對象。每個類都有大約20個元素。所以創建靜態ArrayList不是明智的想法。 – androidGuy

+0

Intent i = new Intent(this,2activity.class); i.putStringArrayListExtra(name,value); –

+0

由於全局靜態變量而被降級。這是沒有用的('Intent'被做成這樣做),並且只能導致崩潰(你從另一個調用'Activity'時,靜態變量仍爲'null'?) –

相關問題