sharedpreferences - Android: access SharedPrefernces from non-activity class -
i trying access sharedprefernces non-activity class.
i trying in way:
context applicationcontext = mainactivity.getcontextofapplication(); sharedpreferences prefs = preferencemanager.getdefaultsharedpreferences(applicationcontext); private int age = prefs.getint("age", 0); private string name = prefs.getstring("name", null); but variable age 0, , variable name null.
what doing wrong?
i save sharedpreferences in activity class:
@override public void onclick(view v) { switch (v.getid()) { case r.id.savebutton: savetext(); prefs = getpreferences(mode_private); int age = prefs.getint("age", 0); string name = prefs.getstring("name", null); if(name == null || age <= 0) { toast.maketext(nameage.this, "put name , age", toast.length_long).show(); } else { toast.maketext(nameage.this, age+prefs.getstring("name", null), toast.length_long).show(); intent = new intent(nameage.this, mainactivity.class); startactivity(i); finish(); break; } } } private void savetext() { prefs = getpreferences(mode_private); sharedpreferences.editor ed = prefs.edit(); ed.putstring(name, nametext.gettext().tostring()); ed.putint(age, integer.parseint(agetext.gettext().tostring())); ed.commit(); }
because trying preference default shared preference file while have stored prefernce @ activity context level using getpreferences(mode_private).
if store preference below work
sharedpreferences prefs = preferencemanager.getdefaultsharedpreferences(applicationcontext); sharedpreferences.editor ed = prefs.edit(); ed.putstring(name, nametext.gettext().tostring()); ed.putint(age, integer.parseint(agetext.gettext().tostring())); ed.commit();
Comments
Post a Comment