Search code examples
javaandroidif-statementwifi

Java variable initialization in if-then statement


I have this code that is suppose to turn off Wifi via a toggle button. I also want to have it so that if the user already had Wifi on before pressing the button, the Wifi would go back on after turning off the toggle button. This is done through the wifiON boolean. However, since the variable is initialized in the first part of the if statement, it won't be used by the else statement. How can I set it so that the else statement can get the value of the boolean from the if statement. Below is the code.

    public void airplaneClicked (View view) {
    boolean on = ((ToggleButton) view).isChecked();
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    boolean wifiOn;

    if (on) {
        if (wifi.isWifiEnabled()) {
            wifiOn = true;
            Log.v("", "" + wifiOn);
            wifi.setWifiEnabled(false);
        } else {
            wifiOn = false;
            Log.v("", "" + wifiOn);
        }
    }
    else {
        if (wifiOn == true) {
            wifi.setWifiEnabled(true);
        }
    }
}

Solution

  • wifi.setWifiEnabled(!wifi.isWifiEnabled());