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

วิธีใช้ Singleton Class ใน Android เพื่อเก็บข้อมูล

ภาพรวม

ตัวอย่างนี้สาธิตการใช้ Singleton Class เพื่อเก็บข้อมูลชั่วคราว (In-Memory Storage) ระหว่างการทำงานของแอปพลิเคชัน โดยรับข้อความจาก EditText แล้วเก็บไว้ใน Singleton และแสดงผลผ่าน Toast

ขั้นตอนการสร้าง

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

Android Studio → File → New Project → กรอกรายละเอียด

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="ป้อนข้อความ" />

    <Button
        android:id="@+id/save"
        android:text="บันทึกใน Singleton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

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

package com.example.andy.myapplication;

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.Toast;

public class MainActivity extends AppCompatActivity {
    EditText editText;
    Button save;

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

        editText = findViewById(R.id.editText);
        save = findViewById(R.id.save);

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputText = editText.getText().toString().trim();

                if (inputText.isEmpty()) {
                    editText.setError("กรุณาป้อนข้อความ");
                } else {
                    SingleTonExample singletonExample = SingleTonExample.getInstance();
                    singletonExample.setText(inputText);
                    Toast.makeText(MainActivity.this, singletonExample.getText(), Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}

ขั้นตอนที่ 4: สร้างคลาส Singleton (SingleTonExample.java)

package com.example.andy.myapplication;

public class SingleTonExample {
    private String storedText;
    private static final SingleTonExample ourInstance = new SingleTonExample();

    public static SingleTonExample getInstance() {
        return ourInstance;
    }

    private SingleTonExample() { }

    public void setText(String text) {
        this.storedText = text;
    }

    public String getText() {
        return storedText;
    }
}

การทดสอบ

รันแอปพลิเคชัน ป้อนข้อความ (เช่น "tutorialspoint.com") แล้วกดปุ่มบันทึก

วิธีใช้ Singleton Class ใน Android เพื่อเก็บข้อมูล

ข้อความจะถูกเก็บใน Singleton และแสดงผ่าน Toast

วิธีใช้ Singleton Class ใน Android เพื่อเก็บข้อมูล

กรณีการใช้งานจริง (Real-world Use Cases)

  • User Session Data: เก็บ Token, User Profile ระหว่างการใช้งาน
  • Cache Data: ข้อมูลที่ดึงจาก API ไว้ใช้ซ้ำ
  • App Settings: การตั้งค่าที่เปลี่ยนแปลงได้ระหว่างรัน
  • Event Bus/Message Queue: สื่อสารระหว่าง Component

ข้อจำกัดและแนวทางแก้ไข

ปัญหา แนวทางแก้ไข
ข้อมูลหายเมื่อ Process ถูก Kill ใช้ SharedPreferences, Room Database, หรือ DataStore
Memory Leak จาก Context อย่าเก็บ View/Activity Context ใน Singleton
ยากต่อการทดสอบ (Testing) ใช้ Dependency Injection (Hilt/Koin) แทน
Thread Safety เพิ่ม synchronized หรือใช้ ConcurrentHashMap

แนวทางปฏิบัติที่ดีกว่า (Modern Kotlin)

// Kotlin Object Declaration (Thread-safe by default)
object DataRepository {
    private var storedText: String? = null
    
    fun setText(text: String) { storedText = text }
    fun getText(): String? = storedText
}

// Usage
DataRepository.setText("Hello")
val text = DataRepository.getText()