2

I am using Volley for webcalls in my application and everything is working fine and smooth except one state in which somehow my device is not getting Network Connection but checking connection via code is returning true using below code.

public static boolean isNetworkAvailable() {

    ConnectivityManager connectivityManager = SessionApplication.getConnectivityManager();
    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
        return true;
    }
    else
        return false;
}

Instead of returning network state false using above code My volley web calls returning me this exception "handle com.android.volley.NoConnectionError: java.net.UnknownHostException".

I checked my internet connection by opening browser in my device and found it is also not working. So i am okay with application behavior but still i need to handle such condition because this is not user friendly user should be prompted a dialog that "Check Your Internet Connection!".

This should be a common issues in Android could any body please help me to give me best approach to handle such cases. Thanks in advance.

Network state is :enter image description here

Suresh Sharma
  • 1,826
  • 22
  • 41

2 Answers2

2

This exception indicates the problem in connectivity. In fact you can show some dialog about the connectivity. Overriding the onErrorResponse(VolleyError error) you can do like this -

public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, error.toString());
                        if (error instanceof NoConnectionError)
                        new AlertDialog.Builder(this).setMessage(
                                "Unable to connect to the server! Please ensure your internet is working!").show();
                    }
Sanjeet A
  • 5,171
  • 3
  • 23
  • 40
1

Try this method might help

public boolean isConnectedToInternet(){
        connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivityManager != null){
              NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
              if (info != null){
                  for (int i = 0; i < info.length; i++){
                      if (info[i].getState() == NetworkInfo.State.CONNECTED){
                          return true;
                      }
                  } 
              }
          }
          return false;
    }
Sahil Manchanda
  • 9,812
  • 4
  • 39
  • 89