class MySettings { // final can't be changed public static final String CONSTANT = "ucantchangeme"; // static - all Objects have just these - even different Acitivities etc public static String sUserName; // class instance members - each Object you create with new has its own version public String mUserName; public MySettings() { mUserName = "uninitialized"; } public static void init() { sUserName = "Peter"; } public static void reset() { sUserName = null; } } /* Your Activity */ class MyActivity extends Actitivy { private MySettings mSettings; private MySettings mOtherSettings; onCreate() { // init those static parts of MySettings MySettings.init(); mSettings = new mSettings(); mSettings.mUserName = "Peter" Log.d("TAG", "Username: " + mSettings.mUserName); // prints Peter // this could also be another Activity mOtherSettings = new MySettings(); Log.d("TAG", "Username: " + mOtherSettings.mUserName); // prints "uninitialized" MySettings.sUserName = "Jim"; Log.d("TAG", "Username: " + MySettings.sUserName); // prints "Jim" mSettings.sUserName = "Joe"; Log.d("TAG", "Username: " + MySettings.sUserName); Log.d("TAG", "Username: " + mSettings.sUserName); Log.d("TAG", "Username: " + mOtherSettings.sUserName); // all print "Joe" now } onDestroy() { // clear MySettings MySettings.reset(); } }
You can reset static variables to null or whatever value you want, but using static variables for other things, constants are usually bad ideas - this is usually a bad class design and can lead to unexpected behavior like the one you observed.
The value of static variables will remain until the class is loaded - it has almost no relation to the activity life cycle ( onCreate , ..., onDestroy )
The first time a class is accessed from code, it will be loaded, and then it will not disappear until there is reason to unload it. During this time, something from your application (technically within the framework of one Process, as a rule, each .apk uses its own), will read the same value from this statics. And if you change it from different places, you change it to other parts that do not know about the change - why is it bad :)
The only reason (I know) that Android will unload the class is because your application is completely deleted from memory - either with the help of a task killer, or when your application is no longer active and the memory becomes low. This is completely out of your control and should not happen while your application is in use. This can happen if, for example, a phone call appears and your application resumes later.
zapl
source share