0

I wrote the code below to check internet connection

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork == null) {
        return false;
    } else {
        if (activeNetwork.isConnected()) {
          return true;
        }
    }
}

I've check if the activeNetWork is null, but still get NullPointerException error, why ? enter image description here

KevinWang
  • 61
  • 5

1 Answers1

0

Use this code:

public static boolean isInternetconnected(Context ct) {  
   boolean connected = false;  
   //get the connectivity manager object to identify the network state.  
   ConnectivityManager connectivityManager = (ConnectivityManager)ct.getSystemService(Context.CONNECTIVITY_SERVICE);  
  //Check if the manager object is NULL, this check is required. to prevent crashes in few devices.
  if(connectivityManager != null) {  
     //Check Mobile data or Wifi net is present  

      if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||   
               connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)  {  
    //we are connected to a network  
    connected = true;  
     } else {  
      connected = false;  
   }  
  return connected;  
  } else  {  
  return false;  
 }  
}  
Sanoop Surendran
  • 3,484
  • 4
  • 28
  • 49
Divyang Patel
  • 347
  • 3
  • 14