Networking HTTP

Resources: Developer Android

Volley overview

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.

Volley offers the following benefits:

  • Automatic scheduling of network requests.

  • Multiple concurrent network connections.

  • Ease of customization, for example, for retry and backoff.

  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.

  • Debugging and tracing tools.

Adding Volley

The easiest way to add Volley to your project is to add the following dependency to your app's build.gradle file:

dependencies {
    ...
    implementation 'com.android.volley:volley:1.1.1'
}

Send a simple request

At a high level, you use Volley by creating a RequestQueue and passing it Request objects.

Add the INTERNET permission

To perform network operations in your application, your manifest must include the following permissions:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testvolley">

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


    <application
    
    ...
</manifest>

Use newRequestQueue

Volley provides a convenience method Volley.newRequestQueue that sets up a RequestQueue for you, using default values, and starts the queue. For example:

  final TextView textView = (TextView) findViewById(R.id.text);
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        String url ="https://www.google.com";

// Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string.
                        textView.setText(response.substring(0,500));
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                textView.setText("That didn't work!");
            }
        });

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

JSON Format

JSON stands for JavaScript Object Notation

JSON is a text format for storing and transporting data

JSON is "self-describing" and easy to understand

JSON Example

This example is a JSON string:

'{"name":"John", "age":30, "car":null}'

It defines an object with 3 properties:

  • name

  • age

  • car

Each property has a value.

If you parse the JSON string with a JavaScript program, you can access the data as an object:

String personName = obj.name;
String personAge = obj.age;

JSON Syntax Rules

JSON syntax is derived from JavaScript object notation syntax:

  • Data is in name/value pairs

  • Data is separated by commas

  • Curly braces hold objects

  • Square brackets hold arrays

JSON Data - A Name and a Value

JSON data is written as name/value pairs (aka key/value pairs).

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

"name":"John"

JSON Values

In JSON, values must be one of the following data types:

  • a string

  • a number

  • an object

  • an array

  • a boolean

  • null

person = {name:"John", age:31, city:"New York"};

JSON Files

  • The file type for JSON files is ".json"

Request JSON

Volley provides the following classes for JSON requests:

  • JsonArrayRequest—A request for retrieving a JSONArray response body at a given URL.

  • JsonObjectRequest—A request for retrieving a JSONObject response body at a given URL, allowing for an optional JSONObject to be passed in as part of the request body.

final TextView textView = (TextView) findViewById(R.id.text);
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        //JSONArrayRequest
        JsonArrayRequest jsonArrayRequest = 
        new JsonArrayRequest(Request.Method.GET,
                "https://api.androidhive.info/json/movies.json", null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject jsonObjectFromArray = 
                                response.getJSONObject(i);
                                Log.d("JSONArray Response", "Movie Title: " + 
                                        jsonObjectFromArray.getString("title"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("JSONArray Error", "Error:" + error);
            }
        });
        queue.add(jsonArrayRequest);

Output:

D: Response: Dawn of the Planet of the Apes
D: Response: District 9
D: Response: Transformers: Age of Extinction
D: Response: X-Men: Days of Future Past
D: Response: The Machinist
D: Response: The Last Samurai
D: Response: The Amazing Spider-Man 2
D: Response: Tangled
D: Response: Rush
D: Response: Drag Me to Hell
D: Response: Despicable Me 2
D: Response: Kill Bill: Vol. 1
D: Response: A Bug's Life
D: Response: Life of Brian
D: Response: How to Train Your Dragon

JSON Deserialization

It is the process of converting a JSON string to a JAVA object, to convert from JSON to Java you need a POJO (Plain Old Java Object) class.

POJOs basically defines an entity. Like in your program, if you want an employee class then you can create a POJO as follows:

 public class Employee
    {
        String name;
        public String id;
        private double salary;
        public Employee(String name, String id,
                        double salary)
        {
            this.name = name;
            this.id = id;
            this.salary = salary;
        }
        public String getName()
        {
            return name;
        }
        public String getId()
        {
            return id;
        }
        public Double getSalary()
        {
            return salary;
        }
    }

In our example found in the JSON object from the following link:

https://api.androidhive.info/json/movies.json

The equivalent Java class will be:

public class Movie {
    private String title;
    private String image;
    private Double rating;
    private Integer releaseYear;
    private ArrayList<String> genre;

    public Movie(String title, String image, Double rating,
                 Integer releaseYear, ArrayList<String> genre) {
        this.title = title;
        this.image = image;
        this.rating = rating;
        this.releaseYear = releaseYear;
        this.genre = genre;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public Double getRating() {
        return rating;
    }

    public void setRating(Double rating) {
        this.rating = rating;
    }

    public Integer getReleaseYear() {
        return releaseYear;
    }

    public void setReleaseYear(Integer releaseYear) {
        this.releaseYear = releaseYear;
    }

    public ArrayList<String> getGenre() {
        return genre;
    }

    public void setGenre(ArrayList<String> genre) {
        this.genre = genre;
    }
}
ArrayList<Movie> movies = new ArrayList<>();

    final TextView textView = (TextView) findViewById(R.id.text);

    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);
    //JSONArrayRequest
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
            "https://api.androidhive.info/json/movies.json", null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject jsonObjectFromArray = 
                            response.getJSONObject(i);

                            JSONArray genre = jsonObjectFromArray
                            .getJSONArray("genre");
                            ArrayList<String> genre_list = new ArrayList<>();
                            for (int j = 0; j < genre.length(); j++) {
                                genre_list.add(genre.get(j).toString());
                            }
                            Movie movie = new Movie(
                                    jsonObjectFromArray.getString("title"),
                                    jsonObjectFromArray.getString("image"),
                                    jsonObjectFromArray.getDouble("rating"),
                                    jsonObjectFromArray.getInt("releaseYear"),
                                    genre_list
                            );

                            movies.add(movie);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("JSONArray Error", "Error:" + error);
        }
    });

queue.add(jsonArrayRequest);

//Log the first movie
Log.d("Movie" , movies.get(0).getImage());

Gson Library

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

Download and Install

dependencies {
  implementation 'com.google.code.gson:gson:2.8.6'
}

Change the Movie class as following:

@SerializedName : An annotation that indicates this member should be serialized to JSON with the provided name value as its field name.


import java.util.ArrayList;
import java.util.List;

public class Movie {
    @SerializedName("title")
    private String title;
    @SerializedName("image")
    private String image;
    @SerializedName("rating")
    private Double rating;
    @SerializedName("releaseYear")
    private Integer releaseYear;
    @SerializedName("genre")
    private ArrayList<String> genre;

    public Movie(String title, String image, Double rating, 
                Integer releaseYear, ArrayList<String> genre) {
        this.title = title;
        this.image = image;
        this.rating = rating;
        this.releaseYear = releaseYear;
        this.genre = genre;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public Double getRating() {
        return rating;
    }

    public void setRating(Double rating) {
        this.rating = rating;
    }

    public Integer getReleaseYear() {
        return releaseYear;
    }

    public void setReleaseYear(Integer releaseYear) {
        this.releaseYear = releaseYear;
    }

    public ArrayList<String> getGenre() {
        return genre;
    }

    public void setGenre(ArrayList<String> genre) {
        this.genre = genre;
    }

}

MainActivity

package com.example.testvolley;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
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.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private Gson gson;

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

        ArrayList<Movie> movies = new ArrayList<>();
        GsonBuilder gsonBuilder = new GsonBuilder();
        gson = gsonBuilder.create();

        final TextView textView = (TextView) findViewById(R.id.text);

        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        //JSONArrayRequest
        JsonArrayRequest jsonArrayRequest = 
        new JsonArrayRequest(Request.Method.GET,
                "https://api.androidhive.info/json/movies.json", null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                Movie movie = 
                                gson.fromJson(response.getJSONObject(i)
                                .toString(), 
                                Movie.class);
                                
                                movies.add(movie);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                        Log.d("Movie", movies.get(0).getTitle());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("JSONArray Error", "Error:" + error);
            }
        });
        queue.add(jsonArrayRequest);
    }
}

Using Break-Points

Last updated

Was this helpful?