android技巧:Activity間資料傳遞之Bundle和SharedPreferences

來源:互聯網
上載者:User

1.介紹

對於初學者android不同activity間的資料轉送一直是一個難題,主要的解決方案主要有兩種一種是用Bundle傳輸資料,一種是用SharedPreferences。兩者的區別,一般來講SharedPreferences用來儲存輕型資料,儲存在xml裡,可以持久儲存。反觀Bundle可以傳輸很多中資料,但是不持久。

2.具體實現方法  Bundle

在發送方class A

Bundle bundle = new Bundle();         //儲存輸入的資訊     bundle.putString("string名", "傳輸的string");     Intent intent=new Intent(A.this,B.class);    intent.putExtras(bundle);

在接收方class B

Bundle b=getIntent().getExtras();    //擷取Bundle的資訊    String info=b.getString("string名");

注意:string名要一樣

SharedPreferences

SharedPreferences 用法很簡單,如果你想要編輯SharedPreferences中的內容就需要用到editor對象。

在發出方A中

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());                           Editor editor = sp.edit();                          editor.putString("string變數名","發出的string內容");                          editor.commit();

接收方B

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(B.this);              string grade = sp.getString("string變數名",“預設值”);

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.