Android Intent传递对象

Intent传递对象有两种方法
  1. 对象 implements Parcelable
  2. 对象 implements Serializable
前者是专门为Android设计的,效率更高,但是需要重写
describeContents,writeToParcel两个方法。
后者不需要实现任何方法。
下面就只介绍Serializable

1.定义一个类,实现Serializable,也仅仅是多了implements Serializable这句话
public class Contact implements Serializable {
    private String name;
    private String phone;
    private String type;
    private String belong;
    private String backgroundColor;
    private String firstName;
    public Contact(String name, String phone, String type, String belong, String backgroundColor) {
        this.name = name;
        this.phone = phone;
        this.type = type;
        this.belong = belong;
        this.backgroundColor = backgroundColor;
        this.firstName = name.substring(0, 1);
    }
    public String getName() {
        return name;
    }
    public String getPhone() {
        return phone;
    }
    public String getType() {
        return type;
    }
    public String getBelong() {
        return belong;
    }
    public String getBackgroundColor() {
        return backgroundColor;
    }
    public String getFirstName() {
        return firstName;
    }
}

2.通过下面的方法发送对象,因为Bundle只接受基本类型,所以对象必须要序列化
Bundle是一个安全类型的容器,只接受基本类型,是对HashMap的一层封装
Intent intent = new Intent(MainActivity.this, DetailContact.class);
Bundle bundle = new Bundle();
bundle.putSerializable("contact", list.get(position));
intent.putExtras(bundle);
startActivity(intent);

3.通过下面方法接受对象,对象的反序列化
Contact personal = null;
try {
    personal = (Contact) getIntent().getSerializableExtra("contact");
} catch (Exception e) {
    e.printStackTrace();
}

优点:几乎不需要更改代码,也不需要实现序列化的方法,只需要在序列化的类里写
implements Serializable
就可以了
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值