Activity之间传递数据

在Activity之间传递数据时有两种方式
1、Serializable方式:序列化方式,即将一个对象转化为可存储或者是可传输的内容,相应的将数据从内存卡中读取出来是反序列化方式
2、Parcelable方式:将一个完整的对象分解成每一个都可以用Intent传输的对象。

使用Serializable传递数据

        Intent intent = new Intent(MainActivity.this, SecondActivity.class);
        //传递boolean类型
        intent.putExtra("boolean", true);
        //传递字符串类型
        intent.putExtra("String", "String");
        //传递整型
        intent.putExtra("Integer", 0);

        //有时候需要同时传递多个数据,这时我们可以使用一个Bundle将其封装起来
        Bundle bundle = new Bundle();
        bundle.putString("s", "s");
        //传递实体类时,必须实现Serializable接口
        bundle.putSerializable("man", new Man("jack", 10));
        //传递字符型
        bundle.putChar("char", 'c');
        //将bundle放入到intent中
        intent.putExtras(bundle);

        //启动activity
        startActivity(intent);
        //获取数据是也比较简单,对应类型就行了:
        String data = getIntent().getStringExtra("String");
        //获取到Bundle对象
        Bundle extras = getIntent().getExtras();
        //再根据bundle中 类型获取到对应的数据

使用Parceleable传递数据

public class Person implements Parcelable {
    private String name;
    private int age;
    private int id;

    public Person(String name, int age, int id) {
        this.name = name;
        this.age = age;
        this.id = id;
    }

    //读取数据:什么类型对应其相应的类型
    protected Person(Parcel in) {
        name = in.readString();
        age = in.readInt();
        id = in.readInt();
    }

    public static final Creator<Person> CREATOR = new Creator<Person>() {
        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }
    };

    @Override
    public String toString() {
        return "name:" + name + "\t" + "age:" + age + "\t id:" + id;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    //往Parcelable中写入相应的数据
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
        dest.writeInt(id);
    }
}读取方式都是相同的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值