Save an arraylist of Strings to shared preferences

后端 未结 4 1422
独厮守ぢ
独厮守ぢ 2020-12-10 14:00

What is the best way to save an ArrayList of strings to SharedPreferences in API level 8? The only way i can think of now is to save all of the str

4条回答
  •  清歌不尽
    2020-12-10 14:34

    If you can guarantee your Strings in ArrayList don't contain comma, you can simply use

    List list = new ArrayList();
    ...
    editor.putString(PREF_KEY_STRINGS, TextUtils.join(",", list));
    

    and to read the list

    String serialized = prefs.getString(PREF_KEY_STRINGS, null);
    List list = Arrays.asList(TextUtils.split(serialized, ","));
    

    You are limited by the memory of the device. It's good practice to use background thread to read/write shared preferences.

提交回复
热议问题