序列化的簡單使用day10網絡
一 序列化緣由:ide
1.永久性保存對象,保存對象的字節序列到本地文件中;
2.經過序列化對象在網絡中傳遞對象;
3.經過序列化在進程或activity間傳遞對象。this
簡單代碼 示例日誌
public class Person implements Serializable,Parcelable{對象
private String name;
private int age;
private boolean isMarried;
public Person() {
}進程
public Person(String name, int age, boolean isMarried) {
this.name = name;
this.age = age;
this.isMarried = isMarried;
}
@Override
public String toString() {
return name + "," + age + "," + isMarried;
}內存
@Override
public int describeContents() {
return 0;
}get
@Override //序列化方法
//把這個類的屬性 寫成序列化到 dest
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
dest.writeBooleanArray(new boolean[]{isMarried});
}
//建立一個構造方法做反序列化, 讀和寫的順序要一致
private Person(Parcel source) {
this.name = source.readString();
this.age = source.readInt();
boolean[] b = new boolean[1];
source.readBooleanArray(b);
this.isMarried = b[0];
}
//注意:CREATOR必定要大寫
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {it
@Override
public Person createFromParcel(Parcel source) {
return new Person(source);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
-------------------------------
經過下列代碼 發送端傳輸對象class
Intent intent = new Intent(this, xxx.class);
Bundle bundle = new Bundle();
Person person = new Person("張三", 20, false);
//bundle.putSerializable("person", person);
//putParcelable方法 會調用序列化類裏面的 -- writeToParcel 方法 -- 把數據序列化 -- 寫到 -- dest
//注意:putParcelable 方法只在要跳轉的時候 才調用(即要執行startActivity(intent)時) -- 能夠本身去用日誌貓測測
bundle.putParcelable("person", person);
intent.putExtras(bundle);
startActivity(intent);
------------------------
經過下列代碼 接收端 接收傳輸過來的序列化對象
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
//Person person = (Person) bundle.getSerializable("person");
//經過getParcelable方法 接收序列化對象
//getParcelable方法會先調用序列化類裏的 1 -- createFromParcel -- 開闢一個內存空間
//而後調用 2 -- Person方法 -- 把數據 -- 讀到 -- 開闢好的空間
Person person = bundle.getParcelable("person"); text_next.setText(person.toString());