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.

 

Constants.java

public class Constants {

    public static int GLOBAL_VARIABLE_1 = 1;

    public static String GLOBAL_VARIABLE_2 = "global variable”;


    public enum AppState {

        NOT_CONNECTED, CONNECTED

    }

    public static AppState appState = AppState.CONNECTED;
}
 

MainActivity.java

        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:

 

 

MainActivity.java

public class MainActivity extends Activity {

    public static MainActivity activity = null;   

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        activity = this;
        
    }

}
 
 

And in place where is needed, can be called:

MainActivity.activity.getBaseContext()

 

 

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

SingletonClass.java

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;
    }

}