2013-10-21 91 views
0

我想找到Wifi的信號強度,但我得到一個空指針異常。 雖然提取像SSID等網絡informatiopns任何人都可以建議我一個解決方案如何刪除空指針異常。如何刪除空指針異常

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(); 
    } 
    } 
+6

1.見logcat的異常堆棧跟蹤。 2.找到相應的代碼行。 3.在你的代碼中查找這行代碼,並找出在那裏被解除引用的'null'。 4.編輯問題以至少包含步驟1和步驟2中的附加信息。 – laalto

+0

帶try..catch(){}塊的簡單環繞聲。 –

+0

10-21 06:23:52.851:E/AndroidRuntime(1045):致命異常:main 10-21 06:23:52.851:E/AndroidRuntime(1045):java.lang.RuntimeException:無法啓動活動ComponentInfo { com.example.wifi/com.example.wifi.MainActivity}:java.lang.NullPointerException 10-21 06:23:52.851:E/AndroidRuntime(1045):\t at android.app.ActivityThread.performLaunchActivity(ActivityThread.java :2211) 10-21 06:23:52.851:E/AndroidRuntime(1045):\t at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) – Dexter

回答

1

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

當沒有「bestSignal」發現,變量「bestSignal」將是無效和您要執行bestSignal.SSID這可能會導致NPE。

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

希望它能幫助:)