Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester

Week 12 Lab 12 – Display Data from an API Using Retrofit and a RecyclerView

Week 12 – Maps and Consuming Web Services over HTTP · 180 min read · 8 MCQs to check yourself

ProgrammingHut – Getting started with Retrofit (Java)

Android Coding with Harsha – RecyclerView in Android Studio (Java)

Objective

Download a list of people from a real REST API with Retrofit (Java, enqueue), convert the JSON into Java objects with Gson, and show them in a RecyclerView, with a loading spinner and an error box with Retry. CLOs: CLO-2 (develop apps that use web services), CLO-4 (use modern libraries – Retrofit, Gson, RecyclerView, Network Inspector).

What you will build in CampusMate

A Directory screen (DirectoryActivity) that lists campus contacts from https://jsonplaceholder.typicode.com/users:

Row shows JSON field
Name (bold) name
Email email
City address.city (a nested object)

Workflow

Step What you do File
1 Add dependencies and the INTERNET permission build.gradle.kts (Module :app), manifest
2 Look at the JSON and write model classes User.java, Address.java
3 Write the API interface ApiService.java
4 Create one Retrofit object RetrofitClient.java
5 Row layout + adapter item_user.xml, UserAdapter.java
6 Screen layout: list, spinner, error box activity_directory.xml
7 Load data with enqueue DirectoryActivity.java
8 Run, test offline, inspect the network Emulator

Step 1 – Dependencies and permission

build.gradle.kts (Module :app) → dependencies { … } then Sync Now:

implementation("com.squareup.retrofit2:retrofit:2.11.0")
implementation("com.squareup.retrofit2:converter-gson:2.11.0")
implementation("androidx.recyclerview:recyclerview:1.3.2")

(The Gradle file is written in Kotlin script – our app code stays Java.) Manifest, above <application>:

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

Step 2 – Model classes (match the JSON)

Open the URL in a browser. One item looks like:

{ "id": 1, "name": "Leanne Graham", "email": "Sincere@april.biz",
  "address": { "street": "Kulas Light", "city": "Gwenborough" } }

address is a nested JSON object, so it gets its own class:

// Address.java
package com.example.campusmate;

public class Address {
    private String city;
    public String getCity() { return city; }
}
// User.java – field names MUST match the JSON keys
package com.example.campusmate;

public class User {
    private int id;
    private String name;
    private String email;
    private Address address;            // nested object

    public int getId() { return id; }
    public String getName() { return name; }
    public String getEmail() { return email; }
    public Address getAddress() { return address; }
}

Fields we do not need (phone, website…) are simply ignored by Gson.

Step 3 – The API interface

// ApiService.java
package com.example.campusmate;

import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiService {
    @GET("users")                       // BASE_URL + "users"
    Call<List<User>> getUsers();
}

Step 4 – One Retrofit object for the whole app

// RetrofitClient.java
package com.example.campusmate;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    private static final String BASE_URL = "https://jsonplaceholder.typicode.com/"; // must end with /
    private static ApiService api;

    public static ApiService getApi() {
        if (api == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())  // JSON ⇄ Java objects
                    .build();
            api = retrofit.create(ApiService.class);
        }
        return api;
    }
}

Step 5 – Row layout and adapter

res/layout/item_user.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tvEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvCity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
// UserAdapter.java
package com.example.campusmate;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {

    private final List<User> users = new ArrayList<>();

    public void setUsers(List<User> newUsers) {
        users.clear();
        users.addAll(newUsers);
        notifyDataSetChanged();             // redraw the rows with the new data
    }

    // 1. ViewHolder: holds the views of ONE row
    static class UserViewHolder extends RecyclerView.ViewHolder {
        TextView tvName, tvEmail, tvCity;
        UserViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tvName);
            tvEmail = itemView.findViewById(R.id.tvEmail);
            tvCity = itemView.findViewById(R.id.tvCity);
        }
    }

    // 2. Create a row (called only a few times – rows are recycled)
    @NonNull
    @Override
    public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user, parent, false);
        return new UserViewHolder(v);
    }

    // 3. Put the data of position into the row
    @Override
    public void onBindViewHolder(@NonNull UserViewHolder h, int position) {
        User u = users.get(position);
        h.tvName.setText(u.getName());
        h.tvEmail.setText(u.getEmail());
        h.tvCity.setText("City: " + u.getAddress().getCity());
    }

    // 4. How many rows?
    @Override
    public int getItemCount() {
        return users.size();
    }
}

Step 6 – Screen layout (activity_directory.xml)

