Make Quick HTTP Calls from Android Using Volley

In general practice an Android developer use “HttpURLConnection” to use web services and do ant data communication over the internet. Its bit confusing as it gives an error to handle threads and Async tasks. So it makes the process too long cumbersome.

For quickly using data communication I prefer Volley library of android. Let’s learn more about it.

You can get more information here about Android Volley and it’s Features.

Let’s begin with installation…

Step 1) Add the following dependency in Module: app build.gradle file

dependencies {
...
compile 'com.android.volley:volley:1.1.0'
}

after that click “Sync Now”

 

Step 2) Add the INTERNET Permission to “AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

 

Step 3) Let’s start using Volley in our application.

Define “RequestQueue” which will hold stack of all HTTP calls we will make an application

RequestQueue queue = Volley.newRequestQueue(this);

We can make multiple types of request using GET, POST, PUT and DELETE

GET HTTP Request:

In GET we will use JsonObjectRequest. JsonObjectRequest will have 4 parameters(Http method type, Url, Json values, Success Listener, Error Listener)

final String url = "http://example.com/get?param=test";
 
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
    new Response.Listener<JSONObject>() 
    {
        @Override
        public void onResponse(JSONObject response) {   
            // display response on Success   
            Log.d("Response", response.toString());
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {            
            Log.d("Error.Response", error.toString());
       }
    }
);
 
// add it to the RequestQueue   
queue.add(getRequest);

 

POST HTTP Request:

url = "http://example.com/post";
StringRequest postRequest = new StringRequest(Request.Method.POST, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response on Success
            Log.d("Response", response);
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error
             Log.d("Error.Response", error);
       }
    }
) {     
    @Override
    protected Map<String, String> getParams() 
    {  
            Map<String, String>  params = new HashMap<String, String>();  
            params.put("name", "Jolly");  
            params.put("domain", "http://freakyjolly.com");
             
            return params;  
    }
};
queue.add(postRequest);

 

PUT HTTP Request:

url = "http://example.com/put";
StringRequest putRequest = new StringRequest(Request.Method.PUT, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error
             Log.d("Error.Response", error);
       }
    }
) {
 
    @Override
    protected Map<String, String> getParams() 
    {  
            Map<String, String>  params = new HashMap<String, String> ();  
            params.put("name", "Jolly");  
            params.put("domain", "http://freakyjolly.com");
             
            return params;  
    }
 
};
 
queue.add(putRequest);

 

DELETE HTTP Request:

url = "http://example.com/delete";
StringRequest deleteRequest = new StringRequest(Request.Method.DELETE, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response on Success
            Log.d("Response", response);
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error
             Log.d("Error.Response", error); 
       }
    }
);

queue.add(deleteRequest);

 

 

 

UPDATE: I was facing a challenge like I created a common class (MyApiClass) having a method (sendData) to send API call, and this method call was called from a service (MyFirebaseInstanceIDService). But I was getting a Context error in following:

RequestQueue queue = Volley.newRequestQueue(this);

here “this” was going null and giving me following Fatal Error:-

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.content.Context android.content.Context.getApplicationContext()’ on a null object reference

Solution:

Step 1) In myApiClass Class create an “Activity” Instance as follows:

public static Activity currentActivity;

 

Step 2) Now in MainActivity add the following statement:

myApiClass.currentActivity = this;

So now it is having Context of MainAvtivity we can safely use Volley services in our myApiClass class.

 

Volley really makes HTTP calls very simple and easy to implement in the application without taking care of threads handling.

Leave a Comment

Your email address will not be published. Required fields are marked *