Is it possible to add an array or object to SharedPreferences on Android Is it possible to add an array or object to SharedPreferences on Android android android

Is it possible to add an array or object to SharedPreferences on Android


Regardless of the API level, Check String arrays and Object arrays in SharedPreferences


SAVE ARRAY

public boolean saveArray(String[] array, String arrayName, Context mContext) {       SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);      SharedPreferences.Editor editor = prefs.edit();      editor.putInt(arrayName +"_size", array.length);      for(int i=0;i<array.length;i++)          editor.putString(arrayName + "_" + i, array[i]);      return editor.commit();  } 

LOAD ARRAY

public String[] loadArray(String arrayName, Context mContext) {      SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);      int size = prefs.getInt(arrayName + "_size", 0);      String array[] = new String[size];      for(int i=0;i<size;i++)          array[i] = prefs.getString(arrayName + "_" + i, null);      return array;  }  


So from the android developer site on Data Storage:

User Preferences

Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).

So I think it is okay since it is simply just key-value pairs which are persisted.

To the original poster, this is not that hard. You simply just iterate through your array list and add the items. In this example I use a map for simplicity but you can use an array list and change it appropriately:

// my list of names, icon locationsMap<String, String> nameIcons = new HashMap<String, String>();nameIcons.put("Noel", "/location/to/noel/icon.png");nameIcons.put("Bob", "another/location/to/bob/icon.png");nameIcons.put("another name", "last/location/icon.png");SharedPreferences keyValues = getContext().getSharedPreferences("name_icons_list", Context.MODE_PRIVATE);SharedPreferences.Editor keyValuesEditor = keyValues.edit();for (String s : nameIcons.keySet()) {    // use the name as the key, and the icon as the value    keyValuesEditor.putString(s, nameIcons.get(s));}keyValuesEditor.commit()

You would do something similar to read the key-value pairs again. Let me know if this works.

Update: If you're using API level 11 or later, there is a method to write out a String Set


To write,

SharedPreferences prefs = PreferenceManager        .getDefaultSharedPreferences(this);JSONArray jsonArray = new JSONArray();jsonArray.put(1);jsonArray.put(2);Editor editor = prefs.edit();editor.putString("key", jsonArray.toString());System.out.println(jsonArray.toString());editor.commit();

To Read,

try {    JSONArray jsonArray2 = new JSONArray(prefs.getString("key", "[]"));    for (int i = 0; i < jsonArray2.length(); i++) {         Log.d("your JSON Array", jsonArray2.getInt(i)+"");    }} catch (Exception e) {    e.printStackTrace();}

Other way to do same:

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

Using GSON in Java:

public void saveArrayList(ArrayList<String> list, String key){    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);    SharedPreferences.Editor editor = prefs.edit();    Gson gson = new Gson();    String json = gson.toJson(list);    editor.putString(key, json);    editor.apply();    }public ArrayList<String> getArrayList(String key){    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);    Gson gson = new Gson();    String json = prefs.getString(key, null);    Type type = new TypeToken<ArrayList<String>>() {}.getType();    return gson.fromJson(json, type);}

Using GSON in Kotlin

fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)    val editor: Editor = prefs.edit()    val gson = Gson()    val json: String = gson.toJson(list)    editor.putString(key, json)    editor.apply()}fun getArrayList(key: String?): java.util.ArrayList<String?>? {    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)    val gson = Gson()    val json: String = prefs.getString(key, null)    val type: Type = object : TypeToken<java.util.ArrayList<String?>?>() {}.getType()    return gson.fromJson(json, type)}