javaandroidandroid-studioandroid-wifiwifimanager

Connecting to Wifi AP programmatically in Android


I'm actually programming something that won't let the user access to android native wifi connecting page, so I'm programming it inside my Android app. It scan the available Wifi Network, display it in a ListView, and then you click on the network you want to connect to.

Actually everything works well beside my connection function, which makes my app crash, so if you have any idea... Here is the code (this is the function that is called after the user has enter the network pass) and the stack trace :

 private void connectToNetwork(String networkSSID, String networkPass, String networkCapabilities) {

        WifiConfiguration wifiConfig = new WifiConfiguration();
        wifiConfig.SSID =networkSSID;

        if (networkCapabilities.toUpperCase().contains("WEP")) { // WEP Network.
            Toast.makeText(this, "WEP Network", Toast.LENGTH_SHORT).show();

            wifiConfig.wepKeys[0] = networkPass;
            wifiConfig.wepTxKeyIndex = 0;
            wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        } else if (networkCapabilities.toUpperCase().contains("WPA")) { // WPA Network
            Toast.makeText(this, "WPA Network", Toast.LENGTH_SHORT).show();
            wifiConfig.preSharedKey = networkPass;
        } else { // OPEN Network.
            Toast.makeText(this, "OPEN Network", Toast.LENGTH_SHORT).show();
            wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }

        @SuppressLint("MissingPermission")
        List<WifiConfiguration> list = this.wifiManager.getConfiguredNetworks();
        for (WifiConfiguration config : list) {
            if (config.SSID != null && config.SSID.equals(networkSSID)) {
                this.wifiManager.disconnect();
                this.wifiManager.enableNetwork(config.networkId, true);
                this.wifiManager.reconnect();
                break;
            }
        }

    }

Stack trace :

java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List android.net.wifi.WifiManager.getConfiguredNetworks()' on a null object reference
        at solutions.#####.############.WifiActivity.connectToNetwork(WifiActivity.java:148)

Solution

  • So here is the full code that works now, after the help of @LevM. and a bit of self researh. I post it because I did not find much solutions to connect to specific Wifi network in Android on internet (SO, Youtube or whatever) so if it can help at least one dev some days, I'll be happy ! :D (Note : I'm a student programmer, I'm not saying that this solution is the best but it is functionnal at least)

    I had actually an issue with my wifiManager not being initialized. And then I deleted the wifiConfiguration list loop, I realized I didn't needed it. Finally I added String Format on SSID and Password since they need to be inside anti slash (" \ ").

    private boolean connectToNetwork(String networkSSID, String networkPass, String networkCapabilities) {
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiConfiguration wifiConfig = new WifiConfiguration();
            wifiConfig.SSID = String.format("\"%s\"", networkSSID);
    
            if (!wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(true);
            }
    
            if (networkCapabilities.toUpperCase().contains("WEP")) { // WEP Network.
                Toast.makeText(this, "WEP Network", Toast.LENGTH_SHORT).show();
    
                wifiConfig.wepKeys[0] = String.format("\"%s\"", networkPass);
                ;
                wifiConfig.wepTxKeyIndex = 0;
                wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            } else if (networkCapabilities.toUpperCase().contains("WPA")) { // WPA Network
                Toast.makeText(this, "WPA Network", Toast.LENGTH_SHORT).show();
                wifiConfig.preSharedKey = String.format("\"%s\"", networkPass);
                ;
            } else { // OPEN Network.
                Toast.makeText(this, "OPEN Network", Toast.LENGTH_SHORT).show();
                wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            }
    
    
            int netId = wifiManager.addNetwork(wifiConfig);//  
            wifiManager.disconnect();
            wifiManager.enableNetwork(netId, true);
            return wifiManager.reconnect();
    
        }