java - Android List in SharedPreference -
i trying edit values list in sharedpreferences someting going wrong.
my sharedpreference is:
public class stepsdata { static sharedpreferences data; static sharedpreferences.editor editor; static final int value_key = 0; static final list<string> list_key= new vector<string>(); }
i use sharedpref by:
stepsdata.data = getapplicationcontext().getsharedpreferences("userdata", mode_private); stepsdata.editor = stepsdata.data.edit();
if want edit or value value_key works by:
int step = stepsdata.data.getint(string.valueof(value_key), 0); editor.putint(string.valueof(value_key), 0).apply();
but have problem using list, code value is:
list<string> mylist = (list<string>) data.getstringset(string.valueof(list_key),null);
and delete:
list<string> clearlist = new vector<string>(); editor.putstringset(string.valueof(list_key), (set<string>) clearlist).apply();
but there nullpointerexception. best way use ".clear()" on list sharedpreference , how is possible values list , size?
if want store list object in sharedpreference use gson library. use convert list object json format , store json string sharedpref.
first include line in gradle file(app level)
compile 'com.google.code.gson:gson:2.4'
below code set type list
type listtype = new typetoken<list<string>>(){}.gettype(); gson gson = new gson();
now create list object , convert json string format using gson object , type
list<string> mylist = new arraylist<>(); //add elements in mylist object string jsonformat = gson.tojson(mylist,listtype); //adding sharedpref editor.put("list",jsonformat).apply();
now values sharedpref , convert json string list object.
//this line json string sharedpref , converted object of type list(specified in listtype object) list<string> list = gson.fromjson(sharedpref.get("list",""),listtype); //now modify list object par requirement , again same step of converting list object jsonformat.
Comments
Post a Comment