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

วิธีเก็บ JSON Object ใน Singleton พร้อม Global Context ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตการเก็บ JSONObject ลงใน Singleton พร้อมใช้ Global Context เพื่อแสดงผลผ่าน Toast เหมาะสำหรับการ Cache ข้อมูล JSON จาก API Response

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

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

    <Button
        android:id="@+id/show"
        android:text="บันทึก JSON ใน 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.Toast;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    Button show;
    JSONObject jsonObject;
    SingleTonExample singletonExample;

    {
        try {
            jsonObject = new JSONObject("{\"balance\": 1000.21, \"num\": 100, \"is_vip\": true, \"name\": \"foo\"}");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

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

        show = findViewById(R.id.show);
        singletonExample = SingleTonExample.getInstance();
        singletonExample.init(getApplicationContext());

        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                singletonExample.storeJson(jsonObject);
                Toast.makeText(SingleTonExample.get(), singletonExample.getJSON(), Toast.LENGTH_LONG).show();
            }
        });
    }
}

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

package com.example.andy.myapplication;

import android.content.Context;
import org.json.JSONObject;

public class SingleTonExample {
    private Context appContext;
    private JSONObject jsonData;
    private static final SingleTonExample ourInstance = new SingleTonExample();

    public void init(Context context) {
        if (appContext == null) {
            this.appContext = context;
        }
    }

    private Context getContext() {
        return appContext;
    }

    public static Context get() {
        return getInstance().getContext();
    }

    public static synchronized SingleTonExample getInstance() {
        return ourInstance;
    }

    private SingleTonExample() { }

    public void storeJson(JSONObject json) {
        this.jsonData = json;
    }

    public String getJSON() {
        return jsonData != null ? jsonData.toString() : "No data";
    }
}

การทดสอบ

รันแอปพลิเคชัน หน้าจอเริ่มต้นแสดงตามภาพ

วิธีเก็บ JSON Object ใน Singleton พร้อม Global Context ใน Android

คลิกปุ่ม จะแสดง JSON Object ใน Toast โดยใช้ Global Context

วิธีเก็บ JSON Object ใน Singleton พร้อม Global Context ใน Android

การปรับปรุงสำหรับ Production (Best Practices)

1. ใช้ Gson/Moshi แทน JSONObject โดยตรง

// Data Class
data class UserProfile(
    val balance: Double,
    val num: Int,
    val isVip: Boolean,
    val name: String
)

// Singleton with Gson
object JsonCache {
    private var userProfile: UserProfile? = null
    private val gson = Gson()
    
    fun storeJson(jsonString: String) {
        userProfile = gson.fromJson(jsonString, UserProfile::class.java)
    }
    
    fun getJsonString(): String? {
        return userProfile?.let { gson.toJson(it) }
    }
    
    fun getUserProfile(): UserProfile? = userProfile
}

2. เพิ่ม Thread Safety

// ใช้ ConcurrentHashMap สำหรับหลาย Key
object JsonCache {
    private val cache = ConcurrentHashMap<String, String>()
    
    fun put(key: String, json: String) = cache.put(key, json)
    fun get(key: String): String? = cache[key]
    fun remove(key: String) = cache.remove(key)
    fun clear() = cache.clear()
}

3. เพิ่ม Expiration Time (TTL)

data class CacheEntry<T>(
    val data: T,
    val timestamp: Long = System.currentTimeMillis(),
    val ttlMillis: Long = 30 * 60 * 1000 // 30 นาที
) {
    fun isExpired() = System.currentTimeMillis() - timestamp > ttlMillis
}

ข้อควรระวัง

  • JSONObject ไม่ใช่ Parcelable/Serializable ไม่สามารถส่งผ่าน Bundle/Intent ได้โดยตรง
  • ข้อมูลใน Singleton จะหายเมื่อ Process ถูก Kill
  • ขนาด JSON ใหญ่ๆ อาจกิน Memory มาก ควรจำกัดขนาด Cache
  • Global Context จาก Application ปลอดภัยกว่า Activity Context