例如,我要保存boolean[] 数组数据:
public static void saveApkEnalbleArray(Context context,boolean[] booleanArray) { SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE); JSONArray jsonArray = new JSONArray(); for (boolean b : booleanArray) { jsonArray.put(b); } SharedPreferences.Editor editor = prefs.edit(); editor.putString(APK_ENABLE_ARRAY,jsonArray.toString()); editor.commit(); }
读取数据:
public static boolean[] getApkEnableArray(Context context,int arrayLength) { SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE); boolean[] resArray=new boolean[arrayLength]; Arrays.fill(resArray, true); try { JSONArray jsonArray = new JSONArray(prefs.getString(APK_ENABLE_ARRAY, "[]")); for (int i = 0; i < jsonArray.length(); i++) { resArray[i] = jsonArray.getBoolean(i); } } catch (Exception e) { e.printStackTrace(); } return resArray; }
当保存一些复杂的对象数组时,可以用gson来处理json和object的相互转换。
【android】存储数组数据到SharedPreferences
原文:http://blog.csdn.net/u011494050/article/details/38851369