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
I have read all answers above. That is all correct but i found a more easy solution as below:
Saving String List in shared-preference>>
public static void setSharedPreferenceStringList(Context pContext, String pKey, List pData) {
SharedPreferences.Editor editor = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit();
editor.putInt(pKey + "size", pData.size());
editor.commit();
for (int i = 0; i < pData.size(); i++) {
SharedPreferences.Editor editor1 = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit();
editor1.putString(pKey + i, (pData.get(i)));
editor1.commit();
}
}
and for getting String List from Shared-preference>>
public static List getSharedPreferenceStringList(Context pContext, String pKey) {
int size = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getInt(pKey + "size", 0);
List list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getString(pKey + i, ""));
}
return list;
}
Here Constants.APP_PREFS
is the name of the file to open; can not contain path separators.