如何删除空指针异常

时间:2013-10-21 10:18:12

标签: android exception

我试图找到Wifi的信号强度,但我得到一个空指针异常。 在获取SSID等网络信息时,有人可以建议我解决方法如何删除空指针异常。

enter code here:

public class MyReciever extends BroadcastReceiver{
    WifiManager wifi;
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        List<ScanResult> results=wifi.getScanResults();
        ScanResult bestSignal=null;

        for(ScanResult result:results)
        {
            if(bestSignal==null || WifiManager.compareSignalLevel(bestSignal.level, result.level)<0)
                bestSignal=result;
        }

        String message=String.format("%s networks found. %s is the strongest", results.size(),bestSignal.SSID);
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();

        Log.d("Debug","onRecieve() message:" +message);
    }

}



public class MainActivity extends Activity {

    TextView textStatus;
    WifiManager wifi;
    BroadcastReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textStatus=(TextView)findViewById(R.id.textStatus);

        wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);

        WifiInfo info=wifi.getConnectionInfo();
        textStatus.append("\n\nWifi Status: " +info.toString());

        List<WifiConfiguration> configs=wifi.getConfiguredNetworks();
        for(WifiConfiguration config:configs)
        {
            textStatus.append("\n\n" +config.toString());
        }

        if(receiver==null)
                receiver = new MyReciever();

        registerReceiver(receiver, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        Log.d("TAG", "onCreate()");
    }

    @Override
    public void onStop() {
        unregisterReceiver(receiver);
            super.onStop();
    }
    }

1 个答案:

答案 0 :(得分:1)

问题可能出在String message=String.format("%s networks found. %s is the strongest", results.size(),bestSignal.SSID);

如果找不到'bestSignal',变量'bestSignal'将为null,并且您尝试执行可能导致NPE的bestSignal.SSID

将代码更改为 if (bestSignal != null) { String message=String.format("%s networks found. %s is the strongest", results.size(),bestSignal.SSID); }

希望有所帮助:)