android序列化好处,浅谈Android序列化

在Activity中使用方法:

1)传递单一对象,具体代码如下:

// parcelable对象传递方法

public void setParcelableMethod() {

Person person = new Person();

person.setmName("王海康");

person.setmSex("男");

person.setmAge(45);

Intent intent = new Intent(this, PersonTest.class);

Bundle bundle = new Bundle();

bundle.putParcelable(PAR_KEY, person);

intent.putExtras(bundle);

startActivity(intent);

}

// parcelable对象获取方法

public Person getParcelableMethod(){

Person mPerson = (Person)getIntent().getParcelableExtra(PAR_KEY);

return mPerson;

}

2)传递对象列表,具体代码如下:

需要注意的是,若ListpersonList = new ArrayList();则会报错,因为下面调用的putParcelableArrayList()函数其中一个参数的类型为ArrayList。

// parcelable对象List传递方法

public void setParcelableListMethod() {

ArrayList personList = new ArrayList();

Person person1 = new Person();

person1.setmName("王海康");

person1.setmSex("男");

person1.setmAge(45);

personList.add(person1);

Person person2 = new Person();

person2.setmName("薛岳");

person2.setmSex("男");

person2.setmAge(15);

personList.add(person2);

Intent intent = new Intent(this, PersonTest.class);

Bundle bundle = new Bundle();

bundle.putParcelableArrayList(PAR_LIST_KEY, personList);

intent.putExtras(bundle);

startActivity(intent);

}

// parcelable对象获取方法

public ArrayList getParcelableMethod(){

ArrayList mPersonList = getIntent().getParcelableExtra(PAR_LIST_KEY);

return mPersonList;

}

3)最后介绍一个投机取巧的方法:

不用继承Parcelable或Serializable方法即可实现IPC中对象的传递。这种方法的实现原理不是很明白,只知道代码中new ArrayList()返回的其实是一个EmptyArray.OBJECT数组,不过我感觉应该还是系统调用Serializable进行序列化的,如果各位读者有好的想法,欢迎告知。

具体代码如下:

//对象List传递

public void setObjectMethod(){

......(省略)

ArrayList list = new ArrayList();

//ObjectList为某一对象列表

list.add(ObjectList);

bundle.putParcelableArrayList(PAR_LIST_KEY, list);

intent.putExtras(bundle);

startActivity(intent);

}

//获取对象List

ArrayList list = bundle.getParcelableArrayList("list");

//强转成你自己定义的list,这样ObjectList就是你传过来的那个list了。

ObjectList= (List) list.get(0);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值