Using static variables in Android

In android, are using static variables a recommended practice? E.g, implementing a Singleton pattern in Java, I usually do:

private static A the_instance;
public static A getInstance() {
    if (the_instance == null) {
       the_instance = new A();
    }
    return the_instance;
}

Also, when does this get cleaned up by the Android JVM?


static fields are attached to the Class instance as a whole, which is in turn attached to the ClassLoader which loaded the class. the_instance would be unloaded when the entire ClassLoader is reclaimed. I am 90% sure this happens when Android destroys the app (not when it goes into the background, or pauses, but is completely shut down.)

So, think of it as living as long as your app runs. Is Singleton a good idea? People have different views. I think it's fine when used appropriately, myself. I don't think the answer changes much on Android. Memory usage isn't the issue per se; if you need to load a bunch of stuff in memory, that's either a problem or it isn't, regardless of whether you encapsulate the data in a Singleton.


I think static variables are OK.

This is what Android doc says:

http://developer.android.com/guide/appendix/faq/framework.html

How do I pass data between Activities/Services within a single application?

A public static field/method

An alternate way to make data accessible across Activities/Services is to use public static fields and/or methods. You can access these static fields from any other class in your application. To share an object, the activity which creates your object sets a static field to point to this object and any other activity that wants to use this object just accesses this static field.


Contrary to what other people say - it is more than ok. Granted, it has some structure to it. In the official googlesamples/android-architecture repo it is used under todo-mvp-clean (Todo app implementing MVP pattern and following Clean Architecture principles). Check out this file.

What you can see is a lot of static methods referencing singleton getters.

Modern, less error prone and convenient alternative is the Dagger DI framework.