Checking internet connection in android using getActiveNetworkInfo
<p>if you want to check <strong>internet connection</strong> in <strong>android</strong> there is a lot of ways to do that
for example:</p>
<pre><code>   public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) 
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null) 
              for (int i = 0; i &lt; info.length; i++) 
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
    }
</code></pre>
<p><strong>getAllNetworkInfo();</strong> was deprecated in api level 23 so i need a solution to check internet connection both api level 23 and prior,i found another way to do that</p>
<pre><code> private boolean isConnectedToInternet()
{
    ConnectivityManager cm = (ConnectivityManager) SplashActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) { // connected to the internet
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                // connected to wifi
                Toast.makeText(SplashActivity.this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
                return true;
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                // connected to the mobile provider's data plan
                Toast.makeText(SplashActivity.this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
                return true;
            }
        } 
    return false;
}
</code></pre>
<p>my question is about getActiveNetworkInfo() and isConnected() the documentation provided by google for this method is <a href="https://developer.android.com/reference/android/net/ConnectivityManager.html#getActiveNetworkInfo()" rel="nofollow noreferrer">here</a></p>
<blockquote>
<p>Returns details about the currently active default data network. When connected, this network is the default route for outgoing connections. You should always check isConnected() before initiating network traffic. This may return null when there is no default network.</p>
</blockquote>
<p>why we need to call <strong>isConnected()</strong> on <strong>getActiveNetworkInfo()</strong> for checking internet connection while we can check returned value from getActiveNetworkInfo() with <strong>null</strong> if not null we have internet connection else if returned null calling isConnected() on getActiveNetworkInfo() throws <strong>null pointer exception</strong> at runtime?</p>