3 ways to store ArrayList in SharedPreferences

Neelanshi
1 min readJan 25, 2021

Shared Preferences allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application.

Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.getDataDirectory().‍

Store ArrayList in SharedPreferences

1. You could convert your List into a HashSet or something similar and store it like that. When you read it back, convert it into an ArrayList, sort it if needed and you’re good to go.

//Retrieve the values
Set<String> set = myScores.getStringSet(“key”, null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet(“key”, set);
scoreEditor.commit();

2. Using this object →TinyDB — Android-Shared-Preferences-Turbo its very simple.

TinyDB tinydb = new TinyDB(context);
tinydb.putList(“MyUsers”, mUsersArray);

This can be retrieved in the following way:

tinydb.getList(“MyUsers”);

3. Another solution could be to store it in sharedPrefernces as a json text by using Gson utility class

//Retrieve the values
Gson gson = new Gson();
String jsonText = Prefs.getString(“key”, null);
String[] text = gson.fromJson(jsonText, String[].class); //EDIT: gso to gson
//Set the values
Gson gson = new Gson();
List<String> textList = new ArrayList<String>(data);
String jsonText = gson.toJson(textList);
prefsEditor.putString(“key”, jsonText);
prefsEditor.apply();

--

--