Android Volley - Checking internet state
Asked Answered
I

6

27

Before I am using Volley, well as usual, I used AsyncTask to check my internet state.

Here is what I did in AsyncTask:

private class NetCheck extends AsyncTask<String, Void, Boolean> {

    @Override
    protected Boolean doInBackground(String... args) {
        // get Internet status
        return cd.isConnectingToInternet();
    }

    protected void onPostExecute(Boolean th) {
        if (th == true) {
            new LoadCategories().execute();
        } else {
            Toast.makeText(CategoryActivity.this, "Unable to connect to server",
                    Toast.LENGTH_LONG).show();
        }
    }
}

And this is isConnectingToInternet function:

public boolean isConnectingToInternet() {
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo info = connectivity.getActiveNetworkInfo();
        if (info != null && info.isConnected())    
            try {
                URL url = new URL("http://www.google.com");
                HttpURLConnection urlc = (HttpURLConnection) url
                        .openConnection();
                urlc.setConnectTimeout(3000);
                urlc.connect();
                if (urlc.getResponseCode() == 200) {
                    return true;
                }
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

    }
    return false;
}

How do I achieve this using Volley?

Important answered 9/1, 2014 at 3:48 Comment(0)
H
112

There is NoConnection Error that get thrown for the Request. Please catch the error in

   @Override
   public void onErrorResponse(VolleyError volleyError) {
   String message = null;
   if (volleyError instanceof NetworkError) {
         message = "Cannot connect to Internet...Please check your connection!";
   } else if (volleyError instanceof ServerError) {
         message = "The server could not be found. Please try again after some time!!";
   } else if (volleyError instanceof AuthFailureError) {
         message = "Cannot connect to Internet...Please check your connection!";
   } else if (volleyError instanceof ParseError) {
         message = "Parsing error! Please try again after some time!!";
   } else if (volleyError instanceof NoConnectionError) {
         message = "Cannot connect to Internet...Please check your connection!";
   } else if (volleyError instanceof TimeoutError) {
         message = "Connection TimeOut! Please check your internet connection.";
   }
}
Hydrostatic answered 11/9, 2014 at 16:14 Comment(2)
This is not the same. NoConnectionError is thrown not only when there is no network connectivity but also when it is impossible to establish connection with a host (for example if it is unable to resolve host).Marika
Since NoConnectionError extends NetworkError, you will never hit if (volleyError instanceof NoConnectionError) {Aleen
A
3

This is how I make Volley Request and handle response and errors, you don't need to add Async task for this, volley make request in backend

StringRequest strReq = new StringRequest(Request.Method.POST, "your_url", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                // handle your response here
                // if your response is a json then create json object and use it
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    // now you can get values from your jsonObject

                }
                catch (Exception e){}

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

                String message = null; // error message, show it in toast or dialog, whatever you want
                if (volleyError instanceof NetworkError || volleyError instanceof AuthFailureError || volleyError instanceof NoConnectionError || volleyError instanceof TimeoutError) {
                    message = "Cannot connect to Internet";
                } else if (volleyError instanceof ServerError) {
                    message = "The server could not be found. Please try again later";
                }  else if (volleyError instanceof ParseError) {
                    message = "Parsing error! Please try again later";
                }

            }
        }) {
            @Override
            public byte[] getBody() throws AuthFailureError {

                HashMap<String, String> params = new HashMap<>();
                params.put("key","value"); // put your params here

                return new JSONObject(params).toString().getBytes();
            }

            @Override
            public String getBodyContentType() {
                return "application/json";
            }
        };
        // Adding String request to request queue

        Volley.newRequestQueue(getApplicationContext()).add(strReq);
Antenna answered 24/6, 2019 at 15:26 Comment(0)
A
2

I use below code for detecting which error is occurring:

 new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {


            if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                Toast.makeText(getApplicationContext(), "Communication Error!", Toast.LENGTH_SHORT).show();

            } else if (error instanceof AuthFailureError) {
                Toast.makeText(getApplicationContext(), "Authentication Error!", Toast.LENGTH_SHORT).show();
            } else if (error instanceof ServerError) {
                Toast.makeText(getApplicationContext(), "Server Side Error!", Toast.LENGTH_SHORT).show();
            } else if (error instanceof NetworkError) {
                Toast.makeText(getApplicationContext(), "Network Error!", Toast.LENGTH_SHORT).show();
            } else if (error instanceof ParseError) {
                Toast.makeText(getApplicationContext(), "Parse Error!", Toast.LENGTH_SHORT).show();
            }
        }
    });
