Search code examples
javaandroidarraylistandroid-sharedpreferences

How to save custom ArrayList by using the SharedPreference?


I wanna know how to save custom ArrayList into Android Phone. Because it used to it at the filter activity. I should keep this information into anywhere.

ArrayList<ListAdapterItemsSelected> mSelectedList = new ArrayList<ListAdapterItemsSelected>();

public class ListAdapterItemsSelected {
    public String  sText;
    public boolean bSelected;

    public String getsText() {
        return sText;
    }

    public void setsText(String sText) {
        this.sText = sText;
    }


    public boolean isbSelected() {
        return bSelected;
    }


    public void setbSelected(boolean bSelected) {
        this.bSelected = bSelected;
    }  

    public ListAdapterItemsSelected(String _text, boolean _selected) {
        sText = _text;
        bSelected = _selected;
    }
}

Solution

  • Use GSON

    Gson gson = new Gson();
    
    ArrayList<ListAdapterItemsSelected> mSelectedList = new ArrayList<ListAdapterItemsSelected>();
    String jsonString = gson.toJson(mSelectedList);
    SharedPreferences sp = context.getSharedPreferences("KEY", Context.MODE_PRIVATE);
    
    //Save to SharedPreferences
    sp.edit().putString("KEY", jsonString).commit();
    
    //Get to SharedPreferences
    
    //For default value, just to get no errors while getting no value from the SharedPreferences
    String empty_list = gson.toJson(new ArrayList<ListAdapterItemsSelected>()); 
    
    ArrayList<ListAdapterItemsSelected> mSelectedList = gson.fromJson(sp.getString("KEY", empty_list),
            new TypeToken<ArrayList<ListAdapterItemsSelected>>() {
            }.getType());