I am getting an NPE when trying to test if wifi SSID isEmpty or equals(“null”) in onResume. Here is how i’ve got it set up:
Class MyActivity extends Activity{
WifiManager myWifiManager;
public void onCreate(Bundle savedInstanceState) {
myWifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
...
}
protected void onResume() {
if (myWifiManager.isWifiEnabled() && !(myWifiManager.getConnectionInfo().getSSID().equals("null"))) {
...
}
I’ve determined that its the getSSID that is throwing the NPE. What confuses me about this is that I haven’t nulled out the WifiManager object in my onCreate (or any other method), and if I test myWifiManager.isWifiEnabled alone, it works just fine, so clearly the object is still alive. and i can log myWifiManager.getConnectionInfo().getSSID() and get null or the said value (depending on whether or not wifi is connected). So not sure why this is getting thrown. Any help would be much appreciated!
Your check for null is wrong; you have to use
==. You can’t callequals()on a nonexistent object, or you get an exception. You need to do this instead:Now, if
getConnetionInfo()can return null (and the Javadoc seems to indicate that it can), then you need to check those using==before calling any methods on them, either, like