Skip to content

Integrating a REST API ​

Until now, all of your app's data lived on the phone: in its layouts, in SQLite, in shared preferences. Most real apps get their data from a server instead. The app sends an HTTP request to an address, and the server answers with data, usually as JSON text. A server that works this way is called a REST API.

In this lab you build an app that talks to two servers. Get Data downloads a list of students from this site as JSON, turns it into Java objects, and lists them. Add Student sends a new student to a test server as JSON, and shows the server's answer. Both requests run on a background thread, with a spinner while they wait and a clear message if anything goes wrong.

Objectives ​

  • Send HTTP GET and POST requests from Android with HttpURLConnection.
  • Parse a JSON array into Java objects with JSONArray and JSONObject, and build JSON to send.
  • Run network code on a background thread with an ExecutorService, and show the result on the main thread with a Handler.
  • Read HTTP status codes, and handle a missing connection, a timeout and a server error.

Background ​

REST in one paragraph ​

REST (Representational State Transfer) is a style of building web APIs. Each kind of data the server has, such as students, is a resource with its own address, and you work with it using the standard HTTP methods:

MethodMeansExample
GETReadGET /students returns the list of students
POSTCreatePOST /students with a student in the body adds one
PUTReplacePUT /students/3 replaces student 3
DELETEDeleteDELETE /students/3 deletes student 3

In Exp 9 you write a server like this yourself with Spring Boot. In this lab you only write the app side.

A request and its response ​

A request has a method, a URL, some headers and, for POST and PUT, a body. The response has a status code, headers and a body. This is the POST the app sends in this lab, and what the test server answers:

http
POST /users HTTP/1.1
Host: jsonplaceholder.typicode.com
Content-Type: application/json; charset=utf-8
Accept: application/json

{"name":"Ahmad","age":21}
http
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8

{
  "name": "Ahmad",
  "age": 21,
  "id": 11
}

Content-Type says what the body is, and Accept says what you want back. The status code tells you how it went. The first digit is what matters:

CodeMeansYou will see it when
200 OKIt worked, the answer is in the bodyGet Data succeeds
201 CreatedIt worked, something was createdAdd Student succeeds
404 Not FoundThere is nothing at that addressThe URL has a typo
500 Internal Server ErrorThe server crashed handling itThe server has a bug (your Exp 9 server, one day)

Codes from 200 to 299 mean success, 4xx means the request was wrong, and 5xx means the server failed.

JSON ​

JSON is text that describes data with two building blocks: objects in { }, which are named fields, and arrays in [ ], which are lists. This is the start of the file Get Data downloads, /api/students.json:

json
[
  { "id": 1, "name": "Ahmad", "age": 21 },
  { "id": 2, "name": "Omar", "age": 22 }
]

Android includes the org.json classes to read and write it, with no library to add:

JSONClassRead a value with
[ … ]JSONArraylength(), getJSONObject(i)
{ … }JSONObjectgetInt("id"), getString("name"), and put("name", …) to write

Each get method throws a JSONException if the field is missing or has the wrong type, so your code finds out at once when the server sends something unexpected.

Never on the main thread ​

The main thread draws the screen and handles every tap. A network request can take seconds, and if the main thread waited for it, the app would freeze, and after five seconds Android would offer to close it: an ANR (Application Not Responding). So Android doesn't allow it at all: a request on the main thread throws NetworkOnMainThreadException.

The opposite rule also holds: only the main thread may touch views. Setting a TextView's text from another thread throws CalledFromWrongThreadException. So every request in this lab goes the same way:

WhereWhat happensWith
Main threadShow the spinner, start the requestA click listener
Background threadSend the request, wait, parse the JSONexecutor.execute(() -> …)
Main threadHide the spinner, show the students or the errormainHandler.post(() -> …)

An ExecutorService is a pool of background threads that runs the tasks you give it. Executors.newSingleThreadExecutor() makes one with a single thread, so requests run one after another. A Handler made with Looper.getMainLooper() runs the code you post to it on the main thread.

Permissions and HTTPS ​

An app can only use the network if its manifest asks for the INTERNET permission. It is granted when the app is installed, without asking the user.

Since Android 9, apps may also only use HTTPS by default. Both servers in this lab use HTTPS, so there is nothing to change. A plain http:// address fails with Cleartext HTTP traffic … not permitted. You will meet this in Exp 9, when the app calls your own server on your laptop: Differences from the manual shows how to allow it for that one address.

Step 1: Create the project ​

Create a new project as described in Setup Guide → Create a lab project:

FieldValue
TemplateEmpty Views Activity
NameExp8Rest
Package nameedu.birzeit.encs5150.exp8
LanguageJava
Minimum SDKAPI 24

HttpURLConnection, the org.json classes and ExecutorService are all part of Android, so you don't add any dependencies.

Step 2: Ask for the INTERNET permission ​

Open manifests/AndroidManifest.xml and add this line inside <manifest>, above <application>:

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

Without it, every request fails with SecurityException: Permission denied (missing INTERNET permission?).

Step 3: The Student class ​

  1. Right-click the package edu.birzeit.encs5150.exp8 → New → Java Class.
  2. Name it Student and press Enter.
  3. Replace the file's contents with:
java
package edu.birzeit.encs5150.exp8;

/** One student, with the same fields as one object in the JSON array. */
public class Student {

    private final int id;
    private final String name;
    private final int age;

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return id + ". " + name + ", " + age;
    }
}

It has the same three fields as one object in the JSON: id, name and age. The fields are final, so a Student can't change after it is made. toString() gives the line the list shows, such as 1. Ahmad, 21.

Step 4: The JSON parser ​

Create another Java class, StudentJsonParser, and replace its contents with:

java
package edu.birzeit.encs5150.exp8;

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

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

/** Turns JSON text into Student objects, and a new student into JSON. */
public class StudentJsonParser {

    // [ {"id": 1, "name": "…", "age": 21}, … ]  ->  a List of Students
    public static List<Student> fromJsonArray(String json) throws JSONException {
        JSONArray array = new JSONArray(json);
        List<Student> students = new ArrayList<>();
        for (int i = 0; i < array.length(); i++) {
            students.add(fromJson(array.getJSONObject(i)));
        }
        return students;
    }

    // {"id": 1, "name": "…", "age": 21}  ->  one Student
    public static Student fromJson(JSONObject object) throws JSONException {
        return new Student(object.getInt("id"), object.getString("name"), object.getInt("age"));
    }

    // name and age  ->  {"name": "…", "age": 21}. The server chooses the id.
    public static JSONObject toJson(String name, int age) throws JSONException {
        JSONObject object = new JSONObject();
        object.put("name", name);
        object.put("age", age);
        return object;
    }
}
  • fromJsonArray reads the whole reply. new JSONArray(json) parses the text, and the loop turns each object in it into a Student.
  • fromJson reads one object. It is separate because the POST reply is a single object, not an array.
  • toJson goes the other way: it builds the object to send. It has no id, because the server chooses it.

All three throw JSONException instead of catching it, so the caller decides what to show when the JSON is wrong.

Step 5: The HTTP manager ​

Create a Java class, HttpManager, and replace its contents with:

java
package edu.birzeit.encs5150.exp8;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;

/** Sends HTTP requests. Call it from a background thread: on the main thread it throws. */
public class HttpManager {

    /** What the server sent back: the status code (200, 201, 404, …) and the body. */
    public static class Response {
        public final int code;
        public final String body;

        Response(int code, String body) {
            this.code = code;
            this.body = body;
        }

        public boolean isSuccessful() {
            return code >= 200 && code < 300;
        }
    }

    private static final int TIMEOUT_MS = 10_000;

    public static Response get(String address) throws IOException {
        HttpURLConnection connection = open(address);
        try {
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");
            return read(connection);
        } finally {
            connection.disconnect();
        }
    }

