Serializable、Parcelable方式传送数据

一、Serializable

实体类的实现:

public class Student1 implements Serializable {
    private int id;
    private String name;

    public Student1() {
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

}

发送、接收数据:

//        1.发送数据
        Student1 student1 = new Student1();
        Intent intent1 = new Intent(MainActivity.this, SecondActivity.class);
        intent1.putExtra("student1", student1);
        startActivity(intent1);

//        2.接收数据
        Intent intent1 = getIntent();
        Student1 student1 = (Student1) intent1.getSerializableExtra("student1");

二、Parcelable

实体类的实现:

public class Student2 implements Parcelable {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

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

    public Student2() {
    }

    protected Student2(Parcel in) {
        id = in.readInt();
        name = in.readString();
    }

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

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

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
    }
}

发送、接收数据:

//        1.发送数据
        Student2 student2 = new Student2();
        Intent intent2 = new Intent(MainActivity.this, SecondActivity.class);
        intent2.putExtra("student2", student2);
        startActivity(intent2);

//        2.接收数据
        Intent intent2 = getIntent();
        Student2 student2 = intent2.getParcelableExtra("student2");

 

全部评论

相关推荐

头像
10-22 19:18
上海大学 后端
jopajhhdjwnqk:水印都叠杀人书了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务