Home Development of Websites A simple example of how to use the Volley library

A simple example of how to use the Volley library

by admin

I’m sure you haven’t heard the word "Volley" yet, it’s a library introduced at Google I/O 2013 Ficus Kirkpatrick

What is the Volley library for?

Volley is a library that makes networking applications for Android easier and, most importantly, faster.

It manages the processing and caching of network requests, and it saves developers precious time from writing the same network request/reading code from the cache over and over again.And another advantage, less code, fewer bugs 🙂
Usually we write the same network request code in the AsyncTask, the logic to process the response from the Web API and display it in the View.We have to take care of displaying the ProgressBar/ProgressDialog inside OnsourceExecute() and OnPostExecute(). I know it’s not a difficult task, but it’s still a chore. Sometimes it gets boring, even when a base class is defined to manage ProgressBar/ProgressDialog and many other things. So now we can say, Volley can be a powerful alternative to AsyncTask.

Benefits of using Volley:

  1. Volley automatically compiles all network requests. Volley will take over all network requests from your application execute them to retrieve a response or image from web sites.
  2. Volley provides transparency to disk caching and in-memory caching.
  3. Volley provides a powerful API for canceling a request. You can cancel a single request or set multiple requests to cancel.
  4. Volley provides powerful modification capabilities.
  5. Volley provides tools for debugging and tracing.

How to start?

  1. Clone Project Volley.
    git clone https://android.googlesource.com/platform/frameworks/volley
  2. Import the code into your project

2 main Volley classes

There are 2 main classes :

  1. Requestqueue
  2. Request

Request queue: is used to send network requests, you can create the request queue class wherever you want but usually it is created at startup and used as a Singleton.
Request: it contains all details necessary to create a Web API call. For example: which method to use (GET or POST), request data, response listener, error listener.
Take a look at the JSONObjectRequest method:

/*** Creates a new request.* @param method the HTTP method to use* @param url URL to fetch the JSON from* @param jsonRequest A {@link JSONObject}to post with the request. Null is allowed and* indicates no parameters will be posted along with request.* @param listener Listener to receive the JSON response* @param errorListener Error listener, or null to ignore errors.*/public JsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) {super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);}/*** Constructor which defaults to <code> GET</code> if <code> jsonRequest</code> is* <code> null</code> , <code> POST</code> otherwise.** @see #JsonObjectRequest(int, String, JSONObject, Listener, ErrorListener)*/public JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) {this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest, listener, errorListener);}

A simple example of using Volley:

I hope you’ve already cloned/downloaded the Volley library from the Git repository. Now follow the instructions to create a simple JSON response extraction example.
Step 1: Make sure you have imported the Volley project into Eclipse. Now after importing, we have to make the project a Library project, right click => Properties => Android (left panel).
A simple example of how to use the Volley library
Step 2: Create a new project VolleyExample
Step 3: Right-click on VolleyExample and include the Volley library in your project.
A simple example of how to use the Volley library
Step 4: Turn on the permission to use the Internet in the AndroidManifest.xml file

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

Step 5:
5.1 Create an object of the RequestQueueue class

RequestQueue queue = Volley.newRequestQueue(this);

5.2 Create a JsonObjectRequest with response and error listener.

String url = "https://www.googleapis.com/customsearch/v1?key=AIzaSyBmSXUzVZBKQv9FJkTpZXn0dObKgEQOIFUcx=014099860786446192319:t5mr0xnusiyq=AndroidDevalt=jsonsearchType=image";JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject> () {@Overridepublic void onResponse(JSONObject response) {// TODO Auto-generated method stubtxtDisplay.setText("Response => "+response.toString());findViewById(R.id.progressBar1).setVisibility(View.GONE);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {// TODO Auto-generated method stub}});

5.3 Add your request to RequestQueue.

queue.add(jsObjRequest);

All code for MainActivity.java file

package com.technotalkative.volleyexamplesimple;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.widget.TextView;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley;public class MainActivity extends Activity {private TextView txtDisplay;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);txtDisplay = (TextView) findViewById(R.id.txtDisplay);RequestQueue queue = Volley.newRequestQueue(this);String url = "https://www.googleapis.com/customsearch/v1?key=AIzaSyBmSXUzVZBKQv9FJkTpZXn0dObKgEQOIFUcx=014099860786446192319:t5mr0xnusiyq=AndroidDevalt=jsonsearchType=image";JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject> () {@Overridepublic void onResponse(JSONObject response) {// TODO Auto-generated method stubtxtDisplay.setText("Response => "+response.toString());findViewById(R.id.progressBar1).setVisibility(View.GONE);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {// TODO Auto-generated method stub}});queue.add(jsObjRequest);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is sourcesent.getMenuInflater().inflate(R.menu.main, menu);return true;}}

You may also like