編輯:關於 Android 開發
SharedPreferences 是 Android 上用來存放輕量級配置數據的標準方案。它上手極簡單,但正因為簡單,很多細節反而容易被忽略——尤其是 Editor 的使用方式和數據提交時機,這兩個地方是新手最常翻車的位置。
SharedPreferences 內部以 Map 的形式組織數據,採用鍵值對的方式讀寫,最終以 XML 文件的形式持久化到本地的 /data/data/<package name>/shared_prefs 目錄下。它適合存放各類配置項、用戶偏好、標記位這類數據量小、結構簡單的信息。
使用簡單。API 只有寥寥幾個方法,學習成本幾乎為零。
類型受限。只支持 Java 基本數據類型和 String,自定義對象需要先序列化或拆成多個字段。
應用內共享。它本質上是單例對象,在同一個應用進程內各處讀到的都是同一份數據,但默認無法跨應用訪問。
文件名決定數據隔離。創建時傳入不同的文件名,就會生成不同的 XML 文件,數據互不相通;傳入相同文件名則會得到多個引用指向同一份數據。
操作必須提交才生效。這是最高頻的錯誤來源。調用了 putString 卻沒調 commit() 或 apply(),程序不會報錯,但數據就是不會被保存。
安全問題不容小覷。三種創建模式裡應始終使用 MODE_PRIVATE。另外兩種允許其他應用讀寫,等於把數據暴露在風險之下。即便用了 MODE_PRIVATE,一旦設備被 root,文件仍然可能被讀取。因此存儲用戶名、密碼這類敏感信息時,絕對不要明文保存,必須先加密。
第一步:獲取 SharedPreferences 對象
SharedPreferences sharedPreferences = getSharedPreferences("info", MODE_PRIVATE);
第一個參數是文件名,注意不要帶 .xml 後綴,系統會自動補上。第二個參數是創建模式,共有三個可選值:
MODE_PRIVATE:僅本應用可讀寫,默認且推薦。
MODE_WORLD_READABLE:其他應用可讀(已廢棄)。
MODE_WORLD_WRITEABLE:其他應用可讀寫(已廢棄)。
第二步:獲取 Editor
Editor editor = sharedPreferences.edit();
第三步:增刪改查
// 添加或更新(同 key 會覆蓋) editor.putString(key, value); // 刪除指定 key editor.remove(key); // 清空全部 editor.clear(); // 查詢,第二個參數是默認值 String result = sharedPreferences.getString(key, defaultValue);
查詢是唯一直接通過 sharedPreferences 完成的操作,其餘寫操作都要走 editor,最後統一提交。
看下面這段代碼,很多人第一眼看不出問題:
sharedPreferences.edit().putString(key1, value1); sharedPreferences.edit().putString(key2, value2); sharedPreferences.edit().putString(key3, value3); sharedPreferences.edit().commit();
執行之後一條數據都存不進去。原因在於:sp.edit() 每次調用都會返回一個全新的 Editor 實例。Editor 的實現類內部維護着一個臨時的緩存 Map,commit() 時先把緩存 Map 寫入內存中的主 Map,再整體落盤。上面這三行分別由三個不同的 Editor 承接,前兩個的緩存裡確實有數據,但它們從未 commit;而最後 commit 的那個 Editor,緩存是空的。
正確寫法只有一個 editor 貫穿始終:
Editor editor = sharedPreferences.edit(); editor.putString(key1, value1); editor.putString(key2, value2); editor.putString(key3, value3); editor.commit();
記住這條規則就不會出錯:所有寫操作必須由同一個 Editor 完成,並由這個 Editor 提交。
另外,commit() 是同步操作,會直接寫入磁盤,在主線程頻繁調用可能造成卡頓;apply() 是異步的,先更新內存再放到後台落盤,日常場景更推薦使用。代價是它不返回布爾結果,如果需要確認是否寫入成功,只能用 commit。

示例界面按從上到下的順序包含:保存用的兩個輸入框與按鈕、查詢用的輸入框與按鈕及結果展示、刪除用的輸入框與按鈕,最後是清空按鈕。
Activity 主要代碼:
public class MainActivity extends Activity {
private EditText et_key;
private EditText et_value;
private EditText et_query;
private EditText et_delete;
private TextView tv_query;
private SharedPreferences sharedPreferences;
private Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("info2", MODE_PRIVATE);
editor = sharedPreferences.edit();
et_key = (EditText) findViewById(R.id.et_key);
et_value = (EditText) findViewById(R.id.et_value);
et_query = (EditText) findViewById(R.id.et_query);
et_delete = (EditText) findViewById(R.id.et_delete);
tv_query = (TextView) findViewById(R.id.tv_content);
}
public void insert(View v) {
String key = et_key.getText().toString().trim();
String value = et_value.getText().toString().trim();
editor.putString(key, value);
editor.commit(); // 一定要提交
}
public void query(View v) {
String queryText = et_query.getText().toString().trim();
String result = sharedPreferences.getString(queryText, null);
tv_query.setText(result == null ? "您查詢的數據不存在" : result);
}
public void delete(View v) {
editor.remove(et_delete.getText().toString().trim());
editor.commit(); // 一定要提交
}
public void clear(View v) {
editor.clear();
editor.commit(); // 一定要提交
}
}
布局文件:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<EditText
android:id="@+id/et_key"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入要保存的鍵" />
<EditText
android:id="@+id/et_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入對應的值" />
<Button
android:id="@+id/bt_insert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:onClick="insert"
android:text="保存" />
<EditText
android:id="@+id/et_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入要查詢的鍵" />
<Button
android:id="@+id/bt_query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:onClick="query"
android:text="查詢" />
<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp" />
<EditText
android:id="@+id/et_delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入要刪除的鍵" />
<Button
android:id="@+id/bt_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:onClick="delete"
android:text="刪除" />
<Button
android:id="@+id/bt_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:onClick="clear"
android:text="清空" />
</LinearLayout>
驗證時可以發現:clear() 只會清空當前對應的那個 XML 文件,不影響用其他文件名創建的 SharedPreferences 數據。
高效分析 Android 記憶體:MAT 工具完整解析
MAT(Memory Analyzer Tool)是知名的 Android 記憶體分析工具。雖然 LeakCanary 使用更為便捷,但 MAT 能清楚呈現整體記憶體使用
Android 透過 PHP 中介連接 MySQL:以 JSON 交換資料的完整流程
Android 透過 PHP 中介連接 MySQL:以 JSON 交換資料的完整流程 管理 MySQL 資料庫最簡單便利的方式,是撰寫 PHP 腳本作為中介。PHP 腳本
Android 手機衛士:導引頁 1 的布局實作
導引頁 1 布局 第一個導引頁用於介紹手機防盜功能,包含標題、功能列表、頁碼指示點、插圖與下一步按鈕。 布局可採用垂直 LinearLayout:上方標題,中間功能說明
《Android 源碼設計模式解析與實戰》筆記(二十一):裝飾模式
第二十一章、裝飾模式 裝飾模式也稱為包裝模式,屬於結構型設計模式。它提供了一條替代繼承的方案,用來動態地為物件擴充職責。 一、定義 動態地為一個物件添加額外的職責。