NullPointerException after disabling Wifi state and trying to enable again

Go To StackoverFlow.com

0

The first time I enable Wifi and then disable it everything is fine, but if I try to re-enable the Wifi after (either immediately or waiting for mobile data to connect again) it throws a NullPointerException and Force Closes.

private void toggleWifi(){

    if (wifi == 0){
        wifiManager.setWifiEnabled(true);
        scanOnly = wifiManager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "scanOnly");
        scanOnly.acquire();

        bWifi.setText("Turn Wifi OFF");

        List<ScanResult> wifiResults = wifiManager.getScanResults();

        StringBuilder sb = new StringBuilder("Scan Results:\n");            
        sb.append("-----------------------\n");

        for (ScanResult r : wifiResults) {
            sb.append(r.SSID + " " + r.level + " dBM\n");
        }

        tvWifi.setText(sb.toString());

        wifi = 1;

    } else {
        scanOnly.release();
        wifiManager.setWifiEnabled(false);

        bWifi.setText("Turn WiFi ON");

        tvWifi.setText("");

        wifi = 0;
    }

}

The error is on this line:

for (ScanResult r : wifiResults) {
    sb.append(r.SSID + " " + r.level + " dBM\n");
}
2012-04-05 01:30
by Rory


0

Have you tried debug? It's possible that wifiResults is null at the moment

2012-04-05 01:46
by Roman Truba
It seems that is the problem. But why would it be null the second time I run it, but not the first - Rory 2012-04-05 01:58
@Rory i guess, you should wait some time before wifi will find network - Roman Truba 2012-04-05 06:24
I just did a little error checking to work around the issue for now. Thanks for you input - Rory 2012-04-05 21:19
Ads