Android中Intent傳遞對象的兩種方法(Serializable,Parcelable)

 

Activity之間通過Intent傳遞值,支持基本數據類型和String對象及它們的數組對象byte、byte[]、char、char[]、boolean、boolean[]、short、short[]、int、int[]、long、long[]、float、float[]、double、double[]、String、String[],還有實現Serializable、Parcelable接口的類對象。

對於,Serializable 還比較熟悉,但是,對於 Parcelable 這個東東,它是android 的一個新的序列化方式。(下面會詳細的講解Parcelable )

下面,將給出用Serializable 和 Parcelable 這兩種方式來傳遞對象的示例代碼:

      

        *下面的是傳遞的對象 -----------

/***
 * 要傳遞的對象Serializable 
 * @author Administrator
 *
 */
public class PassObject_Serializable implements Serializable{
 
 public PassObject_Serializable() {
  super();
 }

 public PassObject_Serializable(int id, String name, double price) {
  super();
  this.id = id;
  this.name = name;
  this.price = price;
 }

 private int id;
 
 private String name ;
 
 private double price;

 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 double getPrice() {
  return price;
 }

 public void setPrice(double price) {
  this.price = price;
 }
}

 

/***
 * 要傳遞的對象Parcelable
 * @author Administrator
 *
 */
public class PassObject_Parcelable implements Parcelable{
 
 @Override
 public int describeContents() {
  return 0;
 }

 @Override
 public void writeToParcel(Parcel dest, int flags) {
  dest.writeInt(this.id);
  dest.writeString(this.name);
  dest.writeDouble(this.price);
 }
 public static final Parcelable.Creator<PassObject_Parcelable> CREATOR = new Creator<PassObject_Parcelable>() {
  @Override
  public PassObject_Parcelable[] newArray(int size) {
   
   return new PassObject_Parcelable[size];
  }
  @Override
  public PassObject_Parcelable createFromParcel(Parcel source) {
   PassObject_Parcelable temp = new PassObject_Parcelable();
   
   temp.id = source.readInt();
   temp.name = source.readString();
   temp.price = source.readDouble();
   return temp;
  }
 };
 
 public PassObject_Parcelable() {
  super();
  // TODO Auto-generated constructor stub
 }

 public PassObject_Parcelable(int id, String name, double price) {
  super();
  this.id = id;
  this.name = name;
  this.price = price;
 }
 private int id;
 
 private String name ;
 
 private double price;

 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 double getPrice() {
  return price;
 }

 public void setPrice(double price) {
  this.price = price;
 }
 
}

 

* 以上是兩個要傳遞的對象,一個實現 Serializable ,一個實現 Parcelable

* 注意 ,紅色的部分

*下面的是傳遞對象的activity -----------

/**
 *  傳遞對象的頁面A
 * @author Administrator
 *
 */
public class ActivityAextends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_a);
       
        Button btnSerlizableBtn = (Button)ActivityA.this.findViewById(R.id.go_btn1);
        Button btnParcelableBtn = (Button)ActivityA.this.findViewById(R.id.go_btn2);
        btnSerlizableBtn.setOnClickListener(new mybtnClick(true, new PassObject_Serializable(1,"牛奶", 50.0)));
        btnParcelableBtn.setOnClickListener(new mybtnClick(false, new PassObject_Parcelable(1,"牛奶", 50.0)));
       
    }
   
    /**
     * 單擊類
     */
    private class mybtnClick implements OnClickListener {
     private boolean  type = false;  //true 爲 Serializable false 爲Parcelable
     private Object passObj =null;   //要傳遞的對象
  public mybtnClick(boolean type, Object passObj) {
   super();
   this.type = type;
   this.passObj = passObj;
  }  @Override
  public void onClick(View v) {
   Bundle mybundle = new Bundle();
   mybundle.putBoolean("type",type);
   if(type){
    mybundle.putSerializable("obj",(Serializable) passObj ); 
   }else{
    mybundle.putParcelable("obj",(Parcelable) passObj);
   }
   Intent myintent = new Intent();
   myintent.putExtras(mybundle);
   myintent.setClass(ActivityA.this, ActivityB.class);
   startActivity(myintent);
  }
    }
}

 

 

/**
 * 接受對象的頁面B
 * @author Administrator
 *
 */
public class ActivityB extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.page_b);
  
  TextView txt = (TextView)ActivityB.this.findViewById(R.id.txt1);
  Bundle myBundle = this.getIntent().getExtras();
  if(myBundle!=null){
   
   Object obj = null;
   
   boolean type = myBundle.getBoolean("type");
   if(type){
    obj =(PassObject_Serializable) myBundle.getSerializable("obj");
    
   }else{
    obj =(PassObject_Parcelable) myBundle.getParcelable("obj");
   }
   StringBuffer str = new StringBuffer();
   str.append("類型:"+(type?"Serializable":"Parcelable"));
   str.append("\n");
   String id,name,price;
   if(type){
    id = ((PassObject_Serializable)obj).getId()+"";
    name = ((PassObject_Serializable)obj).getName()+"";
    price = ((PassObject_Serializable)obj).getPrice()+"";
   }else{
    id = ((PassObject_Parcelable)obj).getId()+"";
    name = ((PassObject_Parcelable)obj).getName()+"";
    price = ((PassObject_Parcelable)obj).getPrice()+"";
   }
   str.append("id:"+id+"\n");
   str.append("name:"+name+"\n");
   str.append("price:"+price+"\n");
   txt.setText(str.toString());
  }
 }
}

 

* 以上就是,傳遞對象的兩種序列化方式,如果你還是不明白,歡迎下載demo程序,以下是鏈接:

http://download.csdn.net/detail/zjl5211314/3798905 

 

 

 

* 頭開始,提到了Parcelable ,是android的一種新的序列化方式,那現在就瞭解下她吧。 

android提供了一種新的類型:Parcel。本類被用作封裝數據的容器,封裝後的數據可以通過Intent或IPC傳遞。

除了基本類型以外,只有實現了Parcelable接口的類才能被放入Parcel中。

Parcelable實現要點:需要實現三個東西

1)writeToParcel 方法。該方法將類的數據寫入外部提供的Parcel中.聲明如下:

writeToParcel (Parcel dest, int flags) 具體參數含義見 javadoc

2)describeContents方法。沒搞懂有什麼用,反正直接返回0也可以

3)靜態的Parcelable.Creator接口,本接口有兩個方法:

createFromParcel(Parcel in) 實現從in中創建出類的實例的功能

newArray(int size) 創建一個類型爲T,長度爲size的數組,僅一句話(return new T[size])即可。估計本方法是供外部類反序列化本類數組使用。

 

*該段落,引自百度文檔。

通過使用 Parcelable ,

1. writeToParcel  方法 ,主要是將數據寫入 parcle 中;

2.Parcelable.Creator 類中的 createFromParcel(Parcel source) 方法,主要是,從 parcle  中讀取數據;

3. describeContents 方法,基本不用動,直接返回0 就可以;

4.Parcelable.Creator 類中的 newArray(int size)  方法,沒怎麼體會過。

5.總之,個人,感覺用這個Parcelable  序列化,是通過 parcle   來傳遞數據的。

(目前,感受就這些,以後可能會更瞭解她得其他特性,到時候,會繼續完善下 *_* )

 

 

 

 

 

 

發佈了35 篇原創文章 · 獲贊 21 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章