在SharedPreferences中保存任意长度的数组 - Android

时间:2013-08-09 16:37:54

标签: android sharedpreferences

我的目标是在用户点击按钮时保存在EditText中输入的字段;在这种情况下,它是一个IP地址。这个想法是在用户关注EditText时显示所有有效输入IP的列表,类似于已保存的搜索。

我找到了这段有用的代码。我需要一些帮助来解释它。代码运行String[] array中所有元素的putString,我认为它是EditText中所有提交字段的集合。如果一次只添加一个字段,如何创建此数组?我需要解释下面发生的事情。

public boolean saveArray(String[] array, String arrayName, Context mContext) {   
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    SharedPreferences.Editor editor = prefs.edit();  
    editor.putInt(arrayName +"_size", array.length);  
    for(int i = 0;i < array.length; i++){ 
        editor.putString(arrayName + "_" + i, array[i]);  
    }
    return editor.commit();
}

public String[] loadArray(String arrayName, Context mContext) {  
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    int size = prefs.getInt(arrayName + "_size", 0);  
    array = new String[size];  
    for(int i=0;i<size;i++)  
        array[i] = prefs.getString(arrayName + "_" + i, null);  
    return array;  
}

2 个答案:

答案 0 :(得分:1)

根据您的要求和您引用的代码,我得到以下想法:

未经测试的错误:

public boolean saveoneData(String oneTimeData, String key, Context mContext) {   
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0); 

    int size = prefs.getInt(key+"_size", 0); // For the first time it gives the default value(0)

    SharedPreferences.Editor editor = prefs.edit(); 

    editor.putString(key+ "_" + size, oneTimeData);   
    editor.putInt(key+"_size", ++size);  // Here everytime you add the data, the size increments.


    return editor.commit();
}

public String[] loadArray(String key, Context mContext) {  
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    int size = prefs.getInt(key+ "_size", 0);  
    array = new String[size];  
    for(int i=0;i<size;i++)  
        array[i] = prefs.getString(key+ "_" + i, null);  
    return array;  
}

但我通常不会将sharedpreferences用于大量数据存储,因为随着数据的增加,这会使data creation, retrieval and data modifications变得困难。希望这是你想要的。

答案 1 :(得分:1)

在一个String []数组或EditTextList<String>中收集所有Set<String>;值后 您不需要将每个数组值保存为SharedPreferences中的单独键值对。有更简单的保存方法,即创建Set<String>并将所有值保存在一个键下:

editor.putStringSet(arrayName, new HashSet<String>(Arrays.asList(array));

对于检索,您可以采用相同的方式将其检索为Set<String>

Set<String> ipsSet = sharedPrefs.getStringSet(arrayName, null);

What is happening in the code you posted: 同样,String数组的每个值都单独保存在唯一键和数组的大小下。 同样地,稍后检索每个项目,移动范围为0到saved size of the array,这是从SharedPreferences

的第一个位置检索的