2014-11-03 73 views
0

我現在開始使用android,並且想知道哪個是將活動中的對象傳遞給另一個活動的最佳方式。Android將對象傳遞給另一個活動的最佳方式

到目前爲止,我已經

  • Seriliazable
  • Parcelable
  • 和總是有其他的選擇,只是通過數據庫再次通過ID和創建對象

哪一個我應該用戶嗎? 謝謝

回答

0

當您創建意圖對象時,您可以利用以下兩種方法 在兩個活動之間傳遞對象。

putParceble

putSerializable

你可以用這個做什麼,是有你的類實現無論是ParcelableSerializable

然後,您可以通過活動傳遞自定義班級。我發現這非常有用。

這裏是一小段代碼,我使用

CustomListing currentListing = new CustomListing(); 
Intent i = new Intent(); 
Bundle b = new Bundle(); 
b.putParcelable(Constants.CUSTOM_LISTING, currentListing); 
i.putExtras(b); 
i.setClass(this, SearchDetailsActivity.class); 
startActivity(i); 

和新開工活動代碼會是這樣的......

Bundle b = this.getIntent().getExtras(); 
if(b!=null) 
    mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING); 

你也可以讓你自定義的類實現Serializable接口,然後可以使用putExtra(Serializable..)方法的Intent#putExtra()方法的變體傳遞意圖額外的對象實例。

僞代碼:

//to pass : 
    intent.putExtra("MyClass", obj); 

// to retrieve object in second Activity 
getIntent().getSerializableExtra("MyClass"); 
相關問題