Global variables, Base Context and singletons in Android

Accessing global variables, Base Context and singletons in Android

In this tutorial is described some straightforward possibilities how to access global variables, Base Context and singletons.

public class Constants {

    public static int GLOBAL_VARIABLE_1 = 1;

    public static String GLOBAL_VARIABLE_2 = "global variable”;

    public enum AppState {



    public static AppState appState = AppState.CONNECTED;

        int global_variable = Constants. GLOBAL_VARIABLE_1;
Lot of objects are expected to be initialized by Base Context, but when to take the Base or Application Context? One of  the solution is to take it from an activity. It can be done by this way for example:

public class MainActivity extends Activity {

    public static MainActivity activity = null;   


    public void onCreate(Bundle savedInstanceState) {



        activity = this;


And in place where is needed, can be called:




And finally, how to access “global” classes across android software? One possibility is use singletons.

public class SingletonClass { 
    private static final SingletonClass instance = new SingletonClass ();

    private SingletonClass () {

        if (instance != null) {

            throw new IllegalStateException("Already instantiated");


    public static SingletonClass getInstance() {

        return instance;