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");
}
Have you tried debug? It's possible that wifiResults is null at the moment