Search code examples
androidandroid-studiocallable-statement

how to pass a value for a Callable function in android studio?


i'm trying to pass a value to a callback function in my code, i'm passing my callbackto another function and i want it to return the callback a state,

here is my function I'm sending out >

wifiWrapper myWifiWrapper = new wifiWrapper(); //- INIZILIZING WIFI
                    myWifiWrapper.checkWifiState(this, wifiStateCallback);

here is my end function in the wifiWrapper class >

//checks if the wifi is On or Off
    public void checkWifiState (Context context, Callable callback) {


        WifiManager wifi = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);

        boolean isOn;


        if (wifi.isWifiEnabled()){

            Toast.makeText(context.getApplicationContext(), "Your Wi-Fi is enabled", //wifi is enabled
                    Toast.LENGTH_SHORT).show();
            isOn = true;

        } else {

            Toast.makeText(context.getApplicationContext(), "Your Wi-Fi is disabled", //wifi is disabled
                    Toast.LENGTH_SHORT).show();
            isOn = false;

        }



        try { //trys to call back to the callable function
            callback.call();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

and here is my Callable that i'm passing >

//callback for the ifiState
    Callable wifiStateCallback = new Callable() {
        @Override
        public Boolean call() throws Exception {


            return null;
        }
    };

PROBLEM IS I want to pass the isOnState to the callable, and can't seem to make it work. i'm adding

callback.call(isOn);

but it doesn't work it says it cannot be applied


Solution

  • You cannot add argument to call() out of nowhere and expect it to work. Callable's call() is argumentless. What you can do however, is to extend Callable and pass whatever you want via constructor:

    class MyCallable extends Callable {
    
        boolean isOn;
    
        public MyCallable(boolean isOn) {
           mIsOn = isOn;
        }
    
        public Boolean call() throws Exception {
            if (mIsOn) {
               ...
            }
            ...
        }
    
    }
    

    so then

    Callable wifiStateCallback = new MyCallable(false);