首页 文章

将ArrayList保存到SharedPreferences

提问于
浏览
272

我有一个 ArrayList 与自定义对象 . 每个自定义对象都包含各种字符串和数字 . 即使用户离开活动然后想要稍后返回,我也需要数组保持不变,但是在应用程序完全关闭后我不需要数组可用 . 我使用 SharedPreferences 以这种方式保存了很多其他对象,但我无法弄清楚如何以这种方式保存整个数组 . 这可能吗?也许 SharedPreferences 不是这样的方法吗?有更简单的方法吗?

30 回答

  • 12

    您可以从FacebookSDK的SharedPreferencesTokenCache类中引用serializeKey()和deserializeKey()函数 . It converts the supportedType into the JSON object and store the JSON string into SharedPreferences . 你可以从here下载SDK

    private void serializeKey(String key, Bundle bundle, SharedPreferences.Editor editor)
        throws JSONException {
        Object value = bundle.get(key);
        if (value == null) {
            // Cannot serialize null values.
            return;
        }
    
        String supportedType = null;
        JSONArray jsonArray = null;
        JSONObject json = new JSONObject();
    
        if (value instanceof Byte) {
            supportedType = TYPE_BYTE;
            json.put(JSON_VALUE, ((Byte)value).intValue());
        } else if (value instanceof Short) {
            supportedType = TYPE_SHORT;
            json.put(JSON_VALUE, ((Short)value).intValue());
        } else if (value instanceof Integer) {
            supportedType = TYPE_INTEGER;
            json.put(JSON_VALUE, ((Integer)value).intValue());
        } else if (value instanceof Long) {
            supportedType = TYPE_LONG;
            json.put(JSON_VALUE, ((Long)value).longValue());
        } else if (value instanceof Float) {
            supportedType = TYPE_FLOAT;
            json.put(JSON_VALUE, ((Float)value).doubleValue());
        } else if (value instanceof Double) {
            supportedType = TYPE_DOUBLE;
            json.put(JSON_VALUE, ((Double)value).doubleValue());
        } else if (value instanceof Boolean) {
            supportedType = TYPE_BOOLEAN;
            json.put(JSON_VALUE, ((Boolean)value).booleanValue());
        } else if (value instanceof Character) {
            supportedType = TYPE_CHAR;
            json.put(JSON_VALUE, value.toString());
        } else if (value instanceof String) {
            supportedType = TYPE_STRING;
            json.put(JSON_VALUE, (String)value);
        } else {
            // Optimistically create a JSONArray. If not an array type, we can null
            // it out later
            jsonArray = new JSONArray();
            if (value instanceof byte[]) {
                supportedType = TYPE_BYTE_ARRAY;
                for (byte v : (byte[])value) {
                    jsonArray.put((int)v);
                }
            } else if (value instanceof short[]) {
                supportedType = TYPE_SHORT_ARRAY;
                for (short v : (short[])value) {
                    jsonArray.put((int)v);
                }
            } else if (value instanceof int[]) {
                supportedType = TYPE_INTEGER_ARRAY;
                for (int v : (int[])value) {
                    jsonArray.put(v);
                }
            } else if (value instanceof long[]) {
                supportedType = TYPE_LONG_ARRAY;
                for (long v : (long[])value) {
                    jsonArray.put(v);
                }
            } else if (value instanceof float[]) {
                supportedType = TYPE_FLOAT_ARRAY;
                for (float v : (float[])value) {
                    jsonArray.put((double)v);
                }
            } else if (value instanceof double[]) {
                supportedType = TYPE_DOUBLE_ARRAY;
                for (double v : (double[])value) {
                    jsonArray.put(v);
                }
            } else if (value instanceof boolean[]) {
                supportedType = TYPE_BOOLEAN_ARRAY;
                for (boolean v : (boolean[])value) {
                    jsonArray.put(v);
                }
            } else if (value instanceof char[]) {
                supportedType = TYPE_CHAR_ARRAY;
                for (char v : (char[])value) {
                    jsonArray.put(String.valueOf(v));
                }
            } else if (value instanceof List<?>) {
                supportedType = TYPE_STRING_LIST;
                @SuppressWarnings("unchecked")
                List<String> stringList = (List<String>)value;
                for (String v : stringList) {
                    jsonArray.put((v == null) ? JSONObject.NULL : v);
                }
            } else {
                // Unsupported type. Clear out the array as a precaution even though
                // it is redundant with the null supportedType.
                jsonArray = null;
            }
        }
    
        if (supportedType != null) {
            json.put(JSON_VALUE_TYPE, supportedType);
            if (jsonArray != null) {
                // If we have an array, it has already been converted to JSON. So use
                // that instead.
                json.putOpt(JSON_VALUE, jsonArray);
            }
    
            String jsonString = json.toString();
            editor.putString(key, jsonString);
        }
    }
    
    private void deserializeKey(String key, Bundle bundle)
            throws JSONException {
        String jsonString = cache.getString(key, "{}");
        JSONObject json = new JSONObject(jsonString);
    
        String valueType = json.getString(JSON_VALUE_TYPE);
    
        if (valueType.equals(TYPE_BOOLEAN)) {
            bundle.putBoolean(key, json.getBoolean(JSON_VALUE));
        } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
            JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
            boolean[] array = new boolean[jsonArray.length()];
            for (int i = 0; i < array.length; i++) {
                array[i] = jsonArray.getBoolean(i);
            }
            bundle.putBooleanArray(key, array);
        } else if (valueType.equals(TYPE_BYTE)) {
            bundle.putByte(key, (byte)json.getInt(JSON_VALUE));
        } else if (valueType.equals(TYPE_BYTE_ARRAY)) {
            JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
            byte[] array = new byte[jsonArray.length()];
            for (int i = 0; i < array.length; i++) {
                array[i] = (byte)jsonArray.getInt(i);
            }
            bundle.putByteArray(key, array);
        } else if (valueType.equals(TYPE_SHORT)) {
            bundle.putShort(key, (short)json.getInt(JSON_VALUE));
        } else if (valueType.equals(TYPE_SHORT_ARRAY)) {
            JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
            short[] array = new short[jsonArray.length()];
            for (int i = 0; i < array.length; i++) {
                array[i] = (short)jsonArray.getInt(i);
            }
            bundle.putShortArray(key, array);
        } else if (valueType.equals(TYPE_INTEGER)) {
            bundle.putInt(key, json.getInt(JSON_VALUE));
        } else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
            JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
            int[] array = new int[jsonArray.length()];
            for (int i = 0; i < array.length; i++) {
                array[i] = jsonArray.getInt(i);
            }
            bundle.putIntArray(key, array);
        } else if (valueType.equals(TYPE_LONG)) {
            bundle.putLong(key, json.getLong(JSON_VALUE));
        } else if (valueType.equals(TYPE_LONG_ARRAY)) {
            JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
            long[] array = new long[jsonArray.length()];
            for (int i = 0; i < array.length; i++) {
                array[i] = jsonArray.getLong(i);
            }
            bundle.putLongArray(key, array);
        } else if (valueType.equals(TYPE_FLOAT)) {
            bundle.putFloat(key, (float)json.getDouble(JSON_VALUE));
        } else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
            JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
            float[] array = new float[jsonArray.length()];
            for (int i = 0; i < array.length; i++) {
                array[i] = (float)jsonArray.getDouble(i);
            }
            bundle.putFloatArray(key, array);
        } else if (valueType.equals(TYPE_DOUBLE)) {
            bundle.putDouble(key, json.getDouble(JSON_VALUE));
        } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
            JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
            double[] array = new double[jsonArray.length()];
            for (int i = 0; i < array.length; i++) {
                array[i] = jsonArray.getDouble(i);
            }
            bundle.putDoubleArray(key, array);
        } else if (valueType.equals(TYPE_CHAR)) {
            String charString = json.getString(JSON_VALUE);
            if (charString != null && charString.length() == 1) {
                bundle.putChar(key, charString.charAt(0));
            }
        } else if (valueType.equals(TYPE_CHAR_ARRAY)) {
            JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
            char[] array = new char[jsonArray.length()];
            for (int i = 0; i < array.length; i++) {
                String charString = jsonArray.getString(i);
                if (charString != null && charString.length() == 1) {
                    array[i] = charString.charAt(0);
                }
            }
            bundle.putCharArray(key, array);
        } else if (valueType.equals(TYPE_STRING)) {
            bundle.putString(key, json.getString(JSON_VALUE));
        } else if (valueType.equals(TYPE_STRING_LIST)) {
            JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
            int numStrings = jsonArray.length();
            ArrayList<String> stringList = new ArrayList<String>(numStrings);
            for (int i = 0; i < numStrings; i++) {
                Object jsonStringValue = jsonArray.get(i);
                stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String)jsonStringValue);
            }
            bundle.putStringArrayList(key, stringList);
        }
    }
    
  • 2

    当应用程序被真正杀死时,为什么要销毁't you stick your arraylist on an Application class? It only get',因此,只要应用程序可用,它就会一直存在 .

  • 2

    在API 11之后 SharedPreferences Editor 接受 Sets . 您可以将列表转换为 HashSet 或类似的东西并将其存储 . 当你回读它时,把它转换成 ArrayList ,如果需要你可以对它进行排序,你就可以了 .

    //Retrieve the values
    Set<String> set = myScores.getStringSet("key", null);
    
    //Set the values
    Set<String> set = new HashSet<String>();
    set.addAll(listOfExistingScores);
    scoreEditor.putStringSet("key", set);
    scoreEditor.commit();
    

    您也可以序列化 ArrayList ,然后将其保存/读取到 SharedPreferences . 以下是解决方案:

    EDIT:
    好的,下面是将 ArrayList 作为序列化对象保存到 SharedPreferences 的解决方案,然后从SharedPreferences中读取它 .

    因为API仅支持在SharedPreferences中存储和检索字符串(在API 11之后,它更简单),我们必须将具有任务列表的ArrayList对象序列化和反序列化为字符串 .

    在TaskManagerApplication类的 addTask() 方法中,我们必须获取共享首选项的实例,然后使用 putString() 方法存储序列化的ArrayList:

    public void addTask(Task t) {
      if (null == currentTasks) {
        currentTasks = new ArrayList<task>();
      }
      currentTasks.add(t);
    
      // save the task list to preference
      SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
      Editor editor = prefs.edit();
      try {
        editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
      } catch (IOException e) {
        e.printStackTrace();
      }
      editor.commit();
    }
    

    同样,我们必须从 onCreate() 方法中的首选项中检索任务列表:

    public void onCreate() {
      super.onCreate();
      if (null == currentTasks) {
        currentTasks = new ArrayList<task>();
      }
    
      // load tasks from preference
      SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
    
      try {
        currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
      } catch (IOException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
    

    你可以从Apache Pig项目获得 ObjectSerializerObjectSerializer.java

  • 4

    使用这个对象 - > TinyDB--Android-Shared-Preferences-Turbo很简单 .

    TinyDB tinydb = new TinyDB(context);
    

    放在

    tinydb.putList("MyUsers", mUsersArray);
    

    要得到

    tinydb.getList("MyUsers");
    
  • 7

    在_849778中保存 Array

    public static boolean saveArray()
    {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor mEdit1 = sp.edit();
        /* sKey is an array */
        mEdit1.putInt("Status_size", sKey.size());  
    
        for(int i=0;i<sKey.size();i++)  
        {
            mEdit1.remove("Status_" + i);
            mEdit1.putString("Status_" + i, sKey.get(i));  
        }
    
        return mEdit1.commit();     
    }
    

    SharedPreferences 加载 Array 数据

    public static void loadArray(Context mContext)
    {  
        SharedPreferences mSharedPreference1 =   PreferenceManager.getDefaultSharedPreferences(mContext);
        sKey.clear();
        int size = mSharedPreference1.getInt("Status_size", 0);  
    
        for(int i=0;i<size;i++) 
        {
         sKey.add(mSharedPreference1.getString("Status_" + i, null));
        }
    
    }
    
  • 90

    您可以将其转换为 JSON String 并将字符串存储在 SharedPreferences 中 .

  • 2

    正如@nirav所说,最好的解决方案是使用Gson实用程序类将它作为json文本存储在sharedPrefernces中 . 下面的示例代码:

    //Retrieve the values
    Gson gson = new Gson();
    String jsonText = Prefs.getString("key", null);
    String[] text = gson.fromJson(jsonText, String[].class);  //EDIT: gso to gson
    
    
    //Set the values
    Gson gson = new Gson();
    List<String> textList = new ArrayList<String>();
    textList.addAll(data);
    String jsonText = gson.toJson(textList);
    prefsEditor.putString("key", jsonText);
    prefsEditor.apply();
    
  • 3

    嘿朋友我没有使用 Gson 库就得到了上述问题的解决方案 . 在这里我发布源代码 .

    1.变量声明,即

    SharedPreferences shared;
      ArrayList<String> arrPackage;
    

    2.可变初始化即

    shared = getSharedPreferences("App_settings", MODE_PRIVATE);
     // add values for your ArrayList any where...
     arrPackage = new ArrayList<>();
    

    3.使用 packagesharedPreferences() 将值存储到sharedPreference:

    private void packagesharedPreferences() {
       SharedPreferences.Editor editor = shared.edit();
       Set<String> set = new HashSet<String>();
       set.addAll(arrPackage);
       editor.putStringSet("DATE_LIST", set);
       editor.apply();
       Log.d("storesharedPreferences",""+set);
     }
    

    4.使用 retriveSharedValue() 传递sharedPreference的值:

    private void retriveSharedValue() {
       Set<String> set = shared.getStringSet("DATE_LIST", null);
       arrPackage.addAll(set);
       Log.d("retrivesharedPreferences",""+set);
     }
    

    我希望它对你有帮助...

  • 0

    Android SharedPreferances允许您将内存类型(自API11以来可用的布尔,浮点数,整数,长整数,字符串和字符串集)保存为内存中的xml文件 .

    任何解决方案的关键思想是将数据转换为其中一种原始类型 .

    我个人喜欢将我的列表转换为json格式,然后将其保存为SharedPreferences值中的String .

    要使用我的解决方案,您必须添加Google Gson lib .

    在gradle中只需添加以下依赖项(请使用google的最新版本):

    compile 'com.google.code.gson:gson:2.6.2'
    

    保存数据(HttpParam是你的对象):

    List<HttpParam> httpParamList = "**get your list**"
    String httpParamJSONList = new Gson().toJson(httpParamList);
    
    SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(**"your_prefes_key"**, httpParamJSONList);
    
    editor.apply();
    

    检索数据(HttpParam是你的对象):

    SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
    String httpParamJSONList = prefs.getString(**"your_prefes_key"**, ""); 
    
    List<HttpParam> httpParamList =  
    new Gson().fromJson(httpParamJSONList, new TypeToken<List<HttpParam>>() {
                }.getType());
    
  • 1

    您还可以将arraylist转换为String并优先保存

    private String convertToString(ArrayList<String> list) {
    
                StringBuilder sb = new StringBuilder();
                String delim = "";
                for (String s : list)
                {
                    sb.append(delim);
                    sb.append(s);;
                    delim = ",";
                }
                return sb.toString();
            }
    
    private ArrayList<String> convertToArray(String string) {
    
                ArrayList<String> list = new ArrayList<String>(Arrays.asList(string.split(",")));
                return list;
            }
    

    您可以使用 convertToString 方法将Arraylist转换为字符串后保存它并检索字符串并使用 convertToArray 将其转换为数组

    在API 11之后,您可以将set直接保存到SharedPreferences尽管!!! :)

  • 0

    最好的方法是使用GSON转换为JSOn字符串并将此字符串保存到SharedPreference . 我也用这种方式缓存响应 .

  • 2

    我已经阅读了上面的所有答案 . 这一切都是正确的,但我找到了一个更简单的解决方案如下:

    • 在共享首选项中保存字符串列表>>
    public static void setSharedPreferenceStringList(Context pContext, String pKey, List<String> pData) {
    SharedPreferences.Editor editor = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit();
    editor.putInt(pKey + "size", pData.size());
    editor.commit();
    
    for (int i = 0; i < pData.size(); i++) {
        SharedPreferences.Editor editor1 = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit();
        editor1.putString(pKey + i, (pData.get(i)));
        editor1.commit();
    }
    

    }

    • 以及从共享首选项>>获取字符串列表
    public static List<String> getSharedPreferenceStringList(Context pContext, String pKey) {
    int size = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getInt(pKey + "size", 0);
    List<String> list = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        list.add(pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getString(pKey + i, ""));
    }
    return list;
    }
    

    这里 Constants.APP_PREFS 是要打开的文件的名称;不能包含路径分隔符 .

  • 2

    我能找到的最好的方法是制作一个2D数组键,并将数组的自定义项放在二维数组键中,然后在启动时通过2D arra检索它 . 我不喜欢使用字符串集的想法,因为大多数Android用户仍然使用Gingerbread并且使用字符串集需要使用蜂窝 .

    示例代码:这里ditor是共享的pref编辑器,rowitem是我的自定义对象 .

    editor.putString(genrealfeedkey[j][1], Rowitemslist.get(j).getname());
            editor.putString(genrealfeedkey[j][2], Rowitemslist.get(j).getdescription());
            editor.putString(genrealfeedkey[j][3], Rowitemslist.get(j).getlink());
            editor.putString(genrealfeedkey[j][4], Rowitemslist.get(j).getid());
            editor.putString(genrealfeedkey[j][5], Rowitemslist.get(j).getmessage());
    
  • 1

    下面的代码是接受的答案,还有一些新人(我)的行,例如 . 展示了如何将set类型对象转换回arrayList,以及有关'.putStringSet'和'.getStringSet'之前的内容的其他指导 . (谢谢你)

    // shared preferences
       private SharedPreferences preferences;
       private SharedPreferences.Editor nsuserdefaults;
    
    // setup persistent data
            preferences = this.getSharedPreferences("MyPreferences", MainActivity.MODE_PRIVATE);
            nsuserdefaults = preferences.edit();
    
            arrayOfMemberUrlsUserIsFollowing = new ArrayList<String>();
            //Retrieve followers from sharedPreferences
            Set<String> set = preferences.getStringSet("following", null);
    
            if (set == null) {
                // lazy instantiate array
                arrayOfMemberUrlsUserIsFollowing = new ArrayList<String>();
            } else {
                // there is data from previous run
                arrayOfMemberUrlsUserIsFollowing = new ArrayList<>(set);
            }
    
    // convert arraylist to set, and save arrayOfMemberUrlsUserIsFollowing to nsuserdefaults
                    Set<String> set = new HashSet<String>();
                    set.addAll(arrayOfMemberUrlsUserIsFollowing);
                    nsuserdefaults.putStringSet("following", set);
                    nsuserdefaults.commit();
    
  • 0
    //Set the values
    intent.putParcelableArrayListExtra("key",collection);
    
    //Retrieve the values
    ArrayList<OnlineMember> onlineMembers = data.getParcelableArrayListExtra("key");
    
  • 381

    别忘了实施序列化:

    Class dataBean implements Serializable{
     public String name;
    }
    ArrayList<dataBean> dataBeanArrayList = new ArrayList();
    

    https://stackoverflow.com/a/7635154/4639974

  • 19

    此方法用于存储/保存数组列表: -

    public static void saveSharedPreferencesLogList(Context context, List<String> collageList) {
                SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                Gson gson = new Gson();
                String json = gson.toJson(collageList);
                prefsEditor.putString("myJson", json);
                prefsEditor.commit();
            }
    

    此方法用于检索数组列表: -

    public static List<String> loadSharedPreferencesLogList(Context context) {
            List<String> savedCollage = new ArrayList<String>();
            SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
            Gson gson = new Gson();
            String json = mPrefs.getString("myJson", "");
            if (json.isEmpty()) {
                savedCollage = new ArrayList<String>();
            } else {
                Type type = new TypeToken<List<String>>() {
                }.getType();
                savedCollage = gson.fromJson(json, type);
            }
    
            return savedCollage;
        }
    
  • 39

    您可以将其转换为 Map 对象来存储它,然后在检索 SharedPreferences 时将值更改回ArrayList .

  • 0

    您可以使用序列化或Gson库将列表转换为字符串,反之亦然,然后在首选项中保存字符串 .

    使用谷歌的Gson库:

    //Converting list to string
    new Gson().toJson(list);
    
    //Converting string to list
    new Gson().fromJson(listString, CustomObjectsList.class);
    

    使用Java序列化:

    //Converting list to string
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(list);
    oos.flush();
    String string = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
    oos.close();
    bos.close();
    return string;
    
    //Converting string to list
    byte[] bytesArray = Base64.decode(familiarVisitsString, Base64.DEFAULT);
    ByteArrayInputStream bis = new ByteArrayInputStream(bytesArray);
    ObjectInputStream ois = new ObjectInputStream(bis);
    Object clone = ois.readObject();
    ois.close();
    bis.close();
    return (CustomObjectsList) clone;
    
  • 1

    使用此自定义类:

    public class SharedPreferencesUtil {
    
        public static void pushStringList(SharedPreferences sharedPref, 
                                          List<String> list, String uniqueListName) {
    
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putInt(uniqueListName + "_size", list.size());
    
            for (int i = 0; i < list.size(); i++) {
                editor.remove(uniqueListName + i);
                editor.putString(uniqueListName + i, list.get(i));
            }
            editor.apply();
        }
    
        public static List<String> pullStringList(SharedPreferences sharedPref, 
                                                  String uniqueListName) {
    
            List<String> result = new ArrayList<>();
            int size = sharedPref.getInt(uniqueListName + "_size", 0);
    
            for (int i = 0; i < size; i++) {
                result.add(sharedPref.getString(uniqueListName + i, null));
            }
            return result;
        }
    }
    

    如何使用:

    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    SharedPreferencesUtil.pushStringList(sharedPref, list, getString(R.string.list_name));
    List<String> list = SharedPreferencesUtil.pullStringList(sharedPref, getString(R.string.list_name));
    
  • 1

    You can save String and custom array list using Gson library.

    =>First you need to create function to save array list to SharedPreferences.

    public void saveListInLocal(ArrayList<String> list, String key) {
    
            SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            Gson gson = new Gson();
            String json = gson.toJson(list);
            editor.putString(key, json);
            editor.apply();     // This line is IMPORTANT !!!
    
        }
    

    => You need to create function to get array list from SharedPreferences.

    public ArrayList<String> getListFromLocal(String key)
    {
        SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
        Gson gson = new Gson();
        String json = prefs.getString(key, null);
        Type type = new TypeToken<ArrayList<String>>() {}.getType();
        return gson.fromJson(json, type);
    
    }
    

    => How to call save and retrieve array list function.

    ArrayList<String> listSave=new ArrayList<>();
    listSave.add("test1"));
    listSave.add("test2"));
    saveListInLocal(listSave,"key");
    Log.e("saveArrayList:","Save ArrayList success");
    ArrayList<String> listGet=new ArrayList<>();
    listGet=getListFromLocal("key");
    Log.e("getArrayList:","Get ArrayList size"+listGet.size());
    

    =>不要忘记在app level build.gradle中添加gson库 .

    实现'com.google.code.gson:gson:2.8.2'

  • 90

    还有Kotlin:

    fun SharedPreferences.Editor.putIntegerArrayList(key: String, list: ArrayList<Int>?): SharedPreferences.Editor {
        putString(key, list?.joinToString(",") ?: "")
        return this
    }
    
    fun SharedPreferences.getIntegerArrayList(key: String, defValue: ArrayList<Int>?): ArrayList<Int>? {
        val value = getString(key, null)
        if (value.isNullOrBlank())
            return defValue
        return value.split(",").map { it.toInt() }.toArrayList()
    }
    
  • 57

    我的utils类保存列表为 SharedPreferences

    public class SharedPrefApi {
        private SharedPreferences sharedPreferences;
        private Gson gson;
    
        public SharedPrefApi(Context context, Gson gson) {
            this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            this.gson = gson;
        } 
    
        ...
    
        public <T> void putList(String key, List<T> list) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(key, gson.toJson(list));
            editor.apply();
        }
    
        public <T> List<T> getList(String key, Class<T> clazz) {
            Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
            return gson.fromJson(getString(key, null), typeOfT);
        }
    }
    

    运用

    // for save
    sharedPrefApi.putList(SharedPrefApi.Key.USER_LIST, userList);
    
    // for retrieve
    List<User> userList = sharedPrefApi.getList(SharedPrefApi.Key.USER_LIST, User.class);
    

    .
    Full code of my utils //使用活动代码中的示例进行检查

  • 4
    public  void saveUserName(Context con,String username)
        {
            try
            {
                usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
                usernameEditor = usernameSharedPreferences.edit();
                usernameEditor.putInt(PREFS_KEY_SIZE,(USERNAME.size()+1)); 
                int size=USERNAME.size();//USERNAME is arrayList
                usernameEditor.putString(PREFS_KEY_USERNAME+size,username);
                usernameEditor.commit();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
    
        }
        public void loadUserName(Context con)
        {  
            try
            {
                usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
                size=usernameSharedPreferences.getInt(PREFS_KEY_SIZE,size);
                USERNAME.clear();
                for(int i=0;i<size;i++)
                { 
                    String username1="";
                    username1=usernameSharedPreferences.getString(PREFS_KEY_USERNAME+i,username1);
                    USERNAME.add(username1);
                }
                usernameArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, USERNAME);
                username.setAdapter(usernameArrayAdapter);
                username.setThreshold(0);
    
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    
  • 0

    所有上述答案都是正确的 . :)我自己在我的情况中使用其中一个 . 然而,当我读到这个问题时,我发现OP实际上是在讨论与本文 Headers 不同的场景,如果我没有弄错的话 .

    "I need the array to stick around even if the user leaves the activity and then wants to come back at a later time"

    他实际上希望存储数据直到应用程序打开,而不管用户在应用程序中更改屏幕 .

    "however I don't need the array available after the application has been closed completely"

    但是一旦关闭应用程序,就不应该保留数据 . 因此我觉得使用 SharedPreferences 并不是最佳方法 .

    可以为此要求做的是创建一个扩展 Application 类的类 .

    public class MyApp extends Application {
    
        //Pardon me for using global ;)
    
        private ArrayList<CustomObject> globalArray;
    
        public void setGlobalArrayOfCustomObjects(ArrayList<CustomObject> newArray){
            globalArray = newArray; 
        }
    
        public ArrayList<CustomObject> getGlobalArrayOfCustomObjects(){
            return globalArray;
        }
    
    }
    

    使用setter和getter,可以使用Application从任何地方访问ArrayList . 最好的部分是应用程序关闭后,我们不必担心存储的数据 . :)

  • 1

    SharedPreferences中使用getStringSet和putStringSet非常简单,但在我的情况下,我必须复制Set对象才能向Set中添加任何内容 . 否则,如果我的应用程序强制关闭,则不会保存该设置 . 可能是因为以下API中的注释 . (如果应用程序被后退按钮关闭,它保存了) .

    请注意,您不得修改此调用返回的set实例 . 如果您这样做,则无法保证存储数据的一致性,也无法完全修改实例 . http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    SharedPreferences.Editor editor = prefs.edit();
    
    Set<String> outSet = prefs.getStringSet("key", new HashSet<String>());
    Set<String> workingSet = new HashSet<String>(outSet);
    workingSet.add("Another String");
    
    editor.putStringSet("key", workingSet);
    editor.commit();
    
  • 0

    从SharedPreference保存和检索ArrayList

    public static void addToPreference(String id,Context context) {
            SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
            ArrayList<String> list = getListFromPreference(context);
            if (!list.contains(id)) {
                list.add(id);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                Set<String> set = new HashSet<>();
                set.addAll(list);
                edit.putStringSet(Constant.LIST, set);
                edit.commit();
    
            }
        }
        public static ArrayList<String> getListFromPreference(Context context) {
            SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
            Set<String> set = sharedPreferences.getStringSet(Constant.LIST, null);
            ArrayList<String> list = new ArrayList<>();
            if (set != null) {
                list = new ArrayList<>(set);
            }
            return list;
        }
    
  • 2

    使用Kotlin,对于简单的数组和列表,您可以执行以下操作:

    class MyPrefs(context: Context) {
        val prefs = context.getSharedPreferences("x.y.z.PREFS_FILENAME", 0)
        var listOfFloats: List<Float>
            get() = prefs.getString("listOfFloats", "").split(",").map { it.toFloat() }
            set(value) = prefs.edit().putString("listOfFloats", value.joinToString(",")).apply()
    }
    

    然后轻松访问首选项:

    MyPrefs(context).listOfFloats = ....
    val list = MyPrefs(context).listOfFloats
    
  • 1

    我使用相同的方式保存和检索字符串,但在这里使用arrayList我使用HashSet作为中介

    要将arrayList保存到SharedPreferences,我们使用HashSet:

    1-我们创建SharedPreferences变量(在数组发生更改的位置)

    2 - 我们将arrayList转换为HashSet

    3 - 然后我们把stringSet和apply

    4 - 在HashSet中使用getStringSet并重新创建ArrayList以设置HashSet .

    公共类MainActivity扩展AppCompatActivity {ArrayList arrayList = new ArrayList <>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        SharedPreferences prefs = this.getSharedPreferences("com.example.nec.myapplication", Context.MODE_PRIVATE);
    
        HashSet<String> set = new HashSet(arrayList);
        prefs.edit().putStringSet("names", set).apply();
    
    
        set = (HashSet<String>) prefs.getStringSet("names", null);
        arrayList = new ArrayList(set);
    
        Log.i("array list", arrayList.toString());
    }
    
  • 0

    这应该工作:

    public void setSections (Context c,  List<Section> sectionList){
        this.sectionList = sectionList;
    
        Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
        String sectionListString = new Gson().toJson(sectionList,sectionListType);
    
        SharedPreferences.Editor editor = getSharedPreferences(c).edit().putString(PREFS_KEY_SECTIONS, sectionListString);
        editor.apply();
    }
    

    他们,只是 grab 它:

    public List<Section> getSections(Context c){
    
        if(this.sectionList == null){
            String sSections = getSharedPreferences(c).getString(PREFS_KEY_SECTIONS, null);
    
            if(sSections == null){
                return new ArrayList<>();
            }
    
            Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
            try {
    
                this.sectionList = new Gson().fromJson(sSections, sectionListType);
    
                if(this.sectionList == null){
                    return new ArrayList<>();
                }
            }catch (JsonSyntaxException ex){
    
                return new ArrayList<>();
    
            }catch (JsonParseException exc){
    
                return new ArrayList<>();
            }
        }
        return this.sectionList;
    }
    

    这个对我有用 .

相关问题