使用Intent传递对象
原文首发http://blog.lll0.net/post/intent_data.html
在应用中我们会经常用到在页面间传递数值,但是有些数据是存储在对象里面的,为了避免对数据的重复存取过程,在google API提供那个两种解决办法
两种实现方式
采用java序列化的方式对对象处理
//实体类的处理
//直接实现Serializable 序列化接口
public class Student implements Serializable{
private String name = null;
private int age = null;
public Student(Stirng name ,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(){
retuen age;
}
}
按钮实现页面跳转的过程
public void onclick(View v){
Intent intent = new Intent(this,TwoActivity.class);
Bundle bundle = new Bundle();
Student student = new Student();
intent.putSerializable("key",student);
startActivity(intent);
}
获得传递过来的数据
Students student = getIntent().getExtras().getSerializable("key");
采用google提供的方法传递对象
public class Students implements Parcelable{
private String name;
private int age;
private int ima ;
public Students() {
}
public Students(String name, int age, int ima) {
this.name = name;
this.age = age;
this.ima = ima;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getIma() {
return ima;
}
public void setIma(int ima) {
this.ima = ima;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
//此方法必须写否者会在传递内容的时候会出现错误
public static final Parcelable.Creator<Students> CREATOR = new Creator<Students>() {
@Override
public Students[] newArray(int size) {
// TODO Auto-generated method stub
return new Students[size];
}
@Override
public Students createFromParcel(Parcel source) {
Students student = new Students();
//这里的顺序必须和声明的顺序一样
student.setName(source.readString());
student.setAge(source.readInt());
student.setIma(source.readInt());
return student;
}
};
@Override
public void writeToParcel(Parcel dest, int flags) {
//这里的顺序同样需要跟声明一样
dest.writeString(name);
dest.writeInt(age);
dest.writeInt(ima);
}
}
传递过程的方法使用
public void onclick(View v){
Intent intent = new Intent();
Students student = new Students();
Bundle bundle = new Bundle();
bundle.putParcelable("key",student);
intent.putExtras(bundle);
}
获得传递过来的数据
Students student = getIntent().getExtras().getParcelable("key");