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

Android 資料儲存:SharedPreferences 使用全面整理

編輯:關於 Android 程式設計

SharedPreferences 提供開發者保存與讀取基本資料類型鍵值對的能力,主要用於 boolean、float、int、long 與 String 等基本類型。它的資料以 XML 檔案形式存在本地,位置在 /data/data/包名/shared_prefs 目錄下。應用結束後資料仍會保留,只要程式沒有被解除安裝,下次啟動時還能存取上次保存的資料。

SharedPreferences 物件並非用 new 建立,而是透過 getSharedPreferences(String name, int mode) 方法取得。這個方法是 Context 提供的,第一個參數是共享檔案的名稱,第二個參數是資料保存的模式。對於以同一檔名取得的多個 SharedPreferences 參照,它們指向的是同一個物件。

檔案資料保存的模式

  • MODE_PRIVATE:最常用,其他模式則較少使用。
  • MODE_APPEND:在既有設定檔後追加。
  • MODE_WORLD_READABLE:允許其他應用讀取(已不建議)。
  • MODE_WORLD_WRITEABLE:允許其他應用寫入(已不建議)。

從 SharedPreferences 物件取值時,主要用該類別定義的 getXxx() 方法,例如:

String name = share.getString("name", "");

使用步驟

  1. 呼叫 SharedPreferences 物件的 edit() 方法,取得 SharedPreferences.Editor 參照。
  2. 呼叫 putBoolean()、putString() 等方法寫入值。
  3. 使用 commit() 方法提交新值。

典型應用場景

  • 判斷使用者是否第一次登入。
  • 保存使用者的相關預設設定開關,例如預設音效、是否開啟訊息推播等。
  • 實現使用者自動登入等功能。

實作範例:可自動登入的登入頁

程式功能:

  1. 驗證使用者名稱與密碼是否正確(此處資訊為模擬)。
  2. 若勾選「記住密碼」,登入成功後退出程式,兩個輸入框會顯示上次登入成功的使用者名稱與密碼。
  3. 若勾選「自動登入」,頁面啟動時會驗證帳密並自動登入。
  4. 若沒有勾選「記住密碼」,先前保存的帳密也會被清除,下次登入時輸入框不再有任何資訊。

(一)版面配置檔

<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/main_et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleline="true"
        android:hint="請輸入用戶名" />

    <EditText
        android:id="@+id/main_et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleline="true"
        android:hint="密碼" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <CheckBox
            android:id="@+id/main_cb_remember"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="記住密碼" />

        <CheckBox
            android:id="@+id/main_cb_auto"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="自動登入" />
    </LinearLayout>

    <TextView
        android:id="@+id/main_tv_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:background="#336699"
        android:gravity="center"
        android:padding="10dp"
        android:text="登入"
        android:textColor="@android:color/white" />
</LinearLayout>

(二)SharedPreferences 工具類

為了讓資料存取更簡潔,我們封裝一個 SPHelper 工具類,透過 ContentValue 一次處理多筆資料:

package com.lwz.sharepreferences;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * SharePreference 工具類,用它可以更方便地進行簡單資料儲存。
 * 1. 透過建構方法傳入上下文與檔名
 * 2. 透過 putValues 傳入一或多個自訂的 ContentValue 物件進行儲存
 * 3. 透過 get 方法讀取資料
 * 4. 透過 clear 方法清除這個檔案的所有資料
 */
public class SPHelper {

    SharedPreferences sharedPreferences;

    // 透過建構方法傳入上下文與檔名
    SPHelper(Context context, String fileName) {
        // 使用 getSharedPreferences 而非 new 建立
        sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
    }

    // 用來承載 key 與 value 的內部類
    static class ContentValue {
        String key;
        Object value;
        ContentValue(String key, Object value) {
            this.key = key;
            this.value = value;
        }
    }

