Volley library in Android :

 

Volley Library in Android :


Volley is an HTTP library that makes networking very easy and fast, for Android apps. It was developed by Google and introduced during Google I/O 2013. It was developed because there is an absence in Android SDK, of a networking class capable of working without interfering with the user experience. Although Volley is a part of the Android Open Source Project(AOSP), Google announced in January 2017 that Volley will move to a standalone library. It manages the processing and caching of network requests and it saves developers valuable time from writing the same network call/cache code again and again.



Volley is a networking library managed by the RequestQueue and mainly used for smaller Networking purposes in Android. To use it, first you need to instantiate the RequestQueue and later on you can start or stop request, add or cancel request and access the response cache(s).

RequestQueue queue = Volley.newRequestQueue(this);

After instantiating RequestQueue, a request must be created. The default request classes already included in Volley library are String request, JSON request, and image request. You can also create custom request by extending Volley’s request class.

Request Constructors used in Volley takes 4 parameter:

JsonObjectRequest request = JsonObjectRequest(Request.Method.GET, url,  new ResponseListener(), new ErrorListener();

First Parameter: Request.Method.GET – The GET is used to read. You can also use POST (to create), PUT (To update/replace), DELETE (to delete), PATCH (to update/modify) and more.

Second Parameter: URL – The url that will response to the HTTP request.

Third Parameter: Successful Response Listener – Where your data will go after the request is successfully complete.

private class ResponseListener implements Response.Listener{
@Override
public void onResponse(JSONObject response){
}
}

Fourth Parameter: Error Listener – What will be told if there was a problem with your request. For example, you can display it in Log to see the error.

private class ErrorListener implements Response.ErrorListener{
@Override
public void onErrorResponse(VolleyError error){
}
}

Now the last step is to add your request to Request queue and rest volley will handle for you.

queue.add(request);

Create new project.

dependencies{ 
    //...
    implementation 'com.android.volley:volley:1.0.0'
}
In AndroidManifest.xml add the internet permission:
  
<uses-permission    android:name="android.permission.INTERNET />"

Activity Main.xml Code :

  1. <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
    android:id="@+id/buttonRequest"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#414af4"
    android:text="Click Here To Send HTTP Request To Server And See Response Displayed As Toast"
    android:textColor="#ffffff"
    android:layout_alignParentTop="true"
    android:layout_marginTop="50dp" />

    </RelativeLayout>

Activity Main.Java code :

  1. public class MainActivity extends AppCompatActivity {

    String url="https://run.mocky.io/v3/1d254295-55ad-4c6f-8ac0-a84271609c7f";
    private Button btnRequest;

    private RequestQueue mRequestQueue;
    private StringRequest mStringRequest;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnRequest = (Button) findViewById(R.id.buttonRequest);

    btnRequest.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v){

    sendAndRequestResponse();

    }
    }

    );
    }
    private void sendAndRequestResponse() {

    //RequestQueue initialized
    mRequestQueue = Volley.newRequestQueue(this);

    //String Request initialized
    mStringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {

    Toast.makeText(getApplicationContext(),"Response :" + response.toString(),
    Toast.LENGTH_LONG).show();//display the response on screen

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

    Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
    }
    });

    mRequestQueue.add(mStringRequest);
    }
    }
Types of Request using Volley Library:
1- String Request
  1. String url = "https:// string_url/";
    StringRequest
    stringRequest
    = new StringRequest(
    Request.Method.GET,
    url,
    new Response.Listener() {
    @Override
    public void onResponse(String response)
    {
    }
    },
    new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error)
    {
    }
    });
    requestQueue.add(stringRequest);
JSONObject Request
  1. String url = "https:// json_url/";
    JsonObjectRequest
    jsonObjectRequest
    = new JsonObjectRequest(
    Request.Method.GET,
    url,
    null,
    new Response.Listener() {
    @Override
    public void onResponse(JSONObject response)
    {
    }
    },
    new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error)
    {
    }
    });
    requestQueue.add(jsonObjectRequest);
2-JSONArray Request :
  1. JsonArrayRequest
    jsonArrayRequest
    = new JsonArrayRequest(
    Request.Method.GET,
    url,
    null,
    new Response.Listener() {
    @Override
    public void onResponse(JSONArray response)
    {
    }
    },
    new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error)
    {
    }
    });
    requestQueue.add(jsonArrayRequest);
 3- Image Request:
  • int max - width = ...;
    int max_height = ...;

    String URL = "http:// image_url.png";

    ImageRequest imageRequest = new ImageRequest(URL,new Response.Listener() {
    @Override
    public void onResponse(Bitmap response){
    // Assign the response to an ImageView
    ImageView imageView= (ImageView)findViewById(R.id.imageView);
    imageView.setImageBitmap(response);
    }
    },
    max_width, max_height, null);

    requestQueue.add(imageRequest);
  • Cancelling a Request

        stringRequest.cancel()

Sending Data with Volley

We used the Volley library to retrieve data, either String, JSONObjects or Images, but we can also use the Volley library to send data using the GET or POST method of the HTTP protocol.
To send the data using the GET method, you just need to append "?" and the query string to the URL.
To use the POST method when sending a request and send key/values pairs as data, we need to use REQUEST.Method.POST as the first param of the StringRequest and overide the getParams() method of the StringReuest class. For example, to send two parameters for a survey about favorite food and color we would do


Rajeshbhatt12

My name is Rajesh Bhatt. I am working as a senior android developer . I have created this blog for kotlin ,java and Android Development interview questions etc..

Previous Post Next Post