Annapolis answered 22/9, 2016 at 11:58 Comment(0)
F
1

Use this code for checking internet state :

public class Internet {
    private Context context;

    public Internet(Context context) {
        this.context = context;
    }

    public Boolean Check() {
        ConnectivityManager cn = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf = cn.getActiveNetworkInfo();
        if (nf != null && nf.isConnected() == true) {
            return true;
        } else {
            Toast.makeText(context, "No internet connection.!",
                    Toast.LENGTH_LONG).show();
            return false;
        }
    }
}
Frore answered 9/1, 2014 at 3:54 Comment(6)
add permission in android manifest.xml : <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />Frore
yes, you can use this code for check internet connection before start AsyntaskFrore
But I don't want to use AsyncTask. Can it be done using Volley instead?Important
yes, it can. if you want to load image from server to list view , you can use smartImageView : loopj.com/android-smart-image-viewFrore
hi please have a look at arnab.ch/blog/2013/08/…. hope it will explain you that what you wants to do, i do think you can follow the given approach in my answer. i find it really great and suitableSartain
@JiteshUpadhyay I get a file not found error when clicking you link. Is it available somewhere else? Would be really helpful if you could give an updated link.Thanks!Bamako
B
1

I manage to check the internet in Application class

     public class App extends Application {
            private static final String TAG = "MyApp";

            private static App mInstance;
            private RequestQueue mRequestQueue;
            private ImageLoader mImageLoader;

            public static synchronized App getInstance() {
                return mInstance;
            }

            @Override
            public void onCreate() {
                super.onCreate();
              mInstance = this;
            }

            public RequestQueue getRequestQueue() {
                if (mRequestQueue == null) {
                    mRequestQueue = Volley.newRequestQueue(getApplicationContext());
                }

                return mRequestQueue;
            }



            public <T> void addToRequestQueue(Request<T> req, String tag) {
                // set the default tag if tag is empty
                req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
                getRequestQueue().add(req);
            }

            public <T> void addToRequestQueue(Request<T> req) {

                if(CommonUtills.isNetworkAvailable(getApplicationContext())) {
                    req.setRetryPolicy(new DefaultRetryPolicy(
                            60000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    req.setTag(TAG);
                    getRequestQueue().add(req);
                }
                else
                {
                 Toast.makeText(getApplicationContext(), "Unable to 
connect to server",Toast.LENGTH_LONG).show();
                }
            }

            public void cancelPendingRequests(Object tag) {
                if (mRequestQueue != null) {
                    mRequestQueue.cancelAll(tag);
                }
            }

        }

And I am calling each network call using following way every time

App.getInstance().addToRequestQueue(jsonObjRequest);

So before calling each request,it will be execute if internet is available

Bartolome answered 19/9, 2017 at 7:6 Comment(0)
R
0
new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError volleyError) {

        if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
            Toast.makeText(getApplicationContext(), "No Connection/Communication Error!", Toast.LENGTH_SHORT).show();

        } else if (volleyError instanceof AuthFailureError) {
            Toast.makeText(getApplicationContext(), "Authentication/ Auth Error!", Toast.LENGTH_SHORT).show();
        } else if (volleyError instanceof ServerError) {
            Toast.makeText(getApplicationContext(), "Server Error!", Toast.LENGTH_SHORT).show();
        } else if (volleyError instanceof NetworkError) {
            Toast.makeText(getApplicationContext(), "Network Error!", Toast.LENGTH_SHORT).show();
        } else if (volleyError instanceof ParseError) {
            Toast.makeText(getApplicationContext(), "Parse Error!", Toast.LENGTH_SHORT).show();
        }
    }
});

This is good for you as a developer. But do not show some of this direct messages like auth and server-side error to the end user. Be creative and show something like can not connect at the moment.

Rawden answered 22/7, 2018 at 19:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.