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?
In android, we can determine the internet connection status easily by using getActiveNetworkInfo() method of ConnectivityManager object. Following is the code snippet of using the ConnectivityManager class to know whether the internet connection is available or not.
requestQueue is used to stack your request and handles your cache. You need to create this RequestQueue in your application class or in a Singleton class. Then only you can use the same requestQueue from multiple activities.
Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available on GitHub. Volley offers the following benefits: Automatic scheduling of network requests.
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."; } }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With