Search code examples
androidjsonmodelpojo

Saving JSON response globally accessible


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.


Solution

  • 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();