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

Sử dụng SharedPreferences để chia sẻ dữ liệu giữa các Activity Android

SharedPreferences là cơ chế lưu trữ key-value nhẹ lượng, phù hợp để lưu cài đặt, token, hoặc dữ liệu nhỏ cần chia sẻ giữa các Activity, thậm chí giữa các lần chạy ứng dụng.

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

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

Tạo dự án Android Studio với package com.example.myapplication.

Bước 2: Giao diện màn hình chính (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_margin="16dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:hint="Nhập nội dung để chuyển"
        android:inputType="text" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="16dp"
        android:text="Tiếp theo" />
</LinearLayout>

Bước 3: Lưu dữ liệu và mở Activity mới (src/MainActivity.java)

package com.example.myapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    private static final String PREF_NAME = "myKey";

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

        EditText editText = findViewById(R.id.edit_text);
        Button button = findViewById(R.id.button);

        button.setOnClickListener(v -> {
            String value = editText.getText().toString().trim();
            SharedPreferences sharedPref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("value", value);
            editor.apply(); // Bất đồng bộ, hiệu năng tốt hơn commit()

            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        });
    }
}

Bước 4: Giao diện màn hình nhận (res/layout/activity_second.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_margin="16dp"
    android:orientation="vertical"
    tools:context=".SecondActivity">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
</LinearLayout>

Bước 5: Đọc dữ liệu (src/SecondActivity.java)

package com.example.myapplication;

import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {
    private static final String PREF_NAME = "myKey";

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

        TextView textView = findViewById(R.id.text_view);
        SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        String value = sharedPreferences.getString("value", ""); // Giá trị mặc định rỗng
        textView.setText(value);
    }
}

Bước 6: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <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>
        <activity android:name=".SecondActivity" />
    </application>
</manifest>

Các lưu ý quan trọng

  • MODE_PRIVATE: File chỉ truy cập được bởi ứng dụng của bạn (an toàn). Không dùng MODE_WORLD_READABLE/WRITABLE (đã deprecated).
  • apply() vs commit(): apply() ghi bất đồng bộ (không block UI), commit() ghi đồng bộ và trả về boolean. Ưu tiên apply().
  • Kiểu dữ liệu hỗ trợ: String, int, long, float, boolean, Set<String>.
  • Độ bền: Dữ liệu tồn tại cho đến khi gỡ app hoặc xóa dữ liệu app. Phù hợp cho cài đặt, token đăng nhập, không phù hợp cho dữ liệu tạm thời luồng công việc.
  • Truy cập cross-process: Nếu cần chia sẻ giữa nhiều process, dùng getSharedPreferences(name, Context.MODE_MULTI_PROCESS) ( ít dùng).