//将实体类序列化以下: //有两种方法:1,实现Serializable 2.实现parcelable要重写里面的方法 public class Person implements Serializable,Parcelable{ private String name; private int age; private boolean isMarried; public Person(String name, int age, boolean isMarried) { super(); this.name = name; this.age = age; this.isMarried = isMarried; } public Person() { super(); } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", isMarried=" + isMarried + "]"; } /*经过实现Parcelable接口序列化对象的步骤: 一、声明实现接口Parcelable 二、实现Parcelable的方法writeToParcel,将你的对象序列化为一个Parcel对象 三、实例化静态内部对象CREATOR实现接口Parcelable.Creator: 其中public static final一个都不能少,内部对象CREATOR的名称也不能改变,必须所有大写。 四、完成CREATOR的代码,实现方法createFromParcel,将Parcel对象反序列化为你的对象 */ @Override public int describeContents() { //这个能够不用理 return 0; } //1.写操做//序列化方法 @Override public void writeToParcel(Parcel dest, int flags) { //经过这个方法把对象序列化成Parcel,可理解为把你的对象写到流里面 dest.writeString(name); dest.writeInt(age); //boolean写比较特殊一些,要建立一个数组 dest.writeBooleanArray(new boolean[]{isMarried}); } //2.建立一个私有构造方法做反序列化,注意读和写的顺序要一致 private Person(Parcel source){ this.name=source.readString(); this.age=source.readInt(); //boolean读也比较特殊一些,要建立一个数组 boolean[]b=new boolean[1]; source.readBooleanArray(b); this.isMarried=b[0]; } /*3.实例化静态内部对象CREATOR实现接口Parcelable.Creator: 其中public static final一个都不能少,内部对象CREATOR的名称也不能改变,必须所有大写。 <>里面写的是你的对象实体类 */ public static final Parcelable.Creator<Person>CREATOR=new Parcelable.Creator<Person>() { @Override public Person createFromParcel(Parcel source) { //把Parcel反序列为你的对象,可理解为从流中读取对象 return new Person(source); } @Override public Person[] newArray(int size) { return new Person[size]; } }; } //序列化传输代码,传给另一个页面Activiyty public void send_object(View view){ //传输序列化 Intent intent=new Intent(this,SerializableObject.class); Person person=new Person("张三",23,false); Bundle bundle=new Bundle(); //第一种:实现Serializable方法 //bundle.putSerializable("person", person);//实现序列化接口后,bundle能够直接传递序列化对象 //第二种:实现Parcelable bundle.putParcelable("person", person); intent.putExtras(bundle); startActivity(intent); /*不须要返回数据时使用这个startActivity(),有数据回传时用 这个startActivityForResult(intent, requestCode);且要重写onActivityResult()回传方法处理数据*/ } //在另一个页面接收的代码 text_next=(TextView) this.findViewById(R.id.text_next); Intent intent=getIntent();//获取点击到本页面的意图 Bundle bundle=intent.getExtras(); //这是第一种实现Serializable方法接收 //Person person=(Person) bundle.getSerializable("person"); //第二种:实现Parcelable接收 Person person=bundle.getParcelable("person"); text_next.setText(person.toString());