使用宗地对象编写数据

时间:2015-09-07 07:09:44

标签: java android parcelable

我正在努力弄清楚如何使用Parcel对象来编写数据,我是新手使用这个类而且我一直在做一些研究但是不明白怎么做,这里是可分类的

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;
}

我的问题是,如果我想创建一个新的Item对象,我需要作为参数发送一个Parcel对象,我是对的吗?所以我可以这样做:

String name = getString("name");

// how to add name to the parcel object?

Parcel parcel;

Item i = new Item(parcel);

1 个答案:

答案 0 :(得分: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();

通常,当您从Parcel收到对象时,您会从Intent创建一个对象。在这种情况下,您将执行以下操作。

// 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");