2011-06-22 29 views
2

在我的應用程序中,我從JavaScript中獲取數據,因爲無法將數據作爲數組或對象返回,因此我將它作爲String返回。在Android中的活動之間傳遞數據的更好方法

現在組織數據我創建一個類,其中包含ArrayList s和其他字符串變量,並進一步我創建我的類對象變量數組來存儲多個記錄。

public class Data { 

    ArrayList<String> m_empArrayList = new ArrayList(); 
    ArrayList<String> m_depArrayList = new ArrayList(); 
    String m_time; 
    String m_duration; 

} 

Data d = new Data(); 

什麼是一種很好的方法來在活動之間傳遞數據?由於Intent s和ShredPrefrence s用於傳遞小數據單位,我在這裏沒有考慮它。

回答

7

在您的自定義對象落實Parcelable接口,並通過Intent發送。

下面是一個Parcelable對象的示例。

public class MyObject implements Parcelable { 

    private String someString = null; 
    private int someInteger = 0; 

    public MyObject() { 
     // perform initialization if necessary 
    } 

    private MyObject(Parcel in) { 
     someString = in.readString(); 
     someInteger = in.readInt(); 
    } 

    public static final Parcelable.Creator<MyObject> CREATOR = 
      new Parcelable.Creator<MyObject>() { 

     @Override 
     public MyObject createFromParcel(Parcel source) { 
      return new MyObject(source); 
     } 

     @Override 
     public MyObject[] newArray(int size) { 
      return new MyObject[size]; 
     } 

    }; 

    // Getters and setters 

    @Override 
    public int describeContents() { 
     return 0; 
    } 

    @Override 
    public void writeToParcel(Parcel dest, int flags) { 
     dest.writeString(someString); 
     dest.writeInt(someInteger); 
    } 

} 

這是發生了什麼事。如果實現Parcelable接口,則必須創建一個以Parcel作爲參數的私有構造函數。 Parcel保存所有的序列化值。

您必須實現名爲CREATOR的嵌套類Parcelable.Creator,因爲這將在Android重新創建對象時被調用。

方法describeContents()只適用於特殊情況。您可以保留它,因爲它的返回值爲0

有趣的行爲發生在writeToParcel(),你的名字告訴你,你的數據寫入一個Parcel對象。

現在,您可以直接將自定義對象直接添加到Intent(如本例中)。

MyObject myObject = new MyObject(); 
Intent i = new Intent(); 
i.setExtra("MY_OBJECT", myObject); 
// implicit or explicit destination declaration 
startActivity(i); 
+0

那麼這真的很好的解釋,但我使用Parcelable和應用程序類之間混淆,所以你有什麼建議? – Hunt

+0

我想它很大程度上取決於用例,但在你的情況下,我會推薦'Parcelables'。 –

+0

好的,因爲我有一個非常沉重的數據使用量,所以我會去與parcelables。 – Hunt

相關問題