Saving JSON response globally accessible

Jaimin Modi :

I have integrated one web-service. Parsed the data using GSON and initialized model/pojo class.

Now, I have requirement to access that Model/Pojo class globally all over the application.

I want that class to check various things in separate activities and fragments.

How can I make that model/pojo class accessible all over the app?

Thanks.

Sujan Poudel :

You should make the DataSource class singleton and use it in your app:

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;
    }
}

then you can use like this

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

// get data
JsonData data =  JsonDataSource.getInstance().getData();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=301732&siteId=1