Tutorial details

Android – Volley library example | App Code for Sale | Preview

Android – Volley library example | Android Tutorial

How to use Volley library

Overview PAGE TOP

I am not sure whether you have heard “Volley” word yet but it’s the library on which one expert talk was delivered during Google I/O 2013 by Ficus Kirkpatrick.

What is Volley library exactly for?

Volley is a library that makes networking for Android apps easier and most importantly, faster. 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. And one more benefit of having less code is less number of bugs and that’s all developers want and aim for.

My mean of writing the same network call code is AsyncTask and the logic/code you write for fetching response from Web API and displaying it in particular View. We have to take care of displaying ProgressBar/ProgressDialog inside onPreExecute() and onPostExecute(). I know this is not a hard task but still boring, sometimes I also feel get bored even though I have defined BaseTask class for managing display/dismiss operation of ProgressBar/ProgressDialog and many more thing. So now we can say Volley can be a powerful alternative of AsyncTask.

Advantages of using Volley:

  1. Volley automatically schedule all network requests. It means that Volley will be taking care of all the network requests your app executes for fetching response or image from web.
  2. Volley provides transparent disk and memory caching.
  3. Volley provides powerful cancellation request API. It means that you can cancel a single request or you can set blocks or scopes of requests to cancel.
  4. Volley provides powerful customization abilities.
  5. Volley provides Debugging and tracing tools

How to get started?

  1. Clone the Volley project
  2. Import the code into your project

Clone the Volley project:

git clone https://android.googlesource.com/platform/frameworks/volley

google.JPG

It has created “Volley” folder. Now we have to import this in eclipse or Android studio. FYI, I have been using Git GUI client on my windows machine.

Now suppose If your machine is not having Git client installed and still want to clone repository then Eclipse and ADT Bundle is having option for you to clone repository and import project directly. Refer my previous article for the same: Android – Import projects from Git

2 Main classes of Volley: PAGE TOP

There are 2 main classes:

  1. Request queue
  2. Request

Request queue: It is the interest you use for dispatching requests to the network, you can make a request queue on demand if you want, but typically, you’ll instead create it early on, at startup time, and keep it around and use it as a Singleton.

Request: It contains all the necessary details for making web API call. For example: which method to Use (GET or POST), request data to pass, response listener, error listener.

Take a look at JSONObjectRequest request method:

vadra94.png

Basic example using Volley:

I assume you have already cloned/downloaded Volley library from git repo. Now, follow the steps to create a simple example of fetching tweets and display it into ListView.

Step 1: Make sure you have imported Volley projects into Eclipse, if you haven’t then import it. Now after importing, we need to make it a Library project by Right click => Properties => Android (left panel).

suv.JPG

Step 2: Now, Create a new project with the name VolleyExample.

Step 3: Right click on VolleyExample and Include Volley Library in our project.

fre.JPG

Step 4: Include INTERNET permission inside AndroidManifest.xml file.

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

Step 5:

i) Create an object of RequestQueue class.

1   RequestQueue queue = Volley.newRequestQueue(this);

ii) Create a JSONObjectRequest with response and error listener.

01  String url = "https://www.googleapis.com/customsearch/v1?key=AIzaSyBmSXUzVZBKQv9FJkTpZXn0dObKgEQOIFU&cx=014099860786446192319:t5mr0xnusiy&q=AndroidDev&alt=json&searchType=image";
02  
03  JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, newResponse.Listener<JSONObject>() {
04  
05          @Override
06          public void onResponse(JSONObject response) {
07              // TODO Auto-generated method stub
08              txtDisplay.setText("Response => "+response.toString());
09              findViewById(R.id.progressBar1).setVisibility(View.GONE);
10          }
11      }, new Response.ErrorListener() {
12  
13          @Override
14          public void onErrorResponse(VolleyError error) {
15          // TODO Auto-generated method stub
16  
17          }
18      });

iii) Add your request into the RequestQueue.

1   queue.add(jsObjRequest);

Complete Code of MainActivity.java file:

01  package com.technotalkative.volleyexamplesimple;
02  
03  import org.json.JSONObject;
04  
05  import android.app.Activity;
06  import android.os.Bundle;
07  import android.view.Menu;
08  import android.view.View;
09  import android.widget.TextView;
10  
11  import com.android.volley.Request;
12  import com.android.volley.RequestQueue;
13  import com.android.volley.Response;
14  import com.android.volley.VolleyError;
15  import com.android.volley.toolbox.JsonObjectRequest;
16  import com.android.volley.toolbox.Volley;
17  
18  public class MainActivity extends Activity {
19  
20      private TextView txtDisplay;
21  
22      @Override
23      protected void onCreate(Bundle savedInstanceState) {
24          super.onCreate(savedInstanceState);
25          setContentView(R.layout.activity_main);
26  
27          txtDisplay = (TextView) findViewById(R.id.txtDisplay);
28  
29          RequestQueue queue = Volley.newRequestQueue(this);
30          String url = "https://www.googleapis.com/customsearch/v1?key=AIzaSyBmSXUzVZBKQv9FJkTpZXn0dObKgEQOIFU&cx=014099860786446192319:t5mr0xnusiy&q=AndroidDev&alt=json&searchType=image";
31  
32          JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, newResponse.Listener<JSONObject>() {
33  
34              @Override
35              public void onResponse(JSONObject response) {
36                  // TODO Auto-generated method stub
37                  txtDisplay.setText("Response => "+response.toString());
38                  findViewById(R.id.progressBar1).setVisibility(View.GONE);
39              }
40          }, new Response.ErrorListener() {
41  
42              @Override
43              public void onErrorResponse(VolleyError error) {
44                  // TODO Auto-generated method stub
45  
46              }
47          });
48  
49          queue.add(jsObjRequest);
50  
51      }
52  
53      @Override
54      public boolean onCreateOptionsMenu(Menu menu) {
55          // Inflate the menu; this adds items to the action bar if it is present.
56          getMenuInflater().inflate(R.menu.main, menu);
57          return true;
58      }
59  
60  }

Download Volley library and sample example: https://github.com/PareshMayani/Android-Volley-Example

Video in case you haven missed session: Google I/O 2013 – Volley: Easy, Fast Networking for Android

Reference PAGE TOP

http://www.javacodegeeks.com/2013/06/android-volley-library-example.html

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.