Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách sử dụng SharedPreferences trong Android

Hướng dẫn này trình bày cách sử dụng SharedPreferences để lưu trữ dữ liệu cài đặt đơn giản (key-value) trong Android. Ví dụ minh họa chức năng "Ghi nhớ đăng nhập" (Remember me) - lưu tên đăng nhập, mật khẩu khi người dùng tích checkbox.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<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">

    <EditText
        android:id="@+id/etName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:layout_marginTop="75dp"
        android:hint="Nhập tên" />

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/etName"
        android:ems="10"
        android:layout_centerHorizontal="true"
        android:hint="Nhập mật khẩu"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Đăng nhập"
        android:layout_below="@id/etPassword"
        android:layout_alignStart="@id/etPassword"
        android:layout_marginTop="10dp" />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnLogin"
        android:layout_marginTop="10dp"
        android:text="Ghi nhớ thông tin đăng nhập"
        android:layout_alignStart="@id/btnLogin" />

</RelativeLayout>

Bước 3: Code MainActivity (src/MainActivity.java)

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    EditText name, password;
    Button button;
    CheckBox checkBox;
    String strName, strPassword, strCheckBox;

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

        name = findViewById(R.id.etName);
        password = findViewById(R.id.etPassword);
        button = findViewById(R.id.btnLogin);
        checkBox = findViewById(R.id.checkBox);

        // Lấy SharedPreferences mặc định
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = sharedPreferences.edit();

        // Khôi phục dữ liệu đã lưu (nếu có)
        checkSharedPreference();

        button.setOnClickListener(v -> {
            if (checkBox.isChecked()) {
                // Lưu trạng thái checkbox
                editor.putString(getString(R.string.checkBox), "True");
                // Lưu tên và mật khẩu
                strName = name.getText().toString();
                editor.putString(getString(R.string.name), strName);
                strPassword = password.getText().toString();
                editor.putString(getString(R.string.password), strPassword);
                editor.apply(); // apply() bất đồng bộ, tốt hơn commit()
            } else {
                // Xóa dữ liệu lưu
                editor.putString(getString(R.string.checkBox), "False");
                editor.putString(getString(R.string.name), "");
                editor.putString(getString(R.string.password), "");
                editor.apply();
            }
        });
    }

    private void checkSharedPreference() {
        strCheckBox = sharedPreferences.getString(getString(R.string.checkBox), "False");
        strName = sharedPreferences.getString(getString(R.string.name), "");
        strPassword = sharedPreferences.getString(getString(R.string.password), "");

        name.setText(strName);
        password.setText(strPassword);

        if (strCheckBox.equals("True")) {
            checkBox.setChecked(true);
        } else {
            checkBox.setChecked(false);
        }
    }
}
Lưu ý: Dùng editor.apply() thay vì editor.commit(). apply() ghi bất đồng bộ (không block UI thread), trong khi commit() ghi đồng bộ và trả về boolean.

Bước 4: Chuỗi ký tự (res/values/strings.xml)

<resources>
    <string name="app_name">Sample</string>
    <string name="checkBox">Sample.checkbox</string>
    <string name="name">Sample.name</string>
    <string name="password">Sample.password</string>
</resources>

Bước 5: Cấu hình AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhập tên/mật khẩu, tích "Ghi nhớ", nhấn Đăng nhập. Khởi động lại app - thông tin sẽ tự điền.

Cách sử dụng SharedPreferences trong Android

Kiến thức mở rộng

Các kiểu dữ liệu hỗ trợ

  • putString / getString
  • putInt / getInt
  • putBoolean / getBoolean
  • putFloat / getFloat
  • putLong / getLong
  • putStringSet / getStringSet (API 11+)

Hai loại SharedPreferences

Loại Cách lấy Phạm vi
Default (chung app) PreferenceManager.getDefaultSharedPreferences(context) Toàn ứng dụng
Private (riêng file) getSharedPreferences("ten_file", MODE_PRIVATE) Chỉ app truy cập

Lưu ý bảo mật

  • Không lưu mật khẩu thật trong SharedPreferences (lưu trữ plaintext, dễ đọc trên thiết bị root)
  • Dùng EncryptedSharedPreferences (Jetpack Security) cho dữ liệu nhạy cảm
  • Dùng Keystore + mã hóa AES cho bảo mật cao