禁用Wifi状态并尝试再次启用后出现NullPointerException

时间:2012-04-05 01:30:28

标签: java android

我第一次启用Wifi然后禁用它一切都很好,但如果我尝试重新启用Wifi(立即或等待移动数据再次连接),它会抛出NullPointerException并强制关闭。

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;
    }

}

错误在这一行:

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

1 个答案:

答案 0 :(得分:0)

你试过调试吗?目前wifiResults可能为null