Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Activity 間資料傳遞:Bundle 與 SharedPreferences 的用法比較

編輯:Android 開發教學

一、兩者的差異

對初學者來說,Android 不同 Activity 之間的資料傳遞常是個難題,最常見的兩種解法是 Bundle 與 SharedPreferences。簡單講:SharedPreferences 適合存放輕量資料,落地成 XML 檔,可以長期保存;Bundle 則能承載多種類型的資料,但不具持久性,Activity 一關就沒了。

二、Bundle

發送方 A:

Bundle bundle = new Bundle();
// 放入要傳遞的內容
bundle.putString("string名", "傳輸的string");
Intent intent = new Intent(A.this, B.class);
intent.putExtras(bundle);

接收方 B:

Bundle b = getIntent().getExtras();
// 取出 Bundle 中的內容
String info = b.getString("string名");

注意:兩邊使用的 key(這裡的「string名」)必須完全一致,拼錯就會拿到 null。另外 Bundle 可以透過 putExtra 的帶量版本直接寫進 Intent,效果相同。

三、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變量名", "默認值");

讀取時的第二個參數是預設值,當 key 不存在時就會回傳它,因此一定要填,避免拿到 null 造成後續崩潰。commit() 是同步寫入,apply() 則是非同步,在需要立即生效的場景用 commit 比較保險。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved