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