0

Afternoon all,

I'm pretty new to android and java in general so I'm not sure if what I'm trying to achieve is possible this way.

I'm trying to implement a Get and Set method in a shared preference class to save an Array and get it out again when required. In a perfect world I would use the code below:

public class dataStorage {
private SharedPreferences sharedPreferences;
private static String PREF_NAME = "prefs";

public dataStorage() {
    // Blank
}

private static String[] getPuzzleList(Context context, String key)
{
    return getPrefs(context).getArray(PREF_NAME, Context.MODE_PRIVATE);

}

private static void setPuzzleList(Context context, String key, String[] stringArray)
{
    SharedPreferences.Editor editor = getPrefs(context).edit();
    editor.putArray(key, stringArray);
    editor.commit();
}

private static SharedPreferences getPrefs(Context context) {
    return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}

public static String getPuzzle(Context context, String key) {
    return getPrefs(context).getString(key, "default_string");
}

public static void setPuzzle(Context context, String key, String value) {
    SharedPreferences.Editor editor = getPrefs(context).edit();
    editor.putString(key , value);
    editor.commit();
}
}

My get and set for the individual puzzles work fine because putString and getString are valid methods, whereas getArray and `putArray are not.

Is there a method call I can use to pass string arrays in and out of shared preferences or will I have to implement forloops in order to save them as individual strings? And when I want to pass to an ArrayAdapter, use another for loop to get all the strings into one array again?

Any feedback welcome. Thanks.

James
  • 356
  • 2
  • 13
  • Convert your array to a Set and use the get/setStringSet() methods. See: http://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences. – Gary Bak Apr 22 '16 at 19:14

2 Answers2

1

you can put a Set:

private static void setPuzzleList(Context context, String key, String[] stringArray) {
    SharedPreferences.Editor editor = getPrefs(context).edit();
    Set<String> set = new HashSet<String>();
    set.addAll(Arrays.asList(stringArray));
    editor.putStringSet("key", set);
    editor.commit();
}
Matias Elorriaga
  • 8,880
  • 5
  • 40
  • 58
0

Storing an array

public static void storeArray()
{
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sp.edit();


    for(int i=0;i<stringArray.length;i++)  
    {
       editor.putString("key" + i, stringArray[i]);  
    }

 editor.commit();     
}
MrRobot9
  • 2,402
  • 4
  • 31
  • 68