使用意圖在Activity之間傳遞數據小插曲__傳遞自定義的序列化對象

 自定義序列化類 

Java代碼 
  1. public class Contacts implements Parcelable {  
  2.     public static final String PARCELABLE_KEY = "aliusa.cn.ui.Contacts.parcelableKey";   
  3.     private int id;  
  4.     private String name;  
  5.   
  6.     public Contacts(int id,String name){  
  7.         this.name = name;  
  8.         this.id = id;  
  9.     }  
  10.       
  11.     public int getId() {  
  12.         return id;  
  13.     }  
  14.   
  15.     public void setId(int id) {  
  16.         this.id = id;  
  17.     }  
  18.   
  19.     public String getName() {  
  20.         return name;  
  21.     }  
  22.   
  23.     public void setName(String name) {  
  24.         this.name = name;  
  25.     }  
  26.   
  27.   
  28.     @Override  
  29.     public int describeContents() {  
  30.         return 0;  
  31.     }  
  32.   
  33.    //實現Parcelable的方法writeToParcel,將Contacts序列化爲一個Parcel對象 
  34.     @Override  
  35.     public void writeToParcel(Parcel dest, int flags) {  
  36.           
  37.         dest.writeInt(id);    
  38.         dest.writeString(name);  
  39.     }  
  40.       
  41.     //實例化靜態內部對象CREATOR實現接口Parcelable.Creator     
  42.     public static final Parcelable.Creator<Contacts> CREATOR = new Parcelable.Creator<Contacts>() {    
  43. //將Parcel對象反序列化爲Contacts
  44.         public Contacts createFromParcel(Parcel in) {     
  45.             return new Contacts(in);     
  46.         }     
  47.     
  48.         public Contacts[] newArray(int size) {     
  49.             return new Contacts[size];     
  50.         }     
  51.     };     
  52.       
  53.     //關鍵的事  
  54.     private Contacts(Parcel in) {     
  55.         id = in.readInt();    
  56.         name = in.readString();  
  57.     }  
  58. }  
Java代碼 
  1. 傳遞參數  
  2.          Contacts contact = new Contacts("0001""aliusa");  
  3.         Bundle bundle = new Bundle();     
  4.         bundle.putParcelable(Contacts.PARCELABLE_KEY , contact);  
  5.         intent.putExtra(parcelableKey, contact);   
Java代碼 
  1. 讀取參數  
  2.   
  3. final Contacts contact = (Contacts) getIntent().getExtras().getParcelable(Contacts.PARCELABLE_KEY);  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章