Save ArrayList to SharedPreferences

前端 未结 30 3637
野的像风
野的像风 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

    Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple.

    TinyDB tinydb = new TinyDB(context);
    

    to put

    tinydb.putList("MyUsers", mUsersArray);
    

    to get

    tinydb.getList("MyUsers");
    

    UPDATE

    Some useful examples and troubleshooting might be found here: Android Shared Preference TinyDB putListObject frunction

    0 讨论(0)
  • 2020-11-21 05:00

    For String, int, boolean, the best choice would be sharedPreferences.

    If you want to store ArrayList or any complex data. The best choice would be Paper library.

    Add dependency

    implementation 'io.paperdb:paperdb:2.6'
    

    Initialize Paper

    Should be initialized once in Application.onCreate():

    Paper.init(context);
    

    Save

    List<Person> contacts = ...
    Paper.book().write("contacts", contacts);
    

    Loading Data

    Use default values if object doesn't exist in the storage.

    List<Person> contacts = Paper.book().read("contacts", new ArrayList<>());
    

    Here you go.

    https://github.com/pilgr/Paper

    0 讨论(0)
  • 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<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();
      }
      

      }

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

      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;
      }
      

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

    0 讨论(0)
  • 2020-11-21 05:00

    The best way i have been able to find is a make a 2D Array of keys and put the custom items of the array in the 2-D array of keys and then retrieve it through the 2D arra on startup. I did not like the idea of using string set because most of the android users are still on Gingerbread and using string set requires honeycomb.

    Sample Code: here ditor is the shared pref editor and rowitem is my custom object.

    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());
    
    0 讨论(0)
  • 2020-11-21 05:00

    this should work:

    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();
    }
    

    them, to catch it just:

    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;
    }
    

    it works for me.

    0 讨论(0)
  • 2020-11-21 05:04

    Hey friends I got the solution of above problem without using Gson library. Here I post source code.

    1.Variable declaration i.e

      SharedPreferences shared;
      ArrayList<String> arrPackage;
    

    2.Variable initialization i.e

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

    3.Store value to sharedPreference using packagesharedPreferences():

     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.Retrive value of sharedPreference using retriveSharedValue():

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

    I hope it will helpful for you...

    0 讨论(0)
提交回复
热议问题