Create DirectoryActivity (Empty Views Activity, Java) and use:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvUsers"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ProgressBar
        android:id="@+id/progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

    <LinearLayout
        android:id="@+id/errorBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <TextView
            android:id="@+id/tvError"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Could not load data" />

        <Button
            android:id="@+id/btnRetry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Retry" />
    </LinearLayout>
</FrameLayout>

Step 7 – Load the data with enqueue (DirectoryActivity.java)

package com.example.campusmate;

import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DirectoryActivity extends AppCompatActivity {

    private ProgressBar progress;
    private View errorBox;
    private TextView tvError;
    private final UserAdapter adapter = new UserAdapter();

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

        RecyclerView rv = findViewById(R.id.rvUsers);
        rv.setLayoutManager(new LinearLayoutManager(this));   // vertical list
        rv.setAdapter(adapter);

        progress = findViewById(R.id.progress);
        errorBox = findViewById(R.id.errorBox);
        tvError = findViewById(R.id.tvError);
        findViewById(R.id.btnRetry).setOnClickListener(v -> loadUsers());

        loadUsers();
    }

    private void loadUsers() {
        progress.setVisibility(View.VISIBLE);
        errorBox.setVisibility(View.GONE);

        // enqueue = run on a background thread, call back on the MAIN thread
        RetrofitClient.getApi().getUsers().enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(@NonNull Call<List<User>> call, @NonNull Response<List<User>> response) {
                progress.setVisibility(View.GONE);
                if (response.isSuccessful() && response.body() != null) {
                    adapter.setUsers(response.body());
                } else {
                    showError("Server error: " + response.code());
                }
            }

            @Override
            public void onFailure(@NonNull Call<List<User>> call, @NonNull Throwable t) {
                progress.setVisibility(View.GONE);
                showError("No internet? " + t.getMessage());   // e.g. airplane mode
            }
        });
    }

    private void showError(String msg) {
        tvError.setText(msg);
        errorBox.setVisibility(View.VISIBLE);
    }
}

Why not call the API directly in onCreate? A network call on the main thread would freeze the screen, so Android throws NetworkOnMainThreadException. enqueue() runs it in the background and delivers the result back on the main thread, where we may update views. (execute() would run it on the calling thread – never use it on the main thread.)

Open the screen from the Home tab: startActivity(new Intent(requireContext(), DirectoryActivity.class));

Step 8 – Run, test and inspect

Test Expected result
Open Directory with internet Spinner, then 10 people with name, email and city
Airplane mode on → open Error box "No internet? …" with Retry
Airplane mode off → Retry List loads
Change "users" to "userz" "Server error: 404"
View → Tool Windows → App Inspection → Network Inspector Shows the GET request and the JSON response

Common errors and fixes

Problem Fix
SecurityException: Permission denied (missing INTERNET permission?) Add the INTERNET permission (Step 1)
IllegalArgumentException: baseUrl must end in / Add / at the end of BASE_URL
List is empty, no error Forgot setLayoutManager or notifyDataSetChanged()
Names are null Java field names do not match the JSON keys

Short and long questions

1. (Viva) Explain the role of onCreateViewHolder and onBindViewHolder in your adapter.

Model answer

onCreateViewHolder inflates item_user.xml and wraps it in a ViewHolder that caches the TextViews; onBindViewHolder takes the User at the given position and sets its name, email and city into those TextViews.

2. (Viva) What are the steps to use Retrofit in your project?

Model answer

Add the retrofit and converter-gson dependencies and the INTERNET permission; create Java model classes matching the JSON (User, Address); define an interface with @GET("users") Call<List<User>> getUsers();; build Retrofit with a baseUrl ending in / and GsonConverterFactory and create the service; call getUsers().enqueue(new Callback<...>() {...}) and show the data in onResponse.

3. (Viva) How did your app handle loading and errors?

Model answer

It showed a ProgressBar before the request and hid it in both onResponse and onFailure; on a failure or an unsuccessful response it displayed an error box with a Retry button that calls loadUsers() again.

4. (Viva) Why can't we call the API directly on the main thread in onCreate?

Model answer

Network calls on the main thread throw NetworkOnMainThreadException and would freeze the UI. call.enqueue(callback) runs the request on a background thread and calls onResponse/onFailure on the main thread, where the views are updated.

This lesson ends with a quiz of 8 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: Week 12 Theory – Displaying Maps; Consuming Web Services Using HTTP · Next: Week 13 Theory – Web Services – Accessing and Creating

All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester