使用Intent传递对象的两种方式

使用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");

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dqliangjun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值