Reputation: 9
I am trying to find the signal strength of Wifi but I m getting a null pointer exception. While fetching the network informatiopns like SSID etc. Can anyone suggest me a solution how to remove the null pointer exception.
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();
}
}
Upvotes: 0
Views: 465
Reputation: 2066
Problem could be at String message=String.format("%s networks found. %s is the strongest", results.size(),bestSignal.SSID);
When there is no 'bestSignal' found, variable 'bestSignal' will be null and you are trying to execute bestSignal.SSID
which might cause NPE.
Change you code like
if (bestSignal != null) {
String message=String.format("%s networks found. %s is the strongest", results.size(),bestSignal.SSID);
}
Hope it helps :)
Upvotes: 1