使用Intent传递对象

声明:笔者参考《第一行代码》一书:
方法1:使用Serializable接口:


public class Person implements Serializable{
   private String name;
   private int age;
   public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}

}
 Person person  =  new Person();
       person.setName("哈登");
       person.setAge(25);

       Intent intent =  new Intent(MainActivity.this,SecondActivity.class);
       intent.putExtra("Person_data", person);
       startActivity(intent);
//得到Person对象
Person p= (Person)getIntent().getSerializableExtra("Person_data");

方法2:实现Parcelable接口

public class Person implements Parcelable{
   private String name;
   private int age;
   public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
//重写describeContents()
@Override
public int describeContents() {
    return 0;
}
//重写writeToParcel()
@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(name);
    dest.writeInt(age);
}
// Person 类中提供一个名为 CREATOR 的常量,创建了
//Parcelable.Creator 接口的一个实现
   public static final Parcelable.Creator<Person> CREATOR = new 
           Creator<Person>() {

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

            @Override
            public Person createFromParcel(Parcel source) {
                Person person  = new Person();
                person.name = source.readString();
                person.age =  source.readInt();
                return person;
            }
        };
}

//取得对象
Person p= (Person) getIntent().getParcelableExtra(“Person_data”);

总结:
writeString,writeInt 和readString,readInt顺序保持一致。
Serializable的方式较为简单,但由于会把整个对象进行序列化,因此效率方面会比 Parcelable 方式低一些,所以在通常情况下还是更加推荐使用 Parcelable 的方式来实现 Intent 传递对象的功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值