如何在SharedPreferences中存储整数数组?

时间:2011-08-24 13:03:53

标签: android sharedpreferences

我想使用SharedPreferences保存/调用整数数组,这可能吗?

7 个答案:

答案 0 :(得分:47)

您可以尝试这样做:

  • 将整数放入一个字符串中,用字符分隔每个int,例如逗号,然后将它们保存为字符串:

    SharedPreferences prefs = getPreferences(MODE_PRIVATE);
    int[] list = new int[10];
    StringBuilder str = new StringBuilder();
    for (int i = 0; i < list.length; i++) {
        str.append(list[i]).append(",");
    }
    prefs.edit().putString("string", str.toString());
    
  • 获取字符串并使用StringTokenizer解析它:

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

答案 1 :(得分:14)

您不能将数组放在SharedPreferences中,但您可以解决方法:

private static final String LEN_PREFIX = "Count_";
private static final String VAL_PREFIX = "IntValue_";
public void storeIntArray(String name, int[] array){
    SharedPreferences.Editor edit= mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE).edit();
    edit.putInt(LEN_PREFIX + name, array.length);
    int count = 0;
    for (int i: array){
        edit.putInt(VAL_PREFIX + name + count++, i);
    }
    edit.commit();
}
public int[] getFromPrefs(String name){
    int[] ret;
    SharedPreferences prefs = mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE);
    int count = prefs.getInt(LEN_PREFIX + name, 0);
    ret = new int[count];
    for (int i = 0; i < count; i++){
        ret[i] = prefs.getInt(VAL_PREFIX+ name + i, i);
    }
    return ret;
}

答案 2 :(得分:5)

这是我的版本,基于Egor的回答。我不想使用StringBuilder,除非我正在构建一个令人兴奋的字符串,但感谢Egor使用StringTokenizer - 过去没有太多使用它,但它非常方便!仅供参考,这是我的Utility类:

public static void saveIntListPrefs(
    String name, Activity activity, List<Integer> list)
{
  String s = "";
  for (Integer i : list) {
    s += i + ",";
  }

  Editor editor = activity.getPreferences(Context.MODE_PRIVATE).edit();
  editor.putString(name, s);
  editor.commit();
}

public static ArrayList<Integer> readIntArrayPrefs(String name, Activity activity)
{
  SharedPreferences prefs = activity.getPreferences(Context.MODE_PRIVATE);
  String s = prefs.getString(name, "");
  StringTokenizer st = new StringTokenizer(s, ",");
  ArrayList<Integer> result = new ArrayList<Integer>();
  while (st.hasMoreTokens()) {
    result.add(Integer.parseInt(st.nextToken()));
  }
  return result;
}

答案 3 :(得分:4)

两种解决方案:

(1)使用http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

它具有分割/连接功能,允许您在一个衬垫中连接和分割整数:

StringUtils.join([1, 2, 3], ';')  = "1;2;3"
StringUtils.split("1;2;3", ';')   = ["1", "2", "3"]

但是,您仍然需要将字符串转换回整数。

实际上,对于分割java.lang.String.split()同样可行: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

(2)使用SharedPreferences.putStringSet()(API 11):

    SharedPreferences.Editor editor = preferences.edit();
    int count = this.intSet.size();
    if (count > 0) {
        Set<String> theSet = new HashSet<String>();
        for (Long l : this.intSet) {
            theSet.add(String.valueOf(l));
        }
        editor.putStringSet(PREFS_KEY, theSet);
    } else {
        editor.remove(PREFS_KEY);
    }
    editor.commit();

并将其取回:

    Set<String> theSet = this.preferences.getStringSet(PREFS_KEY, null);
    if (theSet != null && !theSet.isEmpty()) {
        this.intSet.clear();
        for (String s : theSet) {
            this.intSet.add(Integer.valueOf(s));
        }
    }

此代码不捕获NPE或NumberFormatExceptions,因为intSet确保不包含任何空值。但是,当然,如果你不能保证在你的代码中你应该用try / catch包围它。

答案 4 :(得分:2)

I like to use JSON, which can be stored and retrieved as a string, to represent any complex data in SharedPreferences. So, in the case of an int array:

Query queryRef = mReference.child("posts").orderByChild("title").startAt(query).endAt(query + "\uf8ff");
                    queryRef.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {

                            if (dataSnapshot.hasChildren()) {

                                for (DataSnapshot postsSnapshot : dataSnapshot.getChildren()) {
                                    final Post post = postsSnapshot.getValue(Post.class);
 // and the rest ...
..
..
..

The beauty is that the same idea can be applied to any other complex data representable as a JSON.

答案 5 :(得分:0)

您只能在sharedPreference中保存原始值。请改用Sqlite

答案 6 :(得分:0)

以下是“转换为逗号分隔字符串”解决方案在Kotlin中的外观,实现为扩展函数:

putIntArray(String, IntArray)

这样你可以像使用其他put和set方法一样使用getIntArray(String)val prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) prefs.edit().putIntArray(INT_ARRAY_TEST_KEY, intArrayOf(1, 2, 3)).apply() val intArray = prefs.getIntArray(INT_ARRAY_TEST_KEY)

library(devtools)
install_version("foobarbaz", "0.1.2")