1

I defined a static variable in my custom Application class. Something like this:

public class App extends Application{
    ...
    public static Object var;
    ...

    @Override
    public void onCreate() {
        var = new Object();
    }
}

During my applications's Activities i need to read App.var value, but some times it seems to be null.
Is this possible that static variables of my App class destroyed (because of GC or anything else) during lifetime of my application? If yes, why?

Fartab
  • 4,725
  • 2
  • 26
  • 39
  • 1
    do not use `Application` object for this purpose - https://developer.android.com/reference/android/app/Application.html: *"Note: There is normally no need to subclass Application. In most situations, static singletons can provide the same functionality in a more modular way."* – pskink Feb 25 '17 at 06:05
  • 1
    as @pskink said don't you Application class for this purpose, if the application process is killed, which will happen almost undoubtedly if you leave the app in the background too long, your singleton will be recreated, and so your var will be re set to a default value. In your case it is would be null. I would recommend use shared preference for that. – Zeeshan Shabbir Feb 25 '17 at 06:08
  • there is some benefits to use Application for this purpose. see this: http://stackoverflow.com/questions/708012/how-to-declare-global-variables-in-android?rq=1 – Fartab Feb 25 '17 at 06:08
  • see https://plus.google.com/u/0/+AnderWebbs/posts/DsfpW51Vvow, Dianne Hackborn - the autor of `Application` class says: "The only reason Application exists as something you can derive from is because during the pre-1.0 development one of our application developers was continually bugging me about needing to have a top-level application object they can derive from so they could have a more "normal" to them application model, and I eventually gave in. I will forever regret giving in on that one." – pskink Feb 25 '17 at 06:16
  • in the above g+ post, i read that android Application may be GCed but singletons didn't. that's strange for me. why is this possible? – Fartab Feb 25 '17 at 06:30

0 Answers0