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
following code is the accepted answer, with a few more lines for new folks (me), eg. shows how to convert the set type object back to arrayList, and additional guidance on what goes before '.putStringSet' and '.getStringSet'. (thank you evilone)
// shared preferences
private SharedPreferences preferences;
private SharedPreferences.Editor nsuserdefaults;
// setup persistent data
preferences = this.getSharedPreferences("MyPreferences", MainActivity.MODE_PRIVATE);
nsuserdefaults = preferences.edit();
arrayOfMemberUrlsUserIsFollowing = new ArrayList();
//Retrieve followers from sharedPreferences
Set set = preferences.getStringSet("following", null);
if (set == null) {
// lazy instantiate array
arrayOfMemberUrlsUserIsFollowing = new ArrayList();
} else {
// there is data from previous run
arrayOfMemberUrlsUserIsFollowing = new ArrayList<>(set);
}
// convert arraylist to set, and save arrayOfMemberUrlsUserIsFollowing to nsuserdefaults
Set set = new HashSet();
set.addAll(arrayOfMemberUrlsUserIsFollowing);
nsuserdefaults.putStringSet("following", set);
nsuserdefaults.commit();