Save ArrayList to SharedPreferences

前端 未结 30 3710
野的像风
野的像风 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条回答
  •  猫巷女王i
    2020-11-21 05:25

    following code is the accepted answer, with a few more lines for new folks (me), eg. shows how to convert the set type object back to arrayList, and additional guidance on what goes before '.putStringSet' and '.getStringSet'. (thank you evilone)

    // 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();
            //Retrieve followers from sharedPreferences
            Set set = preferences.getStringSet("following", null);
    
            if (set == null) {
                // lazy instantiate array
                arrayOfMemberUrlsUserIsFollowing = new ArrayList();
            } else {
                // there is data from previous run
                arrayOfMemberUrlsUserIsFollowing = new ArrayList<>(set);
            }
    
    // convert arraylist to set, and save arrayOfMemberUrlsUserIsFollowing to nsuserdefaults
                    Set set = new HashSet();
                    set.addAll(arrayOfMemberUrlsUserIsFollowing);
                    nsuserdefaults.putStringSet("following", set);
                    nsuserdefaults.commit();
    

提交回复
热议问题