存储数组数据到SharedPreferences

本文介绍了一种将数组数据转换为JSON格式,并将其存储到SharedPreferences的方法。通过这种方式,可以有效地管理和读取boolean[]、int[]等类型的数据。文章提供了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考自长城Great的博客: http://blog.youkuaiyun.com/u011494050/article/details/38851369

如果要数组数据(如boolean[] 、int[]等)到SharedPreferences时,我们可以先将数组数据组织成json数据存储到SharedPreferences,读取时则对json数据进行解析就ok了。

保存boolean[] 数组数据:

 1 public static void saveApkEnalbleArray(Context context,boolean[] booleanArray) {  
 2     SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE);  
 3     JSONArray jsonArray = new JSONArray();  
 4     for (boolean b : booleanArray) {  
 5         jsonArray.put(b);  
 6     }  
 7     SharedPreferences.Editor editor = prefs.edit();  
 8     editor.putString(APK_ENABLE_ARRAY,jsonArray.toString());  
 9     editor.commit();  
10 } 

读取数据:

 1     public static boolean[] getApkEnableArray(Context context,int arrayLength)
 2     {
 3         SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE);
 4         boolean[] resArray=new boolean[arrayLength];
 5         Arrays.fill(resArray, true);
 6         try {
 7             JSONArray jsonArray = new JSONArray(prefs.getString(APK_ENABLE_ARRAY, "[]"));
 8             for (int i = 0; i < jsonArray.length(); i++) {
 9                 resArray[i] = jsonArray.getBoolean(i);
10             }
11         } catch (Exception e) {
12             e.printStackTrace();
13         }
14         return resArray;
15     }

 

转载于:https://www.cnblogs.com/wojiaowoen/p/7421681.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值