Save ArrayList to SharedPreferences

前端 未结 30 3567
野的像风
野的像风 2020-11-21 04:43

I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves

30条回答
  •  盖世英雄少女心
    2020-11-21 05:00

    I have read all answers above. That is all correct but i found a more easy solution as below:

    1. Saving String List in shared-preference>>

      public static void setSharedPreferenceStringList(Context pContext, String pKey, List 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();
      }
      

      }

    2. and for getting String List from Shared-preference>>

      public static List getSharedPreferenceStringList(Context pContext, String pKey) {
      int size = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getInt(pKey + "size", 0);
      List 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;
      }
      

    Here Constants.APP_PREFS is the name of the file to open; can not contain path separators.

提交回复
热议问题