2015-09-07 71 views
0

我有一些困難時刻想弄清楚如何用Parcel對象寫數據,我是新來的使用這個類,我一直在做一些研究,但不明白如何在這裏是parcelable類用包裹對象寫數據

public class Item implements Parcelable { 

private String iItemName; 
private String iType; 
private String iSerial; 
private String iRetailer; 
private String iLocation; 
private String iValue; 
private String iDescription; 

public Item() { 
    super(); 
} 

public Item (Parcel in) { 
    super(); 
    this.iItemName = in.readString(); 
    this.iType = in.readString(); 
    this.iSerial = in.readString(); 
    this.iRetailer = in.readString(); 
    this.iLocation = in.readString(); 
    this.iValue = in.readString(); 
    this.iDescription = in.readString(); 
} 

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

@Override 
public void writeToParcel(Parcel parcel, int flags) { 
    parcel.writeString(getItemName()); 
    parcel.writeString(getType()); 
    parcel.writeString(getSerial()); 
    parcel.writeString(getRetailer()); 
    parcel.writeString(getLocation()); 
    parcel.writeString(getValue()); 
    parcel.writeString(getDescription()); 
} 

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

    @Override 
    public Item createFromParcel(Parcel source) { 
     Item item = new Item(); 
     item.iItemName = source.readString(); 
     return item; 
    } 

    public Item [] newArray(int size) { 
     return new Item[size]; 
    } 
}; 

public String getItemName() { 
    return iItemName; 
} 

public void setItemName(String iItemName) { 
    this.iItemName = iItemName; 
} 

我的問題是,如果我想創建一個新的項目對象我需要發送作爲參數地塊對象是嗎?所以我可以這樣做:

String name = getString("name"); 

// how to add name to the parcel object? 

Parcel parcel; 

Item i = new Item(parcel); 
+0

感謝無禮的粗魯的人, – Juanca

回答

3

不,你不需要。你的對象現在有兩個構造函數。你應該像正常一樣創建對象並調用它的setter方法。您應避免手動創建包裹,而應使用writeValue()readValue()方法。

// Create an item as usual 
Item myItem = new Item(); 
myItem.setItemName("name"); 

// Add it to a parcel 
Parcel parcel = Parcel.obtain(); 
parcel.writeValue(myItem); 

// Read the item back from the parcel 
parcel.setDataPosition(0); 
Item newItem = (Item) parcel.readValue(Item.class.getClassLoader()); 

// When you are finished with the parcel 
parcel.recycle(); 

通常從Intent接受它時,你會創建一個從Parcel的對象。在這種情況下,您可以執行以下操作。

// Create intent 
Intent intent = new Intent(this, MyActivity.class); 
Bundle itemBundle = new Bundle(); 
itemBundle.putParcelable("item_extra", myItem); 
intent.putExtras(itemBundle); 
startActivity(intent); 

// In the activities onCreate(Bundle savedInstanceState) 
Item myItem = getIntent().getParcelableExtra("item_extra"); 
+0

非常感謝,現在我明白了!我會做一些測試,看看會發生什麼 – Juanca