在活动之间传递自定义对象

也可以使用 Bundle 类将自定义对象传递给其他活动。

有两种方法:

  • Serializable 接口 - 适用于 Java 和 Android
  • Parcelable 界面内存高效,仅适用于 Android(推荐)

Parcelable

可分割处理比可序列化快得多。其中一个原因是我们明确了序列化过程而不是使用反射来推断它。理所当然,代码已经为此目的进行了大量优化。

public class MyObjects implements Parcelable {
    
    private int age;
    private String name;
    
    private ArrayList<String> address;
    
    public MyObjects(String name, int age, ArrayList<String> address) {
        this.name = name;
        this.age = age;
        this.address = address;
    
    }
    
    public MyObjects(Parcel source) {
        age = source.readInt();
        name = source.readString();
        address = source.createStringArrayList();
    }
    
    @Override
    public int describeContents() {
        return 0;
    }
    
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(age);
        dest.writeString(name);
        dest.writeStringList(address);
    }
    
    public int getAge() {
        return age;
    }
    
    public String getName() {
        return name;
    }
    
    public ArrayList<String> getAddress() {
        if (!(address == null))
            return address;
        else
            return new ArrayList<String>();
    }
    
    public static final Creator<MyObjects> CREATOR = new Creator<MyObjects>() {
        @Override
        public MyObjects[] newArray(int size) {
            return new MyObjects[size];
        }
    
        @Override
        public MyObjects createFromParcel(Parcel source) {
            return new MyObjects(source);
        }
    };
}

发送活动代码

MyObject mObject = new MyObject("name","age","Address array here");

//Passing MyOject 
Intent mIntent = new Intent(FromActivity.this, ToActivity.class);
mIntent.putExtra("UniqueKey", mObject);
startActivity(mIntent);

在目标活动中接收对象

//Getting MyObjects 
Intent mIntent = getIntent();
MyObjects workorder = (MyObjects) mIntent.getParcelable("UniqueKey");

你可以传递 Parceble 对象的 Arraylist,如下所示

//Array of MyObjects
ArrayList<MyObject> mUsers;

//Passing MyObject List
Intent mIntent = new Intent(FromActivity.this, ToActivity.class);
mIntent.putParcelableArrayListExtra("UniqueKey", mUsers);
startActivity(mIntent);

//Getting MyObject List
Intent mIntent = getIntent();
ArrayList<MyObjects> mUsers = mIntent.getParcelableArrayList("UniqueKey");

注意: 有过 Android Studio 插件,如这一个可用来生成代码 Parcelable

序列化

发送活动代码

Product product = new Product();
Bundle bundle = new Bundle();
bundle.putSerializable("product", product);
Intent cartIntent = new Intent(mContext, ShowCartActivity.class);
cartIntent.putExtras(bundle);
mContext.startActivity(cartIntent);

在目标活动中接收对象。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle bundle = this.getIntent().getExtras();
    Product product = null;
    if (bundle != null) {
        product = (Product) bundle.getSerializable("product");
    }

serializable 对象的 Arraylist:与单个对象传递相同

自定义对象应该实现 Serializable 接口。