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

Android 使用 SharedPreferences 保存鍵值對資料

編輯:關於 Android 程式設計

使用共享首選項

如果你有想要保存的、相對少量的鍵值集合,就應該使用 SharedPreferences API。SharedPreferences 物件指向一個包含鍵值對的檔案,並提供讀寫這些檔案的簡單方法。每個 SharedPreferences 檔案由框架進行管理,可以是專用或共享的。

注意:SharedPreferences API 僅用於讀寫鍵值對,不要將它與 Preference API 混淆——後者幫助你為應用建立設定介面(儘管它們在實現上使用 SharedPreferences 來保存應用設定)。

取得共享首選項的 handle

可以透過以下兩種方法之一建立新的共享首選項檔案或存取現有的檔案:

1. getSharedPreferences()——如果你需要多個共享首選項檔案(用第一個參數指定的名稱來識別),請使用此方法,可從應用中的任何 Context 呼叫。

2. getPreferences()——如果你只需使用 Activity 的一個共享首選項,請從 Activity 中使用此方法,它會取得屬於該 Activity 的預設共享首選項檔案,無需提供名稱。

例如

以下程式碼在 Fragment 內執行,存取透過資源字串 R.string.preference_file_key 識別的共享首選項檔案,並以專用模式打開,僅允許本應用存取:

Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
        getString(R.string.preference_file_key), Context.MODE_PRIVATE);

命名共享首選項檔案時,應使用對應用而言唯一可識別的名稱,例如 "com.example.myapp.PREFERENCE_FILE_KEY"。或者,如果只需 Activity 的一個共享首選項檔案,可用 getPreferences() 方法:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

注意:如果建立帶 MODE_WORLD_READABLE 或 MODE_WORLD_WRITEABLE 的共享首選項檔案,那麼知道檔案標識符的任何其他應用都能存取你的資料。

寫入共享首選項

1. 要寫入共享首選項檔案,先透過對 SharedPreferences 呼叫 edit() 來建立一個 SharedPreferences.Editor。

2. 傳入你想用 putInt() 和 putString() 等方法寫入的鍵和值,然後呼叫 commit() 保存所做的更改。例如:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

從共享首選項讀取資訊

要從共享首選項檔案中取值,請呼叫 getInt() 和 getString() 等方法,為你想要的值提供鍵,並提供在鍵不存在時要返回的預設值。例如:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved