i've got weird problem shared preferences. i'm using them store user-id, different settings , on. i'm using activity switches fragments if user has clicked item in menu (i'm using menu-drawer).
after every login store user profile. works perfect. after doing can restart app, kill memory, can restart device , values still stored. when switch fragment, e.g i'm in home view , click "about app" in menu, gone. values empty.
where gets weirder: if force activity reload fragment selecting home-item while i'm in home view, it's still stored. if replace different type of fragment lost.
i don't have idea why app behaves this. it's in same activity same context. i'm using getactivity context inside fragment.
here's simplified snippet of code store it.
public static void storeuserprofile(context context, loginevent event, string userid, string emailaddress, string passwordhash) { sharedpreferences userprefs = context.getsharedpreferences(appconfig.user_prefs, context.mode_private); sharedpreferences.editor editor = userprefs.edit(); editor.clear(); editor.putstring("username", event.username); editor.putstring("id", userid); editor.putstring("email", emailaddress); editor.commit(); }
this how switch fragments:
homefeedfragment fragment = new homefeedfragment(); fragmenttransaction ft = getsupportfragmentmanager().begintransaction(); ft.replace(r.id.content_frame, fragment); ft.commit();
try snippet, can accessed activities/ fragments in app.
declare these methods first..
public static void putpref(string key, string value, context context) { sharedpreferences prefs = preferencemanager.getdefaultsharedpreferences(context); sharedpreferences.editor editor = prefs.edit(); editor.putstring(key, value); editor.commit(); } public static string getpref(string key, context context) { sharedpreferences preferences = preferencemanager.getdefaultsharedpreferences(context); return preferences.getstring(key, null); }
then call when want put pref:
putpref("mykey", "mystring", getapplicationcontext());
call when want pref:
getpref("mykey", getapplicationcontext());
Comments
Post a Comment