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 used the same manner of saving and retrieving a String but here with arrayList I've used HashSet as a mediator
To save arrayList to SharedPreferences we use HashSet:
1- we create SharedPreferences variable (in place where the change happens to the array)
2 - we convert the arrayList to HashSet
3 - then we put the stringSet and apply
4 - you getStringSet within HashSet and recreate ArrayList to set the HashSet.
public class MainActivity extends AppCompatActivity {
ArrayList arrayList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = this.getSharedPreferences("com.example.nec.myapplication", Context.MODE_PRIVATE);
HashSet set = new HashSet(arrayList);
prefs.edit().putStringSet("names", set).apply();
set = (HashSet) prefs.getStringSet("names", null);
arrayList = new ArrayList(set);
Log.i("array list", arrayList.toString());
}
}