如何使用SharedPreferences保存字符串数组?

时间:2014-05-18 18:37:30

标签: android arrays string sharedpreferences

我有一个字符串数组,我需要使用SharedPreferences保存此数组,然后在ListView上读取并显示它们。

现在,我使用这个算法:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

//To save the strings
public void saveStrings(String[] str){
    int a = 0;
    int lenght = str.length;
    while (a<lenght){
        sp.edit().putString(Integer.toString(a), Integer.toString(str[a])).apply();
        a=a+1;
    }
}

//To read the strings
public String[] getStrings(){
    String[] str = new String [8];
    int a = 0;
    int lenght = 8; //To read 8 strings
    while (a<lenght){
        str[a] = sp.getString(Integer.toString(a),"Null");
        a=a+1;
    }
return str;
}

有没有办法保存和读取整个数组,而不是一次一个字符串?

对于这个项目,我使用API​​级别19(Android 4.4.2 KitKat)

3 个答案:

答案 0 :(得分:2)

好吧,您可以使用putStringSet(),但(a)它仅来自API级别11以及(b)如其名称所示, sets < / strong>(这意味着您将丢失原始排序以及阵列中存在的任何重复项。)

我们通过&#34;编码&#34;解决了这个问题。将集合转换为字符串并使用putString()并在getString()之后使用这对方法解码它们(对于ArrayList,但应该可以轻松转换为数组版本):

public String encodeStringList(List<String> list, char separator)
{
    StringBuilder sb = new StringBuilder(list.size() * 50);

    for (String item : list)
    {
        if (sb.length() != 0)
            sb.append(separator);

        // Escape the separator character.
        sb.append(item.replace(Character.toString(separator), "\\" + separator));
    }

    return sb.toString();
}

public List<String> decodeStringList(String encoded, char separator)
{
    ArrayList<String> items = new ArrayList<String>();

    if (encoded != null && encoded.length() != 0)
    {
        // Use negative look-behind with backslash, because it's used for escaping the separator.
        // Expression is "(?<!\)s" with doubling because of escaping in regex, and again because of escaping in Java).
        String splitter = "(?<!\\\\)" + separator; //$NON-NLS-1$
        String[] parts = encoded.split(splitter);

        // While converting to list, take out the escape characters used to escape the now-removed separator.
        for (int i = 0; i < parts.length; i++)
            items.add(parts[i].replace("\\" + separator, Character.toString(separator)));
    }

    return items;
}

答案 1 :(得分:0)

Set<String> set =list.getStringSet("key", null); Set<String> set = new HashSet<String>(); set.addAll(list of the string list u have); editor.putStringSet("key", set); editor.commit();
有关详细信息,请参阅此主题Save ArrayList to SharedPreferences

答案 2 :(得分:0)

//while storing
str is string array
String fin="";
for(i=0;i<n;i++){
    fin=fin+str[i]+",";
}
fin=fin.substring(0,fin.length()-1);

//while retrieving
List<String> items = Arrays.asList(fin.split("\\s*,\\s*"));