How to Cache Json data to be available offline?

后端 未结 7 2360
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 12:55

I have parsed the JSON Data in a listview and now I want to make it available offline. Is there a way to save the JSON data at the phone so that you can see th

7条回答
  •  难免孤独
    2020-12-08 13:10

    How to Cache Json data to be available offline?

    You can use gson to parse JSON data more easily. In your build.gradle file add this dependency.

    compile 'com.google.code.gson:gson:2.8.0'
    

    Then create a POJO class to parse JSON data.

    Example POJO class:

      public class AppGeneralSettings {
        @SerializedName("key1")
    String data;
    
    
        public String getData() {
            return data;
        }
    
    }
    
    • To parse a json string from internet use this snippet

      AppGeneralSettings data=new Gson().fromJson(jsonString, AppGeneralSettings.class);
      

    Then add a helper class to store and retrieve JSON data to and from preferences.

    Example: Helper class to store data

    public class AppPreference {
        private static final String FILE_NAME = BuildConfig.APPLICATION_ID + ".apppreference";
        private static final String APP_GENERAL_SETTINGS = "app_general_settings";
        private final SharedPreferences preferences;
    
        public AppPreference(Context context) {
            preferences = context.getSharedPreferences(FILE_NAME, MODE_PRIVATE);
        }
    
        public SharedPreferences.Editor setGeneralSettings(AppGeneralSettings appGeneralSettings) {
            return preferences.edit().putString(APP_GENERAL_SETTINGS, new Gson().toJson(appGeneralSettings));
        }
    
        public AppGeneralSettings getGeneralSettings() {
            return new Gson().fromJson(preferences.getString(APP_GENERAL_SETTINGS, "{}"), AppGeneralSettings.class);
        }
    }
    

    To save data

    new AppPreference().setGeneralSettings(appGeneralSettings).commit();
    

    To retrieve data

     AppGeneralSettings appGeneralSettings = new AppPreference().getGeneralSettings();
    

提交回复
热议问题