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

 2023-09-18 阅读 15 评论 0

摘要:在Activity中使用方法:1)传递单一对象,具体代码如下:// parcelable对象传递方法java序列化的作用?public void setParcelableMethod() {Person person = new Person();person.setmName("王海康");person.setmSex("男");Android原生?perso

在Activity中使用方法:

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

// parcelable对象传递方法

java序列化的作用?public void setParcelableMethod() {

Person person = new Person();

person.setmName("王海康");

person.setmSex("男");

Android原生?person.setmAge(45);

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

Bundle bundle = new Bundle();

bundle.putParcelable(PAR_KEY, person);

java序列化原理,intent.putExtras(bundle);

startActivity(intent);

}

// parcelable对象获取方法

序列化的作用、public Person getParcelableMethod(){

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

return mPerson;

}

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

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

// parcelable对象List传递方法

public void setParcelableListMethod() {

android技术,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);

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/76668.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息