I have an ArrayList
with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves
this should work:
public void setSections (Context c, List sectionList){
this.sectionList = sectionList;
Type sectionListType = new TypeToken>(){}.getType();
String sectionListString = new Gson().toJson(sectionList,sectionListType);
SharedPreferences.Editor editor = getSharedPreferences(c).edit().putString(PREFS_KEY_SECTIONS, sectionListString);
editor.apply();
}
them, to catch it just:
public List getSections(Context c){
if(this.sectionList == null){
String sSections = getSharedPreferences(c).getString(PREFS_KEY_SECTIONS, null);
if(sSections == null){
return new ArrayList<>();
}
Type sectionListType = new TypeToken>(){}.getType();
try {
this.sectionList = new Gson().fromJson(sSections, sectionListType);
if(this.sectionList == null){
return new ArrayList<>();
}
}catch (JsonSyntaxException ex){
return new ArrayList<>();
}catch (JsonParseException exc){
return new ArrayList<>();
}
}
return this.sectionList;
}
it works for me.