    public static Response post(String address, String json) throws IOException {
        HttpURLConnection connection = open(address);
        try {
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);   // this request has a body
            try (OutputStream out = connection.getOutputStream()) {
                out.write(json.getBytes(StandardCharsets.UTF_8));
            }
            return read(connection);
        } finally {
            connection.disconnect();
        }
    }

    private static HttpURLConnection open(String address) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) URI.create(address).toURL().openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);   // give up if the server can't be reached
        connection.setReadTimeout(TIMEOUT_MS);      // give up if it stops answering
        return connection;
    }

    private static Response read(HttpURLConnection connection) throws IOException {
        int code = connection.getResponseCode();   // sends the request and waits for the reply
        // The body of a 4xx or 5xx reply is on the error stream, not the input stream
        InputStream stream = code < 400 ? connection.getInputStream() : connection.getErrorStream();
        StringBuilder body = new StringBuilder();
        if (stream != null) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    body.append(line).append('\n');
                }
            }
        }
        return new Response(code, body.toString());
    }
}
  1. Response holds what came back: the status code and the body as text. isSuccessful() is true for any 2xx code.
  2. open turns the address into a URL and opens an HttpURLConnection. Nothing is sent yet. The two timeouts make a request give up after 10 seconds, instead of waiting for ever on a bad connection.
  3. get sets the method and the Accept header, then reads the reply.
  4. post also sets Content-Type, and setDoOutput(true) says the request has a body. Writing the JSON to getOutputStream() sends it.
  5. read calls getResponseCode(), which sends the request and waits for the answer. A successful body is on getInputStream(), but for a 4xx or 5xx code it is on getErrorStream(), and getInputStream() would throw. The BufferedReader then reads the body line by line.
  6. disconnect() in finally releases the connection, even if something threw.

try (…) is try-with-resources: it closes the stream at the end of the block, even after an exception.

Step 6: The layout ​

Replace the whole res/layout/activity_main.xml with:

xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button_get"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="16dp"
        android:layout_marginTop="16dp"
        android:text="Get Data" />

    <!-- A spinner while a request runs, and what happened -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="16dp"
        android:layout_marginTop="8dp"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ProgressBar
            android:id="@+id/progress"
            style="?android:attr/progressBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:visibility="gone" />

        <TextView
            android:id="@+id/text_status"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Press Get Data to load the students"
            android:textAppearance="@style/TextAppearance.AppCompat.Small" />
    </LinearLayout>

    <!-- The students, one TextView each, added in code -->
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="16dp"
        android:layout_weight="1">

        <LinearLayout
            android:id="@+id/student_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="16dp"
        android:text="Add a student"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="16dp"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/edit_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_weight="2"
            android:hint="Name"
            android:importantForAutofill="no"
            android:inputType="textPersonName" />

        <EditText
            android:id="@+id/edit_age"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="Age"
            android:importantForAutofill="no"
            android:inputType="number"
            android:maxLength="3" />
    </LinearLayout>

    <Button
        android:id="@+id/button_add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="16dp"
        android:layout_marginBottom="16dp"
        android:text="Add Student" />

</LinearLayout>

From top to bottom: the Get Data button, a row with a small ProgressBar (hidden with visibility="gone" until a request runs) and a status TextView, a ScrollView that takes the rest of the screen (layout_height="0dp" with layout_weight="1") holding the empty student_list, and at the bottom the name and age fields and the Add Student button. The age field has inputType="number", so its keyboard has digits only.

Step 7: The Activity ​

Open MainActivity.java and replace the whole file with the code below. The template lines at the top of onCreate stay as they were.

