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

Android SharedPreferences 入門:保存與讀取應用程式設定

編輯:Android 開發實例

在 Android 開發中,常需要保存少量輕量設定,例如使用者名稱、是否首次啟動、介面偏好等。SharedPreferences 以鍵值對形式將資料保存為 XML 檔案,適合存放簡單、非同步大量資料的內容。

SharedPreferences 的核心概念

SharedPreferences 提供一種簡單的持久化方式。開發者可透過 Context.getSharedPreferences() 取得指定名稱的偏好設定物件,再利用 Editor 修改內容。所有變更都應透過 Editor 完成,並呼叫 commit() 或 apply() 提交。

建立與寫入資料

以下範例展示如何建立 SharedPreferencesHelper,並以字串鍵值寫入資料。

SharedPreferences sp = context.getSharedPreferences(name, 0);
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value);
editor.commit();

若需要保存多個欄位,可以重複呼叫 putString(),最後一次提交即可。例如可保存 name 與 mobile 兩個欄位。

讀取資料

讀取時使用相同鍵值即可。若指定鍵不存在,getString() 的第二個參數可作為預設值。

String value = sp.getString(key, null);

封裝成 Helper 類別

由於多數應用都會需要類似功能,可將建立、寫入、讀取流程封裝為 SharedPreferencesHelper,讓後續呼叫更簡潔。

public class SharedPreferencesHelper {
    private final SharedPreferences sp;
    private final SharedPreferences.Editor editor;

    public SharedPreferencesHelper(Context context, String name) {
        sp = context.getSharedPreferences(name, 0);
        editor = sp.edit();
    }

    public void putValue(String key, String value) {
        editor.putString(key, value);
        editor.commit();
    }

    public String getValue(String key) {
        return sp.getString(key, null);
    }
}

使用範例

在 Activity 中可建立 helper 物件,寫入資料後再讀回,並顯示於 TextView。

SharedPreferencesHelper sp = new SharedPreferencesHelper(this, "contacts");
sp.putValue("name", "Gryphone");
sp.putValue("mobile", "123456789");

String name = sp.getValue("name");
String mobile = sp.getValue("mobile");

檔案存放位置

SharedPreferences 會在應用程式私有目錄中建立 XML 檔案。若 package name 為 com.android.SharedPreferences,且偏好設定名稱為 contacts,檔案通常位於:

/data/data/com.android.SharedPreferences/shared_prefs/contacts.xml

檔案內容會以 map 結構保存鍵值對。開發時可透過 adb 或除錯工具查看,但正式環境不建議依賴直接修改 XML 檔案。

小結

SharedPreferences 適合保存少量、結構簡單的設定資料。透過 Editor 提交變更,並以鍵值方式讀取,即可快速完成設定保存功能。

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