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

Cách lưu trữ JSON Object trong Singleton với Global Context Android

Singleton lưu JSON + Global Context

Kết hợp hai kỹ thuật: Singleton pattern để quản lý đối tượng JSON duy nhất, và Global Context (Application Context) để tránh memory leak khi cần Context cho Toast hoặc các thao tác khác.

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

Android Studio → File → New Project.

Bước 2: Giao diện (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="Lưu & Hiển thị JSON từ Singleton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Bước 3: MainActivity.java

package com.example.jsonSingleton;

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 btnShow;
    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);

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

        btnShow.setOnClickListener(v -> {
            singletonExample.storeJson(jsonObject);
            Toast.makeText(SingleTonExample.get(), 
                singletonExample.getJSON(), 
                Toast.LENGTH_LONG).show();
        });
    }
}

Bước 4: SingleTonExample.java

package com.example.jsonSingleton;

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() : "JSON rỗng";
    }
}

Chạy ứng dụng

Nhấn nút để lưu JSONObject mẫu vào Singleton và hiển thị nội dung JSON qua Toast sử dụng Global Context.

Cải tiến cho thực tế

// Thêm phương thức lấy JSONObject gốc (không toString)
public JSONObject getJsonObject() {
    return jsonData;
}

// Thêm phương thức cập nhật field cụ thể
public void updateField(String key, Object value) {
    if (jsonData != null) {
        try {
            jsonData.put(key, value);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

// Thread-safe cho JSONObject (nếu truy cập từ nhiều thread)
public synchronized void storeJson(JSONObject json) {
    this.jsonData = json;
}

Khi nào dùng cách này?

  • Cần chia sẻ cấu hình JSON giữa nhiều màn hình
  • Cache response API dạng JSON tạm thời
  • Tránh parse JSON lặp lại nhiều lần