ConnectivityManager getActiveNetworkInfo null pointer exception

Martin Vandzura picture Martin Vandzura · May 6, 2013 · Viewed 19k times · Source

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.

Answer

android_dev picture android_dev · May 6, 2013

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