Search code examples
androidsharedpreferences

How can I store an integer array in SharedPreferences?


I want to save/recall an integer array using SharedPreferences. Is this possible?


Solution

  • 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());
      }