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

Activity 間數據傳遞:Bundle 與 SharedPreferences 對比

編輯:關於 Android 程式設計

對於 Android 初學者來說,不同 Activity 之間的數據傳遞一直是個難題。最常見的解決方案有兩種:用 Bundle 傳輸,或用 SharedPreferences 存儲。兩者的核心區別在於:SharedPreferences 適合存儲輕量數據、以 XML 形式持久保存;而 Bundle 能傳輸多種類型的數據,但不具持久性。

一、使用 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名");

注意:兩邊使用的 key("string名")必須保持一致。

二、使用 SharedPreferences

SharedPreferences 的用法也很簡單,若要編輯其中的內容,需要用到 Editor 對象。

發出方 A:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());

Editor editor = sp.edit();

editor.putInt("string變量名", "發出的string內容");

editor.commit();

接收方 B:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(B.this);

String grade = sp.getString("string變量名", "默認值");

總的來說,如果只是 Activity 之間臨時傳值,用 Bundle 更直接;如果需要跨會話持久保存,則首選 SharedPreferences。

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