java - What I missing when tried to retrieve data from Shared Preferences -
hey guyz check out missing here cause of not able fetch data shared preferences. making such tasklist application in saving data(means mytask) key , storing in shared preferences , increments variable total count.
check code(whenever click on addtask button following code gets executed).
private void savetosharedpreference(){ sharedpre = getsharedpreferences("todopref",context.mode_private); editor = sharedpre.edit(); string mykey = "key"+a; string myvalue = et.gettext().tostring(); editor.putstring(mykey,myvalue); // editor.putint("totaltask", a); editor.commit(); } now when close application , open again following code gets executed in order load data shared preferences.
private void loaddata(){ sharedpre = getsharedpreferences("todopref",context.mode_private); int p = 1; string mykey = "key"+p; while(sharedpre.getstring(mykey,"") != null){ toast.maketext(this, sharedpre.getstring(mykey,""),toast.length_short).show(); } } but problem returning null on indexes. don't know why getting error. please me in advance sarosh madara
to load saved values use following code:
private void loaddata() { sharedpreferences sharedpre = getsharedpreferences("todopref",android.content.context.mode_private); map<string,?> keys = sharedpre.getall(); for(map.entry<string,?> entry : keys.entryset()){ if (entry.getvalue().tostring().length() > 0) { log.d("map values",entry.getkey() + ": " + entry.getvalue().tostring()); } } } i found here added check ignore null values.
to save values shared preference suggest using instance of current time key. no need save integer key values:
private void savetosharedpreference(string myvalue){ sharedpreferences sharedpre = getsharedpreferences("todopref",android.content.context.mode_private); editor editor = sharedpre.edit(); string key = string.valueof(calendar.getinstance().gettimeinmillis()); editor.putstring(key,myvalue); editor.commit(); } so whenever want add values shared preferences use:
savetosharedpreference("myvalue"); and load them use:
loaddata(); the map interface
a map object maps keys values. map cannot contain duplicate keys: each key can map @ 1 value. read more...
sharedpreferences: class overview
Comments
Post a Comment