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

Android 實戰教學第十六課:用 SharedPreferences 記住帳號與密碼

編輯:關於 Android 程式設計

上一課把使用者名稱與密碼暫時放在記憶體裡,App 一關閉資料就跟著消失。這一課改用 SharedPreferences 把資料寫入檔案,下次開啟程式時就能讀回來並自動帶入。

先提醒一句:真實專案裡絕不會用明文保存密碼,正式環境會搭配加鹽雜湊、Token 或系統 Keystore。這裡單純提供一個思路,順便帶初學者熟悉幾個簡單的 API。

因為整體結構和前一課幾乎一樣,就不再逐行解釋,直接看程式碼。

一、版面配置

兩個輸入框分別對應用戶名與密碼,一個 CheckBox 控制「記住」,右側放登入按鈕:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin">

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

    <EditText
        android:id="@+id/et_pass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入密碼"
        android:inputType="textPassword" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <CheckBox
            android:id="@+id/cb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="記住用戶名和密碼" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:onClick="login"
            android:text="登錄" />
    </RelativeLayout>
</LinearLayout>

二、MainActivity

public class MainActivity extends Activity {

    private EditText et_name;
    private EditText et_pass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_name = (EditText) findViewById(R.id.et_name);
        et_pass = (EditText) findViewById(R.id.et_pass);

        readAccount();   // 開啟程式時回顯已保存的資料
    }

    private void readAccount() {
        SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
        // 讀取時不必判斷檔案是否存在,getXxx 的第二個參數就是預設值
        String name = sp.getString("name", "");
        String pass = sp.getString("pass", "");
        et_name.setText(name);
        et_pass.setText(pass);
    }

    public void login(View v) {
        String name = et_name.getText().toString();
        String pass = et_pass.getText().toString();
        CheckBox cb = (CheckBox) findViewById(R.id.cb);

        if (cb.isChecked()) {
            // 檔案位置:data/data/套件名/shared_prefs/info.xml
            SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
            SharedPreferences.Editor ed = sp.edit();
            // 以鍵值對方式存入
            ed.putString("name", name);
            ed.putString("pass", pass);
            ed.commit();   // 記得提交,apply() 亦可
        }

        Toast.makeText(this, "登錄成功", 0).show();
    }
}

三、執行結果

SharedPreferences 產生的檔案位置如下:

勾選「記住」並登入後:

把程式完全結束再重新進入,帳號與密碼依然會正確回顯,說明資料確實已經落地成檔案。

四、幾個要點

SharedPreferences 的本質是一個 XML 檔案,適合存放數量不多的小型設定,例如是否首次啟動、字型大小、上次使用的分頁。它並不適合存放大量資料或需要查詢條件的結構化資料,那種情境應該改用資料庫。另外 commit() 是同步寫入、會阻塞主執行緒,apply() 則是先更新記憶體再背景寫檔,日常開發建議優先用 apply()。

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