我想知道如何将自定义ArrayList保存到Android手机中。 因为它习惯于过滤 Activity 。 我应该将此信息保存在任何地方。
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;
}
}
最佳答案
使用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());
关于java - 如何使用SharedPreference保存自定义ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32878684/