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