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

Cách dùng SharedPreferences trên Android để lưu, đọc và sửa dữ liệu

Giới thiệu

SharedPreferences là giải pháp lưu trữ key-value đơn giản, phù hợp cho các cài đặt ứng dụng, token đăng nhập, tùy chọn người dùng... Bài viết hướng dẫn lưu, đọc và xóa dữ liệu qua ví dụ lưu tên và email.

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

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

Android Studio → File → New Project → Empty Activity.

Bước 2: Giao diện (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"
    android:padding="8dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/etEmail"
        android:layout_marginTop="40dp"
        android:ems="10"
        android:hint="Tên"
        android:inputType="text" />

    <EditText
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etName"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="10dp"
        android:ems="10"
        android:hint="Email"
        android:inputType="textEmailAddress" />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerInParent="true"
        android:onClick="Save"
        android:text="Lưu" />

    <Button
        android:id="@+id/btnRetrieve"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_centerHorizontal="true"
        android:onClick="Get"
        android:text="Đọc" />

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_centerInParent="true"
        android:onClick="clear"
        android:text="Xóa" />
</RelativeLayout>

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

package app.com.sample;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText editTextName, editTextEmail;
    public static final String MYPREFERENCE = "mypref";
    public static final String NAME_KEY = "nameKey";
    public static final String EMAIL_KEY = "emailKey";
    SharedPreferences sharedPreferences;

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

        editTextEmail = findViewById(R.id.etEmail);
        editTextName = findViewById(R.id.etName);

        sharedPreferences = getSharedPreferences(MYPREFERENCE, Context.MODE_PRIVATE);

        // Tự động điền dữ liệu đã lưu khi mở app
        if (sharedPreferences.contains(NAME_KEY)) {
            editTextName.setText(sharedPreferences.getString(NAME_KEY, ""));
        }
        if (sharedPreferences.contains(EMAIL_KEY)) {
            editTextEmail.setText(sharedPreferences.getString(EMAIL_KEY, ""));
        }
    }

    public void Save(View view) {
        String strName = editTextName.getText().toString();
        String strEmail = editTextEmail.getText().toString();

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(NAME_KEY, strName);
        editor.putString(EMAIL_KEY, strEmail);
        editor.apply(); // Bất đồng bộ, hiệu năng tốt hơn commit()

        Toast.makeText(getApplicationContext(), "Đã lưu", Toast.LENGTH_SHORT).show();
    }

    public void Get(View view) {
        sharedPreferences = getSharedPreferences(MYPREFERENCE, Context.MODE_PRIVATE);
        if (sharedPreferences.contains(NAME_KEY)) {
            editTextName.setText(sharedPreferences.getString(NAME_KEY, ""));
        }
        if (sharedPreferences.contains(EMAIL_KEY)) {
            editTextEmail.setText(sharedPreferences.getString(EMAIL_KEY, ""));
        }
        Toast.makeText(getApplicationContext(), "Đã đọc", Toast.LENGTH_SHORT).show();
    }

    public void clear(View view) {
        editTextName.setText("");
        editTextEmail.setText("");
        Toast.makeText(getApplicationContext(), "Đã xóa form", Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}

Bước 4: Manifest

<?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. Thử nhập tên/email → nhấn Lưu → đóng app → mở lại → dữ liệu vẫn còn.

Cách dùng SharedPreferences trên Android để lưu, đọc và sửa dữ liệu Cách dùng SharedPreferences trên Android để lưu, đọc và sửa dữ liệu

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

SharedPreferences hỗ trợ: String, int, long, float, boolean, Set<String>.

Lưu ý quan trọng

  • Dùng apply() thay vì commit() để ghi bất đồng bộ, không chặn UI thread
  • File XML lưu tại /data/data/package.name/shared_prefs/
  • Không phù hợp lưu dữ liệu lớn hoặc phức tạp → dùng Room/SQLite
  • Từ Android 7.0 (API 24), MODE_WORLD_READABLE/WRITABLE bị deprecated

Cách dùng hiện đại (Jetpack DataStore)

Google khuyến nghị DataStore (Preferences DataStore/Proto DataStore) thay thế SharedPreferences:

  • Dựa trên Kotlin Coroutines/Flow
  • An toàn cho thread, tránh ANR
  • Hỗ trợ migration từ SharedPreferences