java - Android - Shared Preference with Two Classes -
basically want set 1 class have getters , setters device store , retrieve data, , other classes access it. managed sharedpreferences working in 1 class having trouble 2 classes (i'm familiar java not android, read somewhere shouldn't using activity static, , couldn't working either). anyway here getter / setter class.
public class storage extends activity { @override public void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); } final sharedpreferences prefs = this.getsharedpreferences( "uk.co.kenreid.examplestory", context.mode_private); string namekey = "uk.co.kenreid.examplestory.name";
i access these pieces of code in other class (final used variable "storage" used within onclicklistener):
final storage storage = new storage(); storage.storeitem("name", name); system.out.println(storage.getstring("name"));
i believe issue initialising sharedpreferences
away activity
?
assuming issue, can pass context
through constructor of storage
class initalise it.
eg.
sharedpreferences prefs; public storage(context acontext){ prefs = acontext.getsharedpreferences("uk.co.kenreid.examplestory", context.mode_private); }
then access via original acessor methods. might best pass application contex
t rather activity context
through constructor, when create storage class, call in activity:
storage mystorage = new storage(getapplicationcontext());
it might wise create singleton class well, allow use same instance of storage. there plenty of tutorials singletons in java around web.
Comments
Post a Comment