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<String> 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<String> set = new HashSet(arrayList);
prefs.edit().putStringSet("names", set).apply();
set = (HashSet<String>) prefs.getStringSet("names", null);
arrayList = new ArrayList(set);
Log.i("array list", arrayList.toString());
}
}