Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Consuming a RESTful Web Service with Volley

Author: Ian Darwin
Published? true
FormatLanguage: AsciiDoc

Problem:

You want an easy way to access a REST service and have heard that Volley might be the answer.

Solution:

Using Volley, create a RequestQueue, and submit a URL with two "callbacks", a success listener and a failure listener.

Discussion:

Volley, a semi-official Google library, really does make it easy to use REST networking.

First, you have to add the Volley library to your project, as it is not part of the standard Android distribution. The coordinates as of the time of writing are com.android.volley:volley:1.0-SNAPSHOT though the version might have gone up by the time you read this.

With that done, you can initialize a Volley "Request Queue", typically in your onCreate() method.

// Set up the Volley queue for REST processing
queue = Volley.newRequestQueue(this);

Assuming that you want to fetch data in response to a button press or similar event, you will have a View handler to submit the request. Along with the request you will submit a callback handler which Volley will run on the UI thread to display the results.

In this example we use the well-known Google Suggest service, which the Chrome browser uses to make suggestions when you start typing in the browser's search box.

    public void fetchResults(View v) {

String host ="https://suggestqueries.google.com/"; // Amusingly, client=firefox makes the output come back in JSON String baseUrl ="complete/search?output=toolbar&hl=en&client=firefox&q="; String listUrl = mSearchBox.getText().toString();

if (listUrl.length() == 0) { Toast.makeText(this, "Input required!", Toast.LENGTH_SHORT).show(); return; }

// Create a String Request to get information from the provided URL. String requestUrl = host + baseUrl + listUrl; JsonArrayRequest request = new JsonArrayRequest( requestUrl, successListener, failListener);

// Queue the request to do the sending and receiving queue.add(request); }

We ask for the data in JSON as that's the common format for REST services.

The results will be processed by the SuccessListener defined here. For simplicity we display the strings in a large TextView instead of a ListView; elaborating that is an obvious "exercise for the reader".

    /**
     * What we get back from this particular web service is a JSON array containing:
     * 0) A JSON String containing the query string
     * 1) A JSON ARRAY of strings with the results;
     */
    final Response.Listener successListener = new Response.Listener() {
        @Override
        public void onResponse(JSONArray response) {
            try {
                String query = response.getString(0);
                mTextView.append("Original query: " + query + "\n");
                JSONArray rest = response.getJSONArray(1);
                mTextView.setText("We got " + rest.length() + " results:\n");
                for (int i = 0; i < rest.length(); i++) {
                    mTextView.append(rest.getString(i) + "\n");
                }
            } catch (JSONException e) {
                mTextView.append("\n);");
                mTextView.append("FAIL: " + e);
                e.printStackTrace();
            }
        }
    };

See Also:

There is more information on Volley at the official site, http://developer.android.com/training/volley/index.html

Download:

The source code for this project is in the Android Cookbook repository at http://github.com/IanDarwin/Android-Cookbook-Examples, in the subdirectory VolleyDemo.
No records found.