Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีใช้ SharedPreferences ระหว่าง Activity ใน Android

ภาพรวม

SharedPreferences เป็นกลไกเก็บข้อมูลแบบ Key-Value อย่างง่าย เหมาะสำหรับข้อมูลเล็กน้อยที่ต้องคงอยู่ตลอดการใช้งานแอป (Persistent) เช่น การตั้งค่า, Token, Flag ต่างๆ สามารถเข้าถึงได้จาก Activity ใดก็ได้ในแอปเดียวกัน

ตัวอย่าง: ส่งข้อความจาก MainActivity ไป SecondActivity ผ่าน SharedPreferences

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → New Project → Empty Activity (Package: com.example.myapplication)

ขั้นตอนที่ 2: Layout หลัก (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:hint="Enter something to pass"
        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="Next" />
</LinearLayout>

ขั้นตอนที่ 3: 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";
    private static final String KEY_VALUE = "value";

    @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
            SharedPreferences sharedPref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString(KEY_VALUE, value);
            editor.apply(); // ใช้ apply() แทน commit() เพื่อประสิทธิภาพ (async)

            // ไป Activity ถัดไป
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        });
    }
}

ขั้นตอนที่ 4: Layout Activity ที่สอง (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:gravity="center"
        android:textSize="18sp" />
</LinearLayout>

ขั้นตอนที่ 5: 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";
    private static final String KEY_VALUE = "value";

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

        TextView textView = findViewById(R.id.text_view);
        
        // อ่านข้อมูลจาก SharedPreferences
        SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        String value = sharedPreferences.getString(KEY_VALUE, ""); // ค่า default = ""
        textView.setText("ข้อมูลที่รับ: " + value);
    }
}

ขั้นตอนที่ 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"></activity>
    </application>
</manifest>

หลักการทำงาน

  1. MainActivity รับข้อความจากผู้ใช้ → บันทึกลง SharedPreferences ด้วย key "value"
  2. เริ่ม SecondActivity
  3. SecondActivity อ่านค่าจาก SharedPreferences ด้วย key เดียวกัน → แสดงผล

ประเภทข้อมูลที่รองรับ

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

apply() vs commit()

เมธอดลักษณะแนะนำสำหรับ
apply()Async, ไม่คืนค่า, ไม่บล็อก UI Threadการใช้งานทั่วไป
commit()Sync, คืนค่า boolean, บล็อก UI Threadเมื่อต้องรู้ว่าบันทึกสำเร็จทันที

ข้อดีและข้อจำกัด

ข้อดี

  • ง่าย เร็ว ไม่ต้องจัดการ Database
  • ข้อมูลคงอยู่แม้แอปจะถูกปิด
  • เข้าถึงได้จาก Component ใดก็ได้ในแอป

ข้อจำกัด

  • ไม่เหมาะกับข้อมูลขนาดใหญ่ หรือโครงสร้างซับซ้อน
  • ไม่มีการ Query/Filter ข้อมูลได้
  • ไม่รองรับการ sync ระหว่างอุปกรณ์ (ใช้ DataStore หรือ Room แทน)
  • ใน Android 11+ ควรย้ายไปใช้ Jetpack DataStore (Preferences DataStore) ซึ่งใช้ Coroutines และ Flow
แนวทางปัจจุบัน: สำหรับโปรเจกต์ใหม่ แนะนำให้ใช้ Preferences DataStore แทน SharedPreferences เพราะรองรับ Kotlin Coroutines, Flow และแก้ปัญหา UI Thread blocking