    // 一次可傳入多個 ContentValue
    public void putValues(ContentValue... contentValues) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        for (ContentValue contentValue : contentValues) {
            if (contentValue.value instanceof String) {
                editor.putString(contentValue.key, contentValue.value.toString()).commit();
            }
            if (contentValue.value instanceof Integer) {
                editor.putInt(contentValue.key, Integer.parseInt(contentValue.value.toString())).commit();
            }
            if (contentValue.value instanceof Long) {
                editor.putLong(contentValue.key, Long.parseLong(contentValue.value.toString())).commit();
            }
            if (contentValue.value instanceof Boolean) {
                editor.putBoolean(contentValue.key, Boolean.parseBoolean(contentValue.value.toString())).commit();
            }
        }
    }

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

    public boolean getBoolean(String key) {
        return sharedPreferences.getBoolean(key, false);
    }

    public int getInt(String key) {
        return sharedPreferences.getInt(key, -1);
    }

    public long getLong(String key) {
        return sharedPreferences.getLong(key, -1);
    }

    // 清除目前檔案的所有資料
    public void clear() {
        sharedPreferences.edit().clear().commit();
    }
}

(三)主要程式碼

package com.lwz.sharepreferences;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
        implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    EditText et_username;
    EditText et_password;
    CheckBox cb_remenber;
    CheckBox cb_auto;
    TextView tv_login;
    boolean isAutoLogin = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        idFirstlogin();   // 判斷是否第一次登入
        initView();       // 初始化頁面資料
    }

    private void initView() {
        et_username = (EditText) findViewById(R.id.main_et_username);
        et_password = (EditText) findViewById(R.id.main_et_password);
        cb_remenber = (CheckBox) findViewById(R.id.main_cb_remember);
        cb_auto = (CheckBox) findViewById(R.id.main_cb_auto);
        tv_login = (TextView) findViewById(R.id.main_tv_login);

        tv_login.setOnClickListener(this);
        cb_remenber.setOnCheckedChangeListener(this);
        cb_auto.setOnCheckedChangeListener(this);

        SPHelper helper = new SPHelper(this, "login");
        isAutoLogin = helper.getBoolean("isAutoLogin");
        String name = helper.getString("username");
        String pass = helper.getString("password");

        if (!TextUtils.isEmpty(name)) {
            et_username.setText(name);
            et_password.setText(pass);
            cb_remenber.setChecked(true);
        }
        if (isAutoLogin) {
            Toast.makeText(this, name + " 自動登入中……", Toast.LENGTH_LONG).show();
            cb_auto.setChecked(true);
        }
    }

    private void idFirstlogin() {
        SharedPreferences sp = getSharedPreferences("set", MODE_PRIVATE);
        boolean isfirst = sp.getBoolean("isfirst", true);
        if (isfirst) {
            SharedPreferences.Editor et = sp.edit();
            et.putBoolean("isfirst", false);
            et.commit();
            Toast.makeText(this, "第一次登入", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        String[] name = {"李文志", "李世民", "李嘉誠", "lili"};
        String username = et_username.getText().toString();
        String password = et_password.getText().toString();

        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "用戶名不能為空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "密碼不能為空", Toast.LENGTH_SHORT).show();
            return;
        }

        boolean isrightname = false;
        for (int i = 0; i < name.length; i++) {
            if (username.equals(name[i]) && password.equals("123456")) {
                Toast.makeText(this, "恭喜你登入成功", Toast.LENGTH_LONG).show();
                isrightname = true;

                SPHelper helper = new SPHelper(this, "login");
                if (cb_remenber.isChecked()) {
                    helper.putValues(new SPHelper.ContentValue("username", username));
                    helper.putValues(new SPHelper.ContentValue("password", password));
                } else {
                    helper.clear();
                }
                if (cb_auto.isChecked()) {
                    helper.putValues(new SPHelper.ContentValue("isAutoLogin", true));
                } else {
                    helper.putValues(new SPHelper.ContentValue("isAutoLogin", false));
                }
            }
        }
        if (!isrightname) {
            Toast.makeText(this, "用戶名或密碼不正確!", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView == cb_remenber) {
            if (!isChecked) {
                cb_auto.setChecked(false); // 取消記住密碼時,自動登入也取消
            }
        }
        if (buttonView == cb_auto) {
            if (isChecked) {
                cb_remenber.setChecked(true); // 勾選自動登入時,記住密碼也自動勾選
            }
        }
    }
}

小結

SharedPreferences 適合保存少量、簡單的鍵值型資料,用它來記錄登入狀態、使用者偏好等相當合適。這個範例尚未實作多帳號登入(如 QQ 那樣的帳號切換),若想做到那種效果,可以考慮用 ExpandableListView 的下拉清單來顯示曾登入過的帳號。

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