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