Is a "Globals" class holding static variables in Android safe? -
can enlighten me safety of class holding global values in android?
here's short example of mean:
public class globals { public static int somevariable = 0; public static user currentuser = null; public static handler onlogin = null; }
then somewhere in activity
following:
globals.somevariable = 42; globals.currentuser = new user("john", "doe");
i have rely on globals.currentuser
@ multiple places in app user logged in, i'm unsure if should it, , if use handler this.
i read everywhere android app killed anytime, mean killed or maybe part of it, killing globals
class only?
or there other way store globally available data in safe way, without writing every member change database (in fact, user
class little more complex in example. ;-)
thanks effort!
edit: ok, here's did:
public class myapp extends application { private static myapp _instance; public myapp() { super(); _instance = this; } public static myapp getcontext() { return _instance; } .... private user _user = null; public user getuser() { if (_user == null) _user = new user(); return _user; } }
then modify androidmanifest.xml
, add android:name=".myapp"
application
node tell app use subclass.
so far works fine , can access current context
(f.ex. in sqliteopenhelper
) calling myapp.getcontext()
.
it better use android application
class. it's meant store global application state
http://developer.android.com/reference/android/app/application.html
just create subclass , make sure update manifest file use version. can store whatever need in it. activities have method getapplication()
can cast class access implementation
Comments
Post a Comment