1. 程式人生 > >Intent傳遞序列化資料

Intent傳遞序列化資料

Serializable序列化資料

  • 這是一種比較簡單的序列化,只需要將要序列化的類實現Serializable介面,不用再執行其他操作,在Intent中放入序列化資料即可
  • 序列化資料
public class Student implements Serializable{
    private String name;
    private String age;
    private String sex;

    public Student(String name, String age, String sex) {
        this.name = name;
        this
.age = age; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public
String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
  • 放入和拿出資料
                //放入資料
                Student lisi=new Student("李四","25","女");
                intent.putExtra("lisi",lisi);
                //取出資料
                Student lisi= (Student) intent.getSerializableExtra
("lisi"); System.out.println(lisi.getName());

Parcelable序列化資料

  • 序列化資料,由於as很智慧,基本的複寫方法,也會幫我們自動生成
public class People  implements Parcelable{
    private String name;
    private String age;
    private String sex;

    public People(String name, String age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

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

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

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

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

    //下面的兩個方法,程式碼中內容必須一一對應
    protected People(Parcel in) {
        name = in.readString();
        age = in.readString();
        sex = in.readString();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeString(age);
        dest.writeString(sex);
    }
}
  • 放入和取出資料
                //放入資料
                People zhangsan=new People("張三","20","男");
                intent.putExtra("zhangsan",zhangsan)
                //取出資料
                Intent intent=getIntent();
                People zhangsan= (People) intent.getParcelableExtra("zhangsan");
                textView.setText(zhangsan.getName()+zhangsan.getAge()+zhangsan.getSex());

二者區別

  • 從編寫上來講Serializable序列化更比較書寫簡單,但是Serializable同時效率會比較低,因為Serializable原本是java中用來序列化的介面
  • Parcelable雖然編寫略複雜,但是由於as的存在,讓這些複雜都不在複雜,並且其效率更高,因此建議使用Parcelable序列化來傳遞資料。