Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConnectivityManager getActiveNetworkInfo null pointer exception

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.

like image 619
Martin Vandzura Avatar asked May 06 '13 11:05

Martin Vandzura


2 Answers

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()

like image 177
android_dev Avatar answered Oct 07 '22 11:10

android_dev


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

like image 28
user3597165 Avatar answered Oct 07 '22 11:10

user3597165