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
My utils class for save list to SharedPreferences
public class SharedPrefApi {
private SharedPreferences sharedPreferences;
private Gson gson;
public SharedPrefApi(Context context, Gson gson) {
this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
this.gson = gson;
}
...
public void putList(String key, List list) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, gson.toJson(list));
editor.apply();
}
public List getList(String key, Class clazz) {
Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
return gson.fromJson(getString(key, null), typeOfT);
}
}
Using
// for save
sharedPrefApi.putList(SharedPrefApi.Key.USER_LIST, userList);
// for retrieve
List userList = sharedPrefApi.getList(SharedPrefApi.Key.USER_LIST, User.class);
.
Full code of my utils // check using example in Activity code