字符串[]阵列保存并在关闭应用程序后检索



我一直在尝试找出应用程序关闭并在再次打开时将其检索相同的字符串信息后保存字符串数组的最佳方法。上下文是我已经找到了如何从网站解析数据并将其存储在字符串数组中,但是我希望能够保存字符串数组,而用户没有Internet访问字符串数组可以被检索。

这是在Java的Android Studios中完成的 - 只是使该清晰

我一直在研究共享流程方法,但没有工作解决方案。如果有人能帮助我,我将不胜感激!

说字符串数组是:

String[] webValues = new String[(this value can be very large)];

我希望存储整个字符串数组并检索整个字符串数组,然后能够通过活动中的特定索引调用数组。

我不认为SharedPreferences允许您编写一个数组,因此您必须使用putString函数单独编写每个值,或者在API级别11或以后您可以使用putStringSet函数保存一个字符串的Set,但如果将Array转换为Set,这将删除任何重复项。我建议您的情况是将每个字符串单独存储使用索引作为密钥,因此,类似的事情应该为您保存数据

而作用。
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);  
    String array[] = new String[size];  
    for(int i=0;i<size;i++)  
        array[i] = prefs.getString(arrayName + "_" + i, null);  
    return array;  
}  

从这篇文章中获取的是,可以在https://stackoverflow.com/users/833622/sherif-elkhatib

上添加数组或对象。

使用arraylist代替字符串数组,很容易。

然后将您的ArrayList转换为集合并使用以下方式:

   SharedPreferences.Editor editor = shared.edit();
   Set<String> set = new HashSet<String>();
   set.addAll(yourArrayList);
   editor.putStringSet("values", set);
   editor.apply();

获得值:

 List<String> yourValues = new ArrayList();
    Set<String> set = shared.getStringSet("values", null);
    yourValues.addAll(set);

最新更新