Paramclasses Academy - Blog

Tutorials Details

←
Post 26 of 40
→

What is REST API Integration in Android Studio Using Java: Fetch JSON Data ?

What is REST API Integration in Android Studio Using Java: Fetch JSON Data ?

November 3, 2026

1. Introduction

Modern Android applications often need data from online servers. For example:

  • A weather app fetches weather information.

  • A shopping app fetches product details.

  • A news app fetches the latest articles.

  • A social media app fetches posts and user profiles.

To communicate with a server, Android applications commonly use REST APIs.

In this tutorial, we will learn how to send an HTTP GET request from an Android application, receive JSON data, parse it using Java, and display the result on the screen.

We will build a simple Post Details App using the free JSONPlaceholder testing API.

2. What Is a REST API?

REST stands for Representational State Transfer.

A REST API allows two applications to communicate over HTTP.

For example:

  1. An Android app sends a request to a server.

  2. The server processes the request.

  3. The server returns a response.

  4. The Android app reads and displays the response.

A REST API commonly uses these HTTP methods:

  • GET: Retrieve data from a server.

  • POST: Send new data to a server.

  • PUT: Replace existing data.

  • PATCH: Update selected data.

  • DELETE: Remove data.

In this tutorial, we will focus on the GET method.

3. What Is JSON?

JSON stands for JavaScript Object Notation.

It is a lightweight format used to exchange structured data between applications.

Example JSON response:

{
    "userId": 1,
    "id": 1,
    "title": "Introduction to Android",
    "body": "Android development with Java"
}

This JSON contains four key-value pairs:

  • userId: The user ID.

  • id: The post ID.

  • title: The post title.

  • body: The post description.

Android provides built-in classes such as JSONObject and JSONArray to read JSON data.

4. Understanding an API Endpoint

An API endpoint is a URL where an application can request data.

For this tutorial, we will use:

https://jsonplaceholder.typicode.com/posts/1

This endpoint returns one sample post.

You can open this URL in a browser to see its JSON response.

JSONPlaceholder is a free testing service. It provides sample data for practicing API integration.

5. Create a New Android Studio Project

Follow these steps:

  1. Open Android Studio.

  2. Click New Project.

  3. Select Empty Views Activity.

  4. Enter the project name: RestApiDemo.

  5. Select Java as the programming language.

  6. Choose your minimum SDK.

  7. Click Finish.

Wait until Gradle sync completes.

6. Add Internet Permission

An Android application needs internet permission to communicate with an online API.

Open:

app > manifests > AndroidManifest.xml

Add this permission above the <application> tag:

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

Example:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

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

    <application
        android:allowBackup="true"
        android:label="RestApiDemo"
        android:supportsRtl="true">

        <!-- Application components -->

    </application>

</manifest>

Important: INTERNET is a normal Android permission. You do not need to request it through a runtime permission dialog.

7. Design the Application Screen

Open:

app > res > layout > activity_main.xml

Replace the existing layout with this XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="REST API Demo"
        android:textSize="24sp"
        android:textStyle="bold"
        android:gravity="center"
        android:layout_marginBottom="20dp" />

    <Button
        android:id="@+id/btnFetch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetch Post Data" />

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Post title will appear here"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_marginTop="25dp" />

    <TextView
        android:id="@+id/txtBody"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Post description will appear here"
        android:textSize="16sp"
        android:layout_marginTop="12dp" />

</LinearLayout>

Understanding the XML

  • btnFetch: Button used to request data from the API.

  • txtTitle: Displays the post title.

  • txtBody: Displays the post description.

  • LinearLayout: Arranges the views vertically.

8. Write Java Code to Fetch JSON Data

Open:

app > java > your_package_name > MainActivity.java

Replace the existing code with:

