Save ArrayList to SharedPreferences

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

    this should work:

    public void setSections (Context c,  List
    sectionList){ this.sectionList = sectionList; Type sectionListType = new TypeToken>(){}.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
    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>(){}.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.

提交回复
热议问题