Android学习笔记----使用Intent传递对象

/*********************************************************************************************************************/

使用Intent传递对象

使用Intent来传递对象,通常有两种方式实现,Serializable和Parcelable

Serializable
是序列化的意思,表示将一个对象转换成可存储或者可传输的状态。序列化后的对象可以在网络上传输,也可以在本地存储。序列化的方法非常简单,让一个类去继承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;
        }
}
主Activity

Person person = new Person();
person.setName("zhangsan");
person.setAge(10);
Intent intent = new Intent(this,"");
intent.putExtra("person_data", person);
startActivity(intent);
启动Activity

Person personb = (Person) getIntent().getSerializableExtra("pseron_data");


Parcelable

除了Serializable之外,使用Parcelable也可以实现相同的效果,不过不同于将对象进行序列化,Parcelable方式的实现原理是将一个完整的对象进行分解,而分解后的每一部分都是Intent所支持的数据类型,这样也就实现传递对象的功能了。

class Person implements Parcelable{

private String name;
   private int age;

   protected Person(Parcel in) {
        name = in.readString();//读的顺序要跟writeToParcel方法中写的书序一致
        age = in.readInt();
    }



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


    @Override
    public void writeToParcel(Parcel dest, int flags) {

            dest.writeString(name);
            dest.writeInt(age);
    }

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

    public static final Creator<Person> CREATOR = new Creator<Person>() {

        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

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

主Activity 代码同上

启动的Activity 

Person personb = (Person) getIntent().getParcelableExtra("pseron_data");

两种方式对比

Serializable方式比较简单,但是他会将整个对象序列化,因此在效率方面回避Parcelable方式低一些,所以在通常的情况下,我们推荐使用Parcelable方式来实现对象的序列化。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值