放置数组的共享首选项 [英] sharedpreferences putting an array

查看:48
本文介绍了放置数组的共享首选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用此代码添加数组并稍后检索它?我可以使用简单的 for 循环吗?

how can I use this code in order to add an array and retrieve it later? can I use a simple for loop?

  SharedPreferences settings = getSharedPreferences("isChk", 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putBoolean("keys",ArrayValue[i] );
  editor.commit();

然后我如何检索它们并将每个元素存储在数组变量中我可以使用它吗?

and how can I then retrieve them and store each element in an array variable can I use this?

for( int i=0; i<myArr.size(); i++){
keys[i] = settings.getBoolean("isChk", false);
isChkb.add(keys[i]);
}

推荐答案

要将 array 存储在 sharedPreferences 中,您可以放入 array 值 在一个 String 中,然后 store 这个 String .. 如果你想得到你的 array 值 (在我们的例子中,存储在一个字符串中),你获取stringparse它使用StringTokenizer,如下所示:(在我的示例中,我将存储和检索布尔数组)

To store an array in sharedPreferences , you can put your array values in a String , then store this String .. and if you you want to get your array value (in our case ,stored in a string) , you get the string and parse it using StringTokenizer like this : (In my example I will store and retreive an array of Boolean)

  • 将您的布尔值放入一个字符串中,用一个字符(例如逗号)分隔每个 int,然后将它们保存为一个字符串:

  • Put your booleans 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);
Boolean[] list = new Boolean[10];
StringBuilder str = new StringBuilder();
for (int i = 0; i < list.length; i++) {
str.append(list[i]).append(",");
}
prefs.edit().putBoolean("keys", str.toString()).commit();

  • 获取字符串并使用 StringTokenizer 解析它:

  • Get the string and parse it using StringTokenizer:

    String savedString = prefs.getString("string", "");
    StringTokenizer st = new StringTokenizer(savedString, ",");
    Boolean[] savedList = new Boolean[10];
     for (int i = 0; i < 10; i++) {
        savedList[i] = Boolean.valueOf(st.nextToken();
      }
    

  • 这篇关于放置数组的共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