我有一个字符串数组,我需要用 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)
最佳答案
好吧,你可以使用 putStringSet() ,但 (a) 它仅从 API 级别 11 开始,并且 (b) 正如其名称所示,它用于 sets (这意味着您将丢失原始顺序和数组中存在的任何重复项) .
我们通过将集合“编码”为字符串并使用 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;
}
关于android - 如何使用 SharedPreferences 保存字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23725502/