I see occasionally null pointer exception in connectivity manager. From intent service I check network state by isOnWIFI(this). Exception occurs at line cm.getActiveNetworkInfo(). It's strange because I check for null before I call this. Note: Permissions are set.
public static boolean isOnWIFI(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm != null
//here occurs NullPointerException
&& cm.getActiveNetworkInfo() != null
&& ((cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && cm.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).isConnected()));
}
Any thoughts why this happen? I can't debug it because it's only occasional from bugs reports. Only solution I see is to put it into try catch block. Thanks.
are you Checked the api in that they are mentioned if there are no active connections they are simply returning null i think this is ur problem.
http://developer.android.com/reference/android/net/ConnectivityManager.html #getActiveNetworkInfo()
android_dev is right. The problem in your code comes from cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()));
Yes! you check cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null
before, but by calling getNetworkInfo()
a second time, android goes and fetches the Network info a second time, only this time it does not encounters an active network returning null this second time.
The thing is, not because you called getNetworkInfo()
a millisecond before and didn´t get a null, means you are not going to get it a millisecond after
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With