Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

SharedPreferences 實作(3):onStop 存、onCreate 讀

編輯:進階開發

把保存與還原分別放進生命週期裡最合適的位置,資料就不會因為畫面被回收而消失。

還原放在 onCreate,讀出每個鍵並填回元件:

etName.setText(preferences.getString("name", ""));
etAge.setText(preferences.getString("age", ""));
sex.check(preferences.getInt("sex", -1));

保存放在 onStop,先取得 SharedPreferences 與 Editor,再把畫面上的值寫回去:

@Override
protected void onStop() {
    // 取得 SharedPreferences 物件
    SharedPreferences myPreferences =
            getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
    // 取得 Editor
    SharedPreferences.Editor editor = myPreferences.edit();
    // 把元件的值存起來
    editor.putString("name", etName.getText().toString());
    editor.putInt("age", ...);
    editor.commit();
}

三個細節值得注意。第一,getString 的第二個參數是預設值,第一次安裝、檔案還不存在時就靠它避免 crash。第二,第三個參數必須用 Activity.MODE_PRIVATE,否則資料會被其他應用讀到。第三,一定要呼叫 commit(),只 put 不 commit 等於什麼都沒存。

為什麼選 onStop 而不是 onPause?因為 onStop 的時機更接近「使用者真的離開了」,此時寫檔的代價較不影響操作流暢度;但要注意系統在極端情況下可能不呼叫 onStop,所以關鍵資料仍建議提早保存。

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