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
Use this custom class:
public class SharedPreferencesUtil {
public static void pushStringList(SharedPreferences sharedPref,
List list, String uniqueListName) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(uniqueListName + "_size", list.size());
for (int i = 0; i < list.size(); i++) {
editor.remove(uniqueListName + i);
editor.putString(uniqueListName + i, list.get(i));
}
editor.apply();
}
public static List pullStringList(SharedPreferences sharedPref,
String uniqueListName) {
List result = new ArrayList<>();
int size = sharedPref.getInt(uniqueListName + "_size", 0);
for (int i = 0; i < size; i++) {
result.add(sharedPref.getString(uniqueListName + i, null));
}
return result;
}
}
How to use:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferencesUtil.pushStringList(sharedPref, list, getString(R.string.list_name));
List list = SharedPreferencesUtil.pullStringList(sharedPref, getString(R.string.list_name));