正在保存 JSON 全局可访问的响应

Saving JSON response globally accessible

我集成了一项网络服务。使用 GSON 解析数据并初始化 model/pojo class.

现在,我需要在整个应用程序中全局访问 Model/Pojo class。

我希望 class 检查不同活动和片段中的各种内容。

如何让 model/pojo class 可以在整个应用程序中访问?

谢谢。

将您的 json 保存到 SharedPreferences。 试试这个:

    public class MySessionManager {
    public Context context;
    private final String PREF_SD_INFO = "Share_Preference";
    private final String KEY_DEF = "KEY_PRE";
    public MySessionManager(Context context) {
            this.context = context;
        }

//save your json data
public void setSongs(SongsList songs) {
            if (context != null) {
                SharedPreferences LoginPref = context.getSharedPreferences(PREF_SD_INFO, 
                Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = LoginPref.edit();
                Gson gson = new Gson();
                songsLists.add(songs);
                String json = gson.toJson(songsLists);
                editor.putString(KEY_PRE, json);
                editor.apply();

            }


//get your json data
    public ArrayList<SongsList> getSongs() {
            if (context != null) {
                SharedPreferences LoginPref = context.getSharedPreferences(PREF_SD_INFO, 
                Context.MODE_PRIVATE);
                Gson gson = new Gson();
                String json = LoginPref.getString(KEY_PRE, null);
                Type type = new TypeToken<ArrayList<SongsList>>() {
                }.getType();
                return gson.fromJson(json, type);
            } else {
                return null;
            }
        }
        }

    }

您应该使 DataSource class 单例并在您的应用程序中使用它:

public class JsonDataSource {
    private static JsonDataSource instance = new JsonDataSource();

    // your json data model
    private JsonData data;

   // private constructor to prevent creating new instances
    private JsonDataSource() { 
    }

    public static JsonDataSource getInstance() {
        return instance;
    }

    public JsonData getData() {
        return data;
    }

    public void setData(JsonData data) {
        this.data = data;
    }
}

那么你可以这样使用

// set data
JsonDataSource.getInstance().setData(jsonData);

// get data
JsonData data =  JsonDataSource.getInstance().getData();
Simple and easy way Just create getter and setter in your root Application Class
and access it globally within the application using getter method

private String jsonData;

 public String getmJsonData()
    {
        return jsonData;
    }

    public void setjsonData(String jsonData) {
        this.jsonData= jsonData;
    }


//Set Data

((Your_application_class)getApplicationContext()).setjsonData(data);

//get Data

((Your_application_class)getApplicationContext()).getjsondata());