0

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;
    }
}
user3497103
  • 87
  • 1
  • 3
  • 7
  • 1
    Use gson to seralize the arraylist: http://stackoverflow.com/questions/7145606/how-android-sharedpreferences-save-store-object – Zarwan Oct 01 '15 at 02:57

3 Answers3

4

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());
NaviRamyle
  • 3,967
  • 1
  • 31
  • 49
0

There is now generic way. You may convert it to string by any methods like using json converters or use third party library like:

hawk:Secure Simple Key-Value Storage for Android

subhash
  • 2,689
  • 18
  • 13
0

SharedPreferences isn't great for this sort of thing. You can't even easily store a List of Strings without using some nasty hack, let alone a List of custom objects. Personally I'd store the List as a file in internal storage, using a DataOutputStream to write first the size of the ArrayList, followed by a sequence of boolean and String values for your objects.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116