java
package edu.birzeit.encs5150.exp8;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

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

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "Exp8Rest";
    private static final String STUDENTS_URL = "https://encs5150.birzeit.me/api/students.json";
    private static final String ADD_STUDENT_URL = "https://jsonplaceholder.typicode.com/users";

    // One background thread for the requests, and a Handler to get back to the main thread
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    private Button getDataButton;
    private Button addButton;
    private ProgressBar progressBar;
    private TextView statusText;
    private LinearLayout studentList;
    private EditText nameInput;
    private EditText ageInput;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        getDataButton = findViewById(R.id.button_get);
        addButton = findViewById(R.id.button_add);
        progressBar = findViewById(R.id.progress);
        statusText = findViewById(R.id.text_status);
        studentList = findViewById(R.id.student_list);
        nameInput = findViewById(R.id.edit_name);
        ageInput = findViewById(R.id.edit_age);

        getDataButton.setOnClickListener(v -> getStudents());
        addButton.setOnClickListener(v -> addStudent());
    }

    /** GET the list of students and show it. */
    private void getStudents() {
        setBusy(true, "Connecting…");
        executor.execute(() -> {
            // Background thread: the network and the parsing, no views
            try {
                HttpManager.Response response = HttpManager.get(STUDENTS_URL);
                if (!response.isSuccessful()) {
                    showError("The server answered " + response.code);
                    return;
                }
                List<Student> students = StudentJsonParser.fromJsonArray(response.body);
                mainHandler.post(() -> {
                    // Main thread: now it is safe to touch the views
                    setBusy(false, "Got " + students.size() + " students");
                    studentList.removeAllViews();
                    for (Student student : students) {
                        addRow(student);
                    }
                });
            } catch (IOException e) {
                showError(describe(e));
            } catch (JSONException e) {
                showError("The reply is not the JSON we expected");
            }
        });
    }

    /** POST a new student as JSON and show what the server sent back. */
    private void addStudent() {
        String name = nameInput.getText().toString().trim();
        String ageText = ageInput.getText().toString().trim();
        if (name.isEmpty()) {
            nameInput.setError("Enter a name");
            return;
        }
        if (ageText.isEmpty()) {
            ageInput.setError("Enter an age");
            return;
        }
        int age = Integer.parseInt(ageText);   // inputType="number" allows digits only

        setBusy(true, "Sending…");
        executor.execute(() -> {
            try {
                String json = StudentJsonParser.toJson(name, age).toString();
                HttpManager.Response response = HttpManager.post(ADD_STUDENT_URL, json);
                if (!response.isSuccessful()) {
                    showError("The server answered " + response.code);
                    return;
                }
                Student created = StudentJsonParser.fromJson(new JSONObject(response.body));
                mainHandler.post(() -> {
                    setBusy(false, "The server answered " + response.code + " with:\n" + response.body.trim());
                    addRow(created);
                    nameInput.setText("");
                    ageInput.setText("");
                });
            } catch (IOException e) {
                showError(describe(e));
            } catch (JSONException e) {
                showError("The reply is not the JSON we expected");
            }
        });
    }

    private void addRow(Student student) {
        TextView row = new TextView(this);
        row.setText(student.toString());
        row.setTextSize(18);
        row.setPadding(0, 12, 0, 12);
        studentList.addView(row);
    }

    // Called from the background thread: hands the message to the main thread
    private void showError(String message) {
        Log.e(TAG, message);
        mainHandler.post(() -> setBusy(false, message));
    }

    private void setBusy(boolean busy, String message) {
        progressBar.setVisibility(busy ? View.VISIBLE : View.GONE);
        getDataButton.setEnabled(!busy);
        addButton.setEnabled(!busy);
        statusText.setText(message);
    }

    private static String describe(IOException e) {
        if (e instanceof UnknownHostException) {
            return "No internet connection, or the address is wrong";
        }
        if (e instanceof SocketTimeoutException) {
            return "The server took too long to answer";
        }
        return "Network error: " + e.getMessage();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        executor.shutdownNow();   // stop the background thread with the Activity
    }
}
  1. The two URLs are constants at the top. STUDENTS_URL is a JSON file on this site. ADD_STUDENT_URL is JSONPlaceholder, a free test server that answers POST requests like a real API, but doesn't save anything.
  2. executor is the background thread and mainHandler the way back to the main thread, as in Never on the main thread.
  3. getStudents shows the spinner, then gives the executor a lambda. Inside it, everything until mainHandler.post runs on the background thread: the GET, the status check and the parsing. The lambda inside mainHandler.post runs on the main thread and fills the list.
  4. addStudent first checks the two fields on the main thread, and shows an error on an empty field with setError. Then the background thread builds the JSON, sends the POST, and parses the single object the server sends back. The main thread shows the code and the reply, and adds the new student to the list.
  5. The catch blocks turn each failure into a message: IOException when the request didn't get an answer, JSONException when it did but the JSON is wrong. describe gives the two most common IOExceptions a plain sentence.
  6. showError is called from the background thread, so it too goes through mainHandler.post.
  7. setBusy shows or hides the spinner and turns both buttons off while a request runs, so a second tap can't start a second request.
  8. onDestroy shuts the executor down, so its thread doesn't outlive the Activity.

Run and check ​

