1 May 2014 · About 6 minutes read

Android: Getting Started with Volley

Volley is a library developed by Google for fast, easy networking in Android. It wraps up a lot of boiler plate code that you would normally have to code yourself when connecting to servers, queuing requests, handling errors, caching, etc.

In this post, you’ll learn how to use Volley to perform a basic download of remote data. This will form the basis of consuming a simple RESTful API.

Clone the code on github

A Note on Android Studio

Whilst it’s still very much in Beta, I’m a fan of Android Studio and the new Gradle build system for Android. I use it for all day-to-day Android work without too many issues. In this tutorial, I’ll be using Android Studio & Gradle.

If you haven’t tried it yet, you can download Android Studio from android.com. At the time of writing, Android Studio is at version 0.5.7.

Creating the project

With Android Studio running, create a new Blank Activity project. After naming your project, using the default settings will be fine:

New Project Settings

Add the Volley Library

When your app project is created, we can add Volley to the list of dependencies via Gradle. Somewhat strangely, Google don’t provide a build of Volley for Gradle, but thankfully there are mirrored copies of Volley published for use in Gradle.

We can add one of these mirrors from https://github.com/mcxiaoke/android-volley:

// /app/build.gradle
// ...

dependencies {
  // ...
  compile 'com.mcxiaoke.volley:library:1.0.+'
}

Select Tools > Android > Sync Project with Gradle Files (or hit the toolbar icon) to update your project and expose the Volley classes to your code.

Create a RequestQueue

With Volley in our project, we can start using it to download remote content. Volley uses the concept of RequestQueue to manage requests for content and download them. We can create a global request queue for our application in a customer Application subclass.

Create a new VolleyApplication class with a RequestQueue field. We’ll initialise the RequestQueue in the application’s onCreate method, and keep a static instance of VolleyApplication to let us access the queue from anywhere in our app:

// src/main/java/com/example/volleyapp/app/VolleyApplication.java
// ...

class VolleyApplication extends Application {

  private static VolleyApplication sInstance;

  private RequestQueue mRequestQueue;

  @Override
  public void onCreate() {
    super.onCreate();

    mRequestQueue = Volley.newRequestQueue(this);

    sInstance = this;
  }

  public synchronized static VolleyApplication getInstance() {
    return sInstance;
  }

  public RequestQueue getRequestQueue() {
    return mRequestQueue;
  }
}

Be sure to update your AndroidManifest.xml to specify VolleyApplication as the application’s class. We’ll also need to request the INTERNET permission:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.volleyapp.app">
  <uses-permission android:name="android.permission.INTERNET" />

  <application
    android:name=".VolleyApplication"
    ...>
    ...
  </application>
</manifest>

Download a JSON Feed

Now we can create a request and pass it to Volley. As well as plain text responses, Volley provides some helper classes to download and parse JSON, which is great when consuming APIs:

// src/main/java/com/example/volleyapp/app/MainActivity.java
public class MainActivity extends ActionBarActivity {
  private TextView mTextView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      mTextView = (TextView) findViewById(R.id.text1);

      JsonObjectRequest request = new JsonObjectRequest("http://cblunt.github.io/blog-android-volley/response.json", null,
                                                        new Response.Listener<JSONObject>() {

                                                            @Override
                                                            public void onResponse(JSONObject response) {

                                                                mTextView.setText(response.toString());
                                                            }
                                                        },

                                                        new Response.ErrorListener() {

                                                            @Override
                                                            public void onErrorResponse(VolleyError error) {
                                                                mTextView.setText(error.toString());
                                                            }
                                                        }
      );
      VolleyApplication.getInstance().getRequestQueue().add(request);
  }

In this example, we’re fetching the remote and simply displaying it in a TextView (remember to set the TextView id in your activity_main.xml layout file). If something goes wrong, the ErrorListener will display the error message in the TextView.

The second parameter of the JsonObjectRequest is an optional JSONObject to be sent with the request. If set, the request will be submitted as an HTTP POST request, otherwise it will be a GET request. Again, this is helpful if we’re dealing with a RESTful API.

Finally, with the request created, we can add it to the app’s RequestQueue for Volley to handle. Run your app to see the returned JSON response:

Successful JSON Request

Fast, Easy Networking for Android

With Volley, performing networking takes no time at all. In upcoming posts we’ll look at downloading images using Volley’s built-in ImageRequest, and finally put everything together to consume a simple JSON API.

Clone the code on github

Learn how to keep your Rails apps fast, secure and running in top condition.

The Ruby and Rails worlds move fast, so it can feel like no time at all before your app starts to feel left behind.

Slow pages, memory, new gems, a constant stream of security patches, changing third-party APIs, and growing demands on your server's resources all work tirelessly against your app.

While your app launched with a strong foundation— the latest gems, employing best practices, and developing a thorough test suite—it needs constant attention and maintenance to keep running in top condition.

In Keep Your Ruby on Rails App Healthy, you'll learn about the tools and techniques for keeping your Ruby on Rails app running smoothly, and how to apply them to your apps.

The course delivers a range of practical and actionable lessons to enhance and protect your app right away, from simple, quick–win optimisations and setting up thorough monitoring to reviewing your site's performance, and checking your code against security vulnerabilities current best practices.

“I really enjoyed the book. A lot of quick wins for me to implement and makes me realise I can do more with guard.” –– Ben (@r0_0tKat)

Keep Your Ruby on Rails App Healthy is available as both an email course, and as a premium download edition.

The email course is split up into 7 lessons, delivered to your inbox over the course of a month.

The premium edition is available for instant download in PDF, ePub and Mobi (Kindle) format.

Start Email Course Buy Premium $9 (plus EU VAT)

howto programming android api tutorial volley networking restful json
Chris Blunt
Chris Blunt @cblunt
Chris is the founder of Plymouth Software. As well as code and business, he enjoys being a Dad, swimming, and the fine art of drinking tea.