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

SharedPreferences 全面解析:輕量數據持久化的正確用法

編輯:關於 Android 開發

它適合幹什麼

SharedPreferences 是 Android 提供的一種輕量級數據存儲方式,本質上是基於 XML 文件來保存 key-value 鍵值對。它最適合用來存放一些簡單的配置信息,比如密碼、窗口狀態、軟件基本設置、壁紙路徑等等。

有一個容易踩的坑必須記住:SharedPreferences 對象本身只能讀取數據,不支持寫入和修改。所有的存儲與修改操作都要通過 Editor 對象來完成。

完整使用流程

第一步:獲取 SharedPreferences 對象

有兩種方式:

(1)context.getSharedPreferences(String name, int mode)——返回的對象可以被同一應用下的其他組件共享。name 是文件名,mode 是操作模式,共四種:

  • Context.MODE_PRIVATE:默認模式,文件為私有數據,只能被本應用訪問,寫入時會覆蓋原文件內容。
  • Context.MODE_APPEND:若文件已存在則追加內容,否則新建文件。
  • MODE_WORLD_READABLE:文件可被其他應用讀取。
  • MODE_WORLD_WRITEABLE:文件可被其他應用寫入。

需要提醒的是,後兩種「世界可讀/可寫」模式在較新版本的 Android 中已被廢棄,出於數據安全考慮不應再使用。

SharedPreferences pre = getSharedPreferences("myinfo", MODE_PRIVATE);

(2)activity.getPreferences(int mode)——這種方式得到的配置文件僅能被當前 Activity 使用,其他組件拿不到。

第二步:獲取 Editor 對象

SharedPreferences pre = getSharedPreferences("myinfo", MODE_PRIVATE);
Editor edit = pre.edit();

第三步:寫入數據

通過 Editor 的 putXxx() 系列方法保存鍵值對,Xxx 對應不同的數據類型:

edit.putString("name", "zhangsan");
edit.putString("age", "30");

寫完千萬別忘了調用 commit() 提交,否則數據不會真正落盤:

edit.commit();

第四步:讀取數據

用 getXxx() 方法取值,第二個參數是默認值——當 key 不存在時返回它,這個參數永遠要給,能有效避免空值帶來的困擾。

SharedPreferences pre = getSharedPreferences("myinfo", MODE_PRIVATE);
String name = pre.getString("name", "");
String age = pre.getString("age", "");

第五步:刪除數據

edit.remove("name");
edit.remove("age");
edit.commit();

實戰示例:記住賬號密碼

下面這個例子實現了「記住賬號」的功能:勾選複選框後登錄,賬號密碼被保存;下次進入頁面自動回填;點擊「忘記」則清空已保存的信息。

運行效果:

MainActivity.java:

package com.example.sharedpreferences;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    private EditText et_name;
    private EditText et_passward;
    private CheckBox ckb_save;
    private SharedPreferences pre;
    private Editor edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_name = (EditText) findViewById(R.id.et_name);
        et_passward = (EditText) findViewById(R.id.et_passward);
        ckb_save = (CheckBox) findViewById(R.id.checkBox1);
        pre = getSharedPreferences("myinfo", MODE_PRIVATE);
        edit = pre.edit();
        // 進頁面先嘗試回填
        String name = pre.getString("name", "");
        String passward = pre.getString("passward", "");
        if (!name.equals("") && !passward.equals("")) {
            et_name.setText(name);
            et_passward.setText(passward);
        }
    }

    public void btnLogin(View v) {
        switch (v.getId()) {
            case R.id.btn_login: {
                String name = et_name.getText().toString();
                String passward = et_passward.getText().toString();
                if (name.equals("") || passward.equals("")) {
                    Toast.makeText(MainActivity.this, "用戶名或者密碼為空,請重新輸入", Toast.LENGTH_SHORT).show();
                    et_name.setText(null);
                    et_passward.setText(null);
                } else if (ckb_save.isChecked()) {
                    edit.putString("name", name);
                    edit.putString("passward", passward);
                    edit.commit();
                    Toast.makeText(MainActivity.this, "保存用戶成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "未勾選保存,保存失敗", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case R.id.btn_cancel: {
                edit.remove("name");
                edit.remove("passward");
                edit.commit();
                Toast.makeText(MainActivity.this, "已成功忘記", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }
}

布局文件 activity_main.xml:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:gravity="center"
        android:text="帳 號:"
        android:textSize="20sp" />

    <EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/tv_name"
        android:singleLine="true" />

    <TextView
        android:id="@+id/tv_passward"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_name"
        android:layout_margin="5dp"
        android:text="密 碼:"
        android:textSize="20sp" />

    <EditText
        android:id="@+id/et_passward"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_name"
        android:layout_toRightOf="@id/tv_passward"
        android:singleLine="true" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tv_passward"
        android:checked="false"
        android:text="記住帳號" />

    <Button
        android:id="@+id/btn_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tv_passward"
        android:layout_below="@+id/checkBox1"
        android:onClick="btnLogin"
        android:text="保存" />

    <Button
        android:id="@+id/btn_cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/btn_login"
        android:layout_alignBottom="@+id/btn_login"
        android:layout_toRightOf="@+id/et_passward"
        android:onClick="btnLogin"
        android:text="忘記" />
</RelativeLayout>

實踐小結

SharedPreferences 適合存放小而簡單的鍵值配置,但它的能力邊界也很清楚:不支持條件查詢、不適合存放大數據、多進程訪問存在一致性風險。如果你的需求超出這些邊界,就該考慮數據庫或其他存儲方案了。

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