Run the app, open Logcat in Android Studio, and type Exp8Rest in the search box.

  • Press Get Data. The spinner shows for a moment, then the status says "Got 6 students" and the six students are listed.
  • Type a name and an age and press Add Student. The status shows The server answered 201 with: and the JSON the server sent back, with "id": 11, and the student is added at the end of the list.
  • Press Add Student with an empty field. The field shows an error and nothing is sent.

Now break things on purpose, one at a time, and put each one back afterwards:

Do thisOn screenWhy
Turn on Airplane mode in the emulator (swipe down from the top), then press Get Data"No internet connection, or the address is wrong"Without a network, the name encs5150.birzeit.me can't be looked up: UnknownHostException
Change students.json in STUDENTS_URL to student.json"The server answered 404"The server answered, but there is no file at that address
Change STUDENTS_URL to https://jsonplaceholder.typicode.com/users/1"The reply is not the JSON we expected"That address returns one object, not an array, so new JSONArray throws
Change https to http in STUDENTS_URL"Network error: Cleartext HTTP traffic to encs5150.birzeit.me not permitted"Android allows HTTPS only, as in Permissions and HTTPS
Move the code inside executor.execute(…) out of the lambda, so it runs directly in getStudentsThe app crashesLogcat shows NetworkOnMainThreadException

Every error is also written to Logcat with Log.e, in red.

Differences from the manual ​

The manual's address no longer works, and its code uses AsyncTask, which Android has deprecated. Here is what changed and why.

1. A working address, and a POST ​

The manual downloads its students from a mocky.io address that has been taken down, so its app can no longer get any data. This guide downloads the same kind of list, with the same id, name and age fields, from a file on this site, which stays up as long as the lab does.

The manual's objectives also promise POST requests, but its code only does a GET. This guide adds Add Student, which sends JSON to JSONPlaceholder and reads the 201 Created reply.

2. ExecutorService and Handler instead of AsyncTask ​

java
public class ConnectionAsyncTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... params) {
        return HttpManager.getData(params[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        ((MainActivity) activity).fillStudents(StudentJsonParser.getObjectFromJson(s));
    }
}
java
executor.execute(() -> {
    HttpManager.Response response = HttpManager.get(STUDENTS_URL);
    List<Student> students = StudentJsonParser.fromJsonArray(response.body);
    mainHandler.post(() -> {
        // show the students
    });
});

AsyncTask has been deprecated since Android 11. Its official replacement is the standard java.util.concurrent classes, which is what this guide uses. It also had real problems:

