How can I store an integer array in SharedPreferences?

I want to save/recall an integer array using SharedPreferences, is this possible?


You can try to do it this way:

  • Put your integers into a string, delimiting every int by a character, for example a comma, and then save them as a string:

    SharedPreferences prefs = getPreferences(MODE_PRIVATE);
    int[] list = new int[10];
    StringBuilder str = new StringBuilder();
    for (int i = 0; i < list.length; i++) {
        str.append(list[i]).append(",");
    }
    prefs.edit().putString("string", str.toString());
    
  • Get the string and parse it using StringTokenizer:

    String savedString = prefs.getString("string", "");
    StringTokenizer st = new StringTokenizer(savedString, ",");
    int[] savedList = new int[10];
    for (int i = 0; i < 10; i++) {
        savedList[i] = Integer.parseInt(st.nextToken());
    }
    

You can't put Arrays in SharedPreferences, but you can workaround:

private static final String LEN_PREFIX = "Count_";
private static final String VAL_PREFIX = "IntValue_";
public void storeIntArray(String name, int[] array){
    SharedPreferences.Editor edit= mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE).edit();
    edit.putInt(LEN_PREFIX + name, array.length);
    int count = 0;
    for (int i: array){
        edit.putInt(VAL_PREFIX + name + count++, i);
    }
    edit.commit();
}
public int[] getFromPrefs(String name){
    int[] ret;
    SharedPreferences prefs = mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE);
    int count = prefs.getInt(LEN_PREFIX + name, 0);
    ret = new int[count];
    for (int i = 0; i < count; i++){
        ret[i] = prefs.getInt(VAL_PREFIX+ name + i, i);
    }
    return ret;
}