package com.example.restapidemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    Button btnFetch;
    TextView txtTitle, txtBody;

    ExecutorService executorService;
    Handler mainHandler;

    String apiUrl =
            "https://jsonplaceholder.typicode.com/posts/1";

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

        btnFetch = findViewById(R.id.btnFetch);
        txtTitle = findViewById(R.id.txtTitle);
        txtBody = findViewById(R.id.txtBody);

        executorService = Executors.newSingleThreadExecutor();
        mainHandler = new Handler(Looper.getMainLooper());

        btnFetch.setOnClickListener(v -> {
            fetchPostData();
        });
    }

    private void fetchPostData() {

        btnFetch.setEnabled(false);
        btnFetch.setText("Loading...");

        executorService.execute(() -> {

            HttpURLConnection connection = null;

            try {

                URL url = new URL(apiUrl);

                connection = (HttpURLConnection)
                        url.openConnection();

                connection.setRequestMethod("GET");
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(10000);

                int responseCode =
                        connection.getResponseCode();

                if (responseCode != HttpURLConnection.HTTP_OK) {
                    throw new Exception(
                            "Server returned HTTP " + responseCode
                    );
                }

                InputStream inputStream =
                        connection.getInputStream();

                StringBuilder result = new StringBuilder();

                try (BufferedReader reader =
                             new BufferedReader(
                                     new InputStreamReader(
                                             inputStream,
                                             StandardCharsets.UTF_8
                                     ))) {

                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                }

                JSONObject jsonObject =
                        new JSONObject(result.toString());

                String title =
                        jsonObject.getString("title");

                String body =
                        jsonObject.getString("body");

                mainHandler.post(() -> {

                    txtTitle.setText(title);
                    txtBody.setText(body);

                    btnFetch.setEnabled(true);
                    btnFetch.setText("Fetch Post Data");

                });

            } catch (Exception e) {

                mainHandler.post(() -> {

                    Toast.makeText(
                            MainActivity.this,
                            "Error: " + e.getMessage(),
                            Toast.LENGTH_LONG
                    ).show();

                    btnFetch.setEnabled(true);
                    btnFetch.setText("Fetch Post Data");

                });

            } finally {

                if (connection != null) {
                    connection.disconnect();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        executorService.shutdown();
    }
}

Note: If your package name is different, keep the package declaration generated by your own Android Studio project. The remaining code can be used below it.

9. Understand the Important Java Code

A. Create a Background Thread

executorService = Executors.newSingleThreadExecutor();

This creates a background executor.

Network requests should not run on the main UI thread because slow network operations can freeze the application.

B. Create the API URL

URL url = new URL(apiUrl);

This converts the API address into a Java URL object.

C. Open the HTTP Connection

connection = (HttpURLConnection)
        url.openConnection();

This creates an HTTP connection to the API server.

D. Set the Request Method

connection.setRequestMethod("GET");

This tells the server that we want to retrieve data.

E. Check the HTTP Response Code

int responseCode = connection.getResponseCode();

The response code tells us whether the server successfully processed the request.

For example:

  • 200: OK – request successful.

  • 201: Created – resource created.

  • 400: Bad Request.

  • 401: Unauthorized.

  • 404: Not Found.

  • 500: Internal Server Error.

Our example continues only when the response is HTTP 200.

F. Read the JSON Response

StringBuilder result = new StringBuilder();

The StringBuilder collects the response received from the server.

The BufferedReader reads the response line by line.

G. Convert the Response into JSONObject

JSONObject jsonObject =
        new JSONObject(result.toString());

The server sends JSON as text. JSONObject converts that text into an object that Java can read.

H. Extract JSON Values

String title = jsonObject.getString("title");

String body = jsonObject.getString("body");

These statements retrieve the values associated with the title and body keys.

I. Update the Android Screen

mainHandler.post(() -> {
    txtTitle.setText(title);
    txtBody.setText(body);
});

Network operations run in the background, but Android UI components must be updated on the main thread.

The Handler sends the result back to the main thread.

10. Run and Test the Application

Follow these steps:

  1. Start your Android emulator or connect a real Android phone.

  2. Make sure the device has an internet connection.

  3. Run the application.

  4. Tap the Fetch Post Data button.

  5. Wait for the API response.

The application should display the title and body received from the server.

If you tap the button again, it will request the data again.

11. Difference Between JSONObject and JSONArray

JSON responses can contain a single object or an array of objects.

JSONObject Example

{
    "id": 1,
    "title": "Android Development"
}

Read it using:

JSONObject object = new JSONObject(jsonString);

String title = object.getString("title");

JSONArray Example

[
    {
        "id": 1,
        "title": "First Post"
    },
    {
        "id": 2,
        "title": "Second Post"
    }
]

Read it using:

JSONArray array = new JSONArray(jsonString);

for (int i = 0; i < array.length(); i++) {

    JSONObject object = array.getJSONObject(i);

    String title = object.getString("title");

    System.out.println(title);
}

Remember:

  • JSONObject is used for a JSON object.

  • JSONArray is used for a JSON array.

  • getString() reads a string value.

  • getInt() reads an integer value.

  • getBoolean() reads a Boolean value.

12. Common Errors in REST API Integration

Error 1: Internet Permission Missing

Problem: The application cannot access the internet.

Solution: Add the INTERNET permission in AndroidManifest.xml.

Error 2: NetworkOnMainThreadException

Problem: A network request is running on the main UI thread.

Solution: Use an ExecutorService or another background networking mechanism.

Error 3: HTTP 404 Error

Problem: The requested API endpoint does not exist.

Solution: Check the API URL and endpoint.

Error 4: JSON Parsing Error

Problem: The response is not valid JSON or the expected key is missing.

Solution: Check the actual server response and use the correct JSON key.

Error 5: No Internet Connection

Problem: The device cannot reach the server.

Solution: Check the internet connection and try again.

13. REST API Best Practices

When integrating APIs into real Android applications, follow these practices:

  1. Always use HTTPS for secure communication.

  2. Never perform network requests on the main thread.

  3. Set connection and read timeouts.

  4. Handle HTTP error responses properly.

  5. Handle invalid or missing JSON fields.

  6. Disconnect HTTP connections after use.

  7. Do not store secret API keys directly in the application source code.

  8. Avoid displaying sensitive server error details to end users.

  9. Use a structured networking library such as Retrofit when an application grows.

HttpURLConnection is useful for learning how HTTP requests work. Retrofit can simplify API integration in larger applications.

14. Conclusion

In this tutorial, we learned how REST APIs allow Android applications to communicate with online servers.

We created a Post Details App using Java and JSONPlaceholder.

We covered:

  • REST API fundamentals.

  • HTTP GET requests.

  • JSON objects and arrays.

  • Internet permission.

  • HttpURLConnection.

  • Background network operations.

  • JSONObject parsing.

  • Displaying API data in TextViews.

  • HTTP response codes and error handling.

These concepts are important for building real-world Android applications that use online data.

15. Frequently Asked Questions

Q1. What is a REST API in Android?

A REST API allows an Android application to communicate with a remote server using HTTP methods such as GET, POST, PUT, PATCH and DELETE.

Q2. What is JSON parsing?

JSON parsing means reading structured JSON data and extracting the required values from it.

Q3. Why do we use HttpURLConnection?

HttpURLConnection allows Java applications to create HTTP connections and send requests to web servers.

Q4. Why should network requests run in the background?

Network requests can take time. Running them on the main thread can freeze the user interface and cause application errors.

Q5. What is the difference between JSONObject and JSONArray?

JSONObject represents a single JSON object, while JSONArray represents a collection of JSON values or objects.

Q6. Is Retrofit necessary for REST API integration?

No. Android developers can use HttpURLConnection directly. Retrofit is a popular library that simplifies networking and response conversion in larger applications.

←
Post 26 of 40
→