  • It leaked the Activity. The manual's task keeps the Activity in a field. If the screen rotates while it runs, Android destroys that Activity and makes a new one, but the task still holds the old one, and onPostExecute fills a list that is no longer on screen.
  • It needed a cast. ((MainActivity) activity) ties the task to one Activity class. Here the code is a lambda inside MainActivity, so it calls its methods directly.
  • It parsed on the main thread. The manual parses the JSON in onPostExecute, on the main thread. Here the parsing happens in the background, next to the request.

The same two steps also exist in libraries. Retrofit, the most used HTTP library for Android, runs the request on its own thread and calls you back on the main thread. Writing it yourself once with HttpURLConnection shows what such a library does for you.

3. Errors are handled ​

The manual's getData catches every exception, logs it, and returns null, which the parser and fillStudents then use without checking. So any network problem crashes the app with a NullPointerException. Bad JSON does the same: the parser returns a null list.

This guide doesn't hide errors. HttpManager throws them, and MainActivity turns each kind into a message for the user:

ProblemManualThis guide
No connectionCrash"No internet connection, or the address is wrong"
Server never answersWaits for everGives up after 10 seconds: "The server took too long to answer"
404 or 500getInputStream() throws, so it crashes"The server answered 404"
JSON in the wrong shapeCrash"The reply is not the JSON we expected"

It also checks the status code. The manual never calls getResponseCode(), so it can't tell a list of students from an error page.

4. The parser, tidied ​

java
JSONObject jsonObject = new JSONObject();
jsonObject = (JSONObject) jsonArray.get(i);
Student student = new Student();
student.setID(jsonObject.getInt("id"));
student.setName(jsonObject.getString("name"));
student.setAge(jsonObject.getDouble("age"));
java
JSONObject object = array.getJSONObject(i);
return new Student(object.getInt("id"), object.getString("name"), object.getInt("age"));

The manual creates an empty JSONObject only to throw it away on the next line, and casts the result of get(i) where getJSONObject(i) already returns the right type. It also builds each Student empty and fills it with setters. A constructor makes a complete Student in one step, and the fields can be final.

5. The layout ​

The manual's layout uses android.support.constraint.ConstraintLayout, from the old support library, which doesn't exist in a new project: the layout fails to inflate. It also gives the list a fixed size, 395dp by 507dp, which is too big for small phones and leaves a gap on large ones, and the list doesn't scroll. This guide uses a LinearLayout where the list's ScrollView takes whatever space is left.

6. HTTPS, and a narrow exception for your own server ​

The manual's address uses plain http://, so it turns on cleartext (unencrypted) traffic for every address with a base-config. This guide uses HTTPS, which needs no configuration.

In Exp 9, though, the app calls the Spring Boot server on your laptop, which speaks plain HTTP. From the emulator, your laptop is always at the address 10.0.2.2. Allow cleartext for that address only: add a new file res/xml/network_security_config.xml:

xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <!-- Plain HTTP to the emulator's view of your laptop only; HTTPS everywhere else -->
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="false">10.0.2.2</domain>
    </domain-config>
</network-security-config>

and point to it from the <application> tag in the manifest:

xml
<application
    android:networkSecurityConfig="@xml/network_security_config"
    … >

Every other address still needs HTTPS, so the app stays as safe as before.

7. Smaller changes ​

ManualThis guideWhy
getData returns the body as a String, or nullget and post return a Response with the status code and the bodyThe caller can check the code.
new URL(URL)URI.create(address).toURL()The URL constructors are deprecated in current Java. The parameter is also renamed: a variable named URL hides the class URL.
Double ageint ageAges in the JSON are whole numbers.
IDidJava's naming convention: fields start with a lower-case letter.
new View.OnClickListener() { … }A lambda, v -> …Shorter.
import android.support.v7.app.AppCompatActivityandroidx.appcompat.app.AppCompatActivityThe support library was replaced by AndroidX.
The button text changes to "connecting" and "connected"The button is disabled while a request runs, and a status line says what happened"connected" stayed on the button for ever, and a second tap started a second request.

Common problems ​

SymptomCause and fix
SecurityException: Permission denied (missing INTERNET permission?)The <uses-permission> line is missing from the manifest, or is inside <application>. Put it above <application>, as in Step 2.
NetworkOnMainThreadExceptionA request runs on the main thread. Every call to HttpManager must be inside executor.execute(() -> …).
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its viewsA view is changed on the background thread. Wrap that code in mainHandler.post(() -> …).
"No internet connection" on the emulator, but your laptop is onlineThe emulator lost its network. Turn Airplane mode off, or cold-boot the emulator from the Device Manager (the menu next to the device → Cold Boot Now).
Cleartext HTTP traffic to … not permittedThe URL starts with http://. Use https://, or for your own server, the network_security_config.xml in Differences from the manual.
"The reply is not the JSON we expected"The reply isn't an array of objects with id, name and age. Open the URL in a browser to see what it really returns.
JSONException: No value for ageA field name in getInt("…") doesn't match the JSON. Names are case-sensitive: "ID" is not "id".
The spinner never goes awayA path through the background lambda ends without calling mainHandler.post or showError. Every return and every catch must end in one of them.
The added student always gets id 11That's JSONPlaceholder: it only pretends to save, and gives every new user the next id after its ten. A real server, such as yours in Exp 9, saves it and gives a new id each time.

Things to try ​

  • Open /api/students.json and https://jsonplaceholder.typicode.com/users in a browser, then send the same GET and POST from Postman, and compare the status codes and headers with what the app shows.
  • Show the students in a ListView with an ArrayAdapter, as in Exp 2, instead of adding TextViews by hand.
  • Save the downloaded students in the SQLite database from Exp 4, so the list still shows when the phone is offline.
  • Add a Delete button to each row that sends DELETE https://jsonplaceholder.typicode.com/users/{id}. What status code comes back?
  • Rotate the screen while a request runs (set the timeout to a few seconds and use a slow address). The result is lost, because the new Activity never hears about it. Move the request into a ViewModel with LiveData, as in Exp 7, and try again.