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

วิธีใช้ apply() ใน Android SharedPreferences พร้อมตัวอย่าง

ก่อนจะเรียนรู้ SharedPreferences.apply() เราควรเข้าใจก่อนว่า SharedPreferences ใน Android คืออะไร ใช้เก็บหรือดึงค่าเป็นคู่คีย์-ค่า (key-value pair) มีเมธอดหลัก 5 ตัวดังนี้:

  • edit() - เริ่มแก้ไขค่า SharedPreferences
  • commit() - บันทึกค่าลงไฟล์ XML แบบ synchronous (บล็อคจนเสร็จ)
  • apply() - บันทึกค่าลงหน่วยความจำทันที และจัดตารางเขียนลง persistent storage แบบ asynchronous
  • remove(String key) - ลบคีย์และค่าจาก SharedPreferences
  • put() - ใส่คีย์และค่าลง SharedPreferences

ตัวอย่างไวยากรณ์ SharedPreferences:

final SharedPreferences sharedPreferences = getSharedPreferences("USER", MODE_PRIVATE);

สร้างไฟล์ SharedPreferences ชื่อ USER.xml แบบ private mode (แอปอื่นเข้าถึงไม่ได้)

ความแตกต่าง apply() vs commit()

apply() เขียนหน่วยความจำทันที และจัดตารางเขียนไฟล์แบบ asynchronous (non-blocking) เหมาะสำหรับ UI Thread

commit() เขียนไฟล์แบบ synchronous (blocking) คืนค่า boolean บอกสำเร็จ/ล้มเหลว

ตัวอย่างการใช้ apply() ใน SharedPreferences

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

เปิด Android Studio ไปที่ File → New Project แล้วกรอกรายละเอียดที่จำเป็น

ขั้นตอนที่ 2: ออกแบบหน้าจอ (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginTop="8dp"
        android:hint="NAME" />

    <EditText
        android:id="@+id/address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="84dp"
        android:hint="Phone Number"
        android:inputType="phone" />

    <Button
        android:id="@+id/button"
        android:layout_width="108dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="120dp"
        android:text="Save" />

    <Button
        android:id="@+id/read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="88dp"
        android:text="Read" />

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="184dp"
        android:text="Result" />

</android.support.constraint.ConstraintLayout>

มี EditText 2 ตัวสำหรับชื่อและที่อยู่/โทรศัพท์ ปุ่ม Save บันทึกลง SharedPreferences ปุ่ม Read อ่านค่ามาแสดง

ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java

package com.example.andy.myapplication;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final SharedPreferences sharedPreferences = getSharedPreferences("USER", MODE_PRIVATE);
        final EditText name = findViewById(R.id.name);
        final EditText address = findViewById(R.id.address);
        final TextView result = findViewById(R.id.result);
        Button save = findViewById(R.id.button);
        Button read = findViewById(R.id.read);

        // ปุ่ม Read - อ่านข้อมูลจาก SharedPreferences
        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String savedName = sharedPreferences.getString("Name", "No name");
                String savedAddress = sharedPreferences.getString("Address", "No Address");
                result.setText("Name is " + savedName + " Address " + savedAddress);
            }
        });

        // ปุ่ม Save - บันทึกข้อมูลด้วย apply()
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (name.getText().toString().isEmpty() && address.getText().toString().isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please enter all data", Toast.LENGTH_LONG).show();
                } else {
                    String nameData = name.getText().toString().trim();
                    String addressData = address.getText().toString().trim();
                    
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("Name", nameData);
                    editor.putString("Address", addressData);
                    // ใช้ apply() แทน commit() เพื่อ non-blocking
                    editor.apply();
                    
                    Toast.makeText(MainActivity.this, "Saved", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml

ไม่ต้องเปลี่ยนแปลงใดๆ

การทดสอบแอปพลิเคชัน

เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity และคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอเริ่มต้น

วิธีใช้ apply() ใน Android SharedPreferences พร้อมตัวอย่าง

กรอกชื่อและที่อยู่ แล้วกด Save

วิธีใช้ apply() ใน Android SharedPreferences พร้อมตัวอย่าง

กด Read จะแสดงข้อมูลที่บันทึกไว้ใน TextView