您的位置:首页 > 移动开发 > Android开发

android学习杂记(1)--Intent传递对象数据

2015-05-18 09:20 363 查看
Intent意图不仅可以传递基本数据类型的数据,也可以传递对象数据。
android提供了两种传递对象的方式:对象数据的序列化和对象数据的分解。


一、数据的序列化

使将要传递的对象类实现Seriazliable接口。

/*1.使将要传递的对象实现Serializable接口,实现序列化*/
public class Person implements Serializable {

private int age;
private String name;

public int getAge() {
return age;
}

public String getName() {
return name;
}

public void setAge(int age) {
this.age = age;
}

public void setName(String name) {
this.name = name;
}
}


/*2.发送对象数据*/
Intent intent = new Intent(this,SecondActivity.class);
Person p = new Person();
p.setAge(12);
p.setName("zyj");
intent.putExtra("person",p);


/*3.得到Intent对象并获取序列化数据*/
Intent intent = getIntent();
Person person = (Person)intent.getSerializableExtra("person");
int age = person.getAge();
String name = person.getName();


二、数据对象的分解

/*1.使将要传递的类实现Parceable接口并为其成员变量提供相应的get和set方法*/
public class Person implements Parcelable {

private String name;
private int age;

public String getName() {
return name;
}

public int getAge() {
return age;
}

public void setName(String name) {
this.name = name;
}

public void setAge(int age) {
this.age = age;
}
//复写describeContents()方法,返回0
@Override
public int describeContents() {
return 0;
}
//复写writerToParcel方法,将对象的成员变量数据使用Parcel对象输出
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
//创建变量CREATOR,格式为固定格式,泛型的类型就是我们要发送的对象数据的类名。
public static  final  Creator<Person> CREATOR = new Creator<Person>(){

//上文中用Parcel对象写入,现在用Parecl对象读取。注意本处读的顺序必须和上面写的顺序一致
@Override
public Person createFromParcel(Parcel source) {
Person person = new Person();
person.name = source.readString();
person.age = source.readInt();
return person;
}
//复写newArray方法,格式如下
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}


//2.发送对象
//设置数据对象
Person person = new Person();
person.setName("zyj");
person.setAge(23);
//设置意图并发送数据
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("person",person);
startActivity(intent);


/*3.获取到发送的对象数据*/
Intent intent = getIntent();
Person person = (Person) intent.getParcelableExtra("person");
String name = person.getName();
int age = person.getAge();


上面两种方式操作不同,若无特殊要求,建议使用Parcel方式实现对象的传递,虽然书写麻烦但是性能好。Serializable接口为android重量级组件,较为耗费性能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: