How to use Volley (REST API)

Volley Basics

Volley is a nice library from Google that makes HTTP API requests easier and faster. Volley is suitable for most use cases, except very large downloads or streaming operations. It can be used in two kind of requests: String requests or JSON requests. String request returns a string and JSON request returns a json object.

Volley can be used for GET, POST, UPDATE, or DELETE operations. In the example below, we learn how to make a string request with GET operation.

To be able to use Volley we need to do two things: add dependency to volley library and add internet permission to your app.

Add Dependency

Volley needs dependency in build.gradle app level file, as shown in pic below. At the time of writing, the latest volley version was 1.1.1 but you better check if there is a newer version available.

build.gradle (app level)
dependencies {
    ...
    implementation 'com.android.volley:volley:1.1.1'
}

Add Internet Permission

To use Volley, you must add the android.permission.INTERNET permission to your app's manifest file AndroidManifest.xml. Without this, your app won't be able to connect to the internet. The suitable place for the uses-permission is between manifest tag and application tag.

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

Volley Example

In this example, we fetch Chuck Norris jokes from the server. We need two classes as shown below. The first class is MainActivity.java that has the actual code. The second file is activity_main.xml that is the layout file.

MainActivity.java

Copy the code from below to your MainActivity.class. It will be explained in details after the code.

MainActivity.java
// Get Chuck Norris joke from the server somewhere in internet
package com.example.volley;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends AppCompatActivity {

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

    // Get data from api
    public void getResult(View view) {
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "http://api.icndb.com/jokes/random";
        final TextView textView = findViewById(R.id.textfield);

        // Send Volley request to api
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // Response from api is now in string "response"
                textView.setText(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                textView.setText("Error!");
            }
        }) {
        };

        // Add the request to the RequestQueue.
        queue.add(stringRequest);
    }
}

Line 2 is the package name.

Lines 4 - 14 will import the needed libraries.

Actual code starts from line 16. This MainActivity class has two methods: onCreate() and getResult(View view). When starting app, it executes first onCreate() method. It shows only the layout file (activity_main.xml) on the screen. That is all it does here.

The layout file has one button “Get joke” and one text field “Hello Chuck Norris!”. When you click the button, it executes the method getResult(View view) method in line 25)

In line 26 we make a queue for the requests. In our case there will be only one request in the queue.

In line 27 we give the url where we will fetch the Chick Norris joke.

Line 28 defines the textview where we write the response from the server.

Lines 31 - 32 are the actual Volley request. The app will wait here for the response from the server. When it receives the response, it will run the method onResponse(String response). The response string is now in string response. In the onResponse() method line 36, it will show the response string on the screen.

In this example the response string is in json format. It includes several values, such as type, id, joke, and categories. You can make it make usable by parsing the json file and making the screen more beautiful.

activity_main.xml

Copy the code from below to your activity_main.xml. THeis is the layout file and shows the initial stuff on the screen.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Press"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.2"
        android:onClick="getResult" />

    <TextView
        android:id="@+id/textfield"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Chuck Norris!"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>