How can I store an integer array in SharedPreferences?

匿名 (未验证) 提交于 2019-12-03 08:52:47

问题:

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

回答1:

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


回答2:

you can't put arrays in sharedPrefs, but you can workaround:

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


回答3:

Here's my version, based on Egor's answer. I prefer not to use StringBuilder unless I'm building an enourmous string, but thanks to Egor for using StringTokenizer -- haven't made much use of this in the past, but it's very handy! FYI, this went in my Utility class:

public static void saveIntListPrefs(     String name, Activity activity, List list) {   String s = "";   for (Integer i : list) {     s += i + ",";   }    Editor editor = activity.getPreferences(Context.MODE_PRIVATE).edit();   editor.putString(name, s);   editor.commit(); }  public static ArrayList readIntArrayPrefs(String name, Activity activity) {   SharedPreferences prefs = activity        
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!