关闭

Android Serializable Parcelable 序列化

94人阅读 评论(0) 收藏 举报
分类:

序列化后的对象可以作为一个整体进行传输,便于网络传输和存储。

1、Serializable 

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

传输数据:

Intent intent = new Intent(MainActivity.this,SecondActivity.class);
		Person person = new Person();
		person.setAge(10);
		person.setName("啦啦啦");
		intent.putExtra("person_data",person);
		
		startActivity(intent);
在SecondActivity中获取数据:

Person person = (Person)intent.getParcelableExtra("person_data");

2、Parcelable

public class Person2 implements Parcelable{
	private String name;
	private int age;
	
	public void setName(String name){
		this.name = name;
	}
	
	public String getName(){
		return name;
	}
	
	public void setAge(int age){
		this.age = age;
	}
	
	public int getAge(){
		return age;
	}
	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		// TODO Auto-generated method stub
		dest.writeString(name);<span style="white-space:pre">		</span>//将数据写到pacel
		dest.writeInt(age);
	}
	
	public static final Parcelable.Creator<Person2> CREATOR  = new Parcelable.Creator<Person2>() {

		@Override
		public Person2 createFromParcel(Parcel source) {<span style="white-space:pre">	</span>//将数据从pacel中读取
			// TODO Auto-generated method stub
			Person2 person = new Person2();
			person.name = source.readString();
			person.age = source.readInt();
			return person;
		}

		@Override
		public Person2[] newArray(int size) {
			// TODO Auto-generated method stub
			Person2[] person = new Person2[size];
			return person;
		}
	};

}

传输数据:
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
		Person person2 = new Person2();
		person2.setAge(10);
		person2.setName("啦啦啦");
		intent.putExtra("person_data",person);
		
		startActivity(intent);

在SecondActivity中获取数据:

Person person2 = (Person2)intent.getParcelableExtra("person_data");



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:17413次
    • 积分:646
    • 等级:
    • 排名:千里之外
    • 原创:48篇
    • 转载:10篇
    • 译文:1篇
    • 评论:1条
    文章分类
    最新评论