Save ArrayList to SharedPreferences

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

    My utils class for save list to 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);
        }
    }
    

    Using

    // 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 // check using example in Activity code

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

    This method is used to store/save array list:-

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

    This method is used to retrieve array list:-

    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;
        }
    
    0 讨论(0)
  • 2020-11-21 05:22
    /**
     *     Save and get ArrayList in SharedPreference
     */
    

    JAVA:

    public void saveArrayList(ArrayList<String> list, String key){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        editor.putString(key, json);
        editor.apply();    
    
    }
    
    public ArrayList<String> getArrayList(String key){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        Gson gson = new Gson();
        String json = prefs.getString(key, null);
        Type type = new TypeToken<ArrayList<String>>() {}.getType();
        return gson.fromJson(json, type);
    }
    

    Kotlin

    fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {
        val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
        val editor: Editor = prefs.edit()
        val gson = Gson()
        val json: String = gson.toJson(list)
        editor.putString(key, json)
        editor.apply()
    }
    
    fun getArrayList(key: String?): java.util.ArrayList<String?>? {
        val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
        val gson = Gson()
        val json: String = prefs.getString(key, null)
        val type: Type = object : TypeToken<java.util.ArrayList<String?>?>() {}.getType()
        return gson.fromJson(json, type)
    }
    
    0 讨论(0)
  • 2020-11-21 05:24

    Android SharedPreferances allow you to save primitive types (Boolean, Float, Int, Long, String and StringSet which available since API11) in memory as an xml file.

    The key idea of any solution would be to convert the data to one of those primitive types.

    I personally love to convert the my list to json format and then save it as a String in a SharedPreferences value.

    In order to use my solution you'll have to add Google Gson lib.

    In gradle just add the following dependency (please use google's latest version):

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

    Save data (where HttpParam is your object):

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

    Retrieve Data (where HttpParam is your object):

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

    I used the same manner of saving and retrieving a String but here with arrayList I've used HashSet as a mediator

    To save arrayList to SharedPreferences we use HashSet:

    1- we create SharedPreferences variable (in place where the change happens to the array)

    2 - we convert the arrayList to HashSet

    3 - then we put the stringSet and apply

    4 - you getStringSet within HashSet and recreate ArrayList to set the HashSet.

    public class MainActivity extends AppCompatActivity {
        ArrayList<String> 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 讨论(0)
  • 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<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 讨论(0)
提交回复
热议问题