Search code examples
javaandroidglobal-variables

How to implement global variables in extends different from 'Application' and 'Activity'?


I'm trying to implement Global variables in and Android Studio Application that uses BLE gatt services. I need to save a number received from BLE in a global variable.

So I have created this class:

public class Globals extends Application {
    private List<Float> current = new ArrayList<>();

    public float getCurrent() {
        return current.get(current.size()-1);
    }

    public void setCurrent(float someVariable) {
        this.current.add(someVariable);
    }
}

I have also modified the manifest with android:name. I can use correctly these functions in both the main activity and in some fragment. But I want to implement it in other extends different from Application or Activity.

In another java file I have this class:

class SerialSocket extends BluetoothGattCallback {

    // Here how can i get the function declared in Globals??
    Globals globalClass = (Globals) getApplicationContext(); 

Obviousy I can't use getApplicationContext() inside the BluetoothGattCallback extend, but what code can I use?


Solution

  • You can create a static instance of Globals and access.

    public class Globals extends Application {
        private static Globals instance;
        private List<Float> current = new ArrayList<>();
    
        @Override
        public void onCreate() {
            instance = this;
            super.onCreate();
        }
    
        public float getCurrent() {
            return current.get(current.size()-1);
        }
    
        public void setCurrent(float someVariable) {
            this.current.add(someVariable);
        }
    
        public static Globals getInstance() {
            return instance;
        }
    
        public static Context getContext(){
           return instance;
        // or return instance.getApplicationContext();
       } 
    }
    

    Now anywhere in app you can access the current variable or change the value by

    Globals.getInstance().getCurrent();