Search code examples
javaandroidclassloaderstatic-variables

Storing global objects in the Application class vs static class


Are there any differences between the two approaches in terms of the lifecycle of these variables?

As I understand in both cases foo gets garbage collected when the app get's cleared from the memory at the very

end. (correct? or am I missing something?)

Option 1: Storing a static variable in the Application class:

public class App extends android.app.Application {
    private static SomeClass foo;

    public static init setSomeObject(SomeClass someValue){
       foo = someValue;
    }


    public static SomeClass getSomeObject(){
       return foo;
    }
}

Option 2: String a static variable in any static class?

public class JustSomeClass {
    private static SomeClass foo;

        public static init setSomeObject(SomeClass someValue){
           foo = someValue;
        }

        public static SomeClass getSomeObject(){
           return foo;
        }
}

I prefer the second, purely for better readability as I don't want my Application class to grow too big, but I need to know if there are any disadvantages with that.


Solution

  • I agree to GhostCat and Chetan. I too feel using static must be avoided to avoid excess of memory usage.

    I'd prefer making a singleton class for each process, say, to handle flow of screens in my app or to write the helper methods for database operations or few common methods used by many activities/ fragments in my app.

    This link has a good discussion on Application class vs. Singleton.