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

Project Step 4 – Events List and Detail: RecyclerView, Countdown, Map, Call, Web, SMS and Email (Labs 4, 6, 11–14)

Course Project (Java) – Build a Modern Cloud App Step by Step (CampusPulse + 7 ideas) · 150 min read · 6 MCQs to check yourself

RecyclerView adapters explained (Hindi/Urdu) – optional: ListAdapter/DiffUtil is a faster upgrade of our simple adapter

Goal

Show the events in a modern list (RecyclerView – Lab 12) with category chips and pull-to-refresh, and open an event detail screen (Lab 4) that has a live countdown (Lab 13), Open in Maps (Lab 14), Call and Website buttons (Lab 6), and Share by SMS / Email (Lab 11). Data comes from the offline Repository for now.

4.1 List item – res/layout/item_event.xml

<com.google.android.material.card.MaterialCardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:layout_marginHorizontal="16dp" android:layout_marginVertical="6dp"
    app:cardCornerRadius="20dp" style="@style/Widget.Material3.CardView.Elevated">

    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
        android:orientation="horizontal" android:padding="14dp" android:gravity="center_vertical">

        <!-- Date badge -->
        <LinearLayout android:layout_width="56dp" android:layout_height="64dp"
            android:background="@drawable/bg_gradient" android:gravity="center" android:orientation="vertical">
            <TextView android:id="@+id/tvDay" android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:textColor="@color/white" android:textSize="22sp" android:textStyle="bold" />
            <TextView android:id="@+id/tvMonth" android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:textColor="@color/white" android:textSize="12sp" />
        </LinearLayout>

        <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1"
            android:layout_marginStart="14dp" android:orientation="vertical">
            <TextView android:id="@+id/tvTitle" android:layout_width="match_parent" android:layout_height="wrap_content"
                android:textAppearance="?attr/textAppearanceTitleMedium" android:maxLines="2" android:ellipsize="end" />
            <TextView android:id="@+id/tvMeta" android:layout_width="match_parent" android:layout_height="wrap_content"
                android:textAppearance="?attr/textAppearanceBodySmall" android:alpha="0.75" />
        </LinearLayout>

        <com.google.android.material.chip.Chip android:id="@+id/tvCategory"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:clickable="false" style="@style/Widget.Material3.Chip.Suggestion" />
    </LinearLayout>
</com.google.android.material.card.MaterialCardView>

4.2 Adapter – ui/EventAdapter.java

The adapter turns each Event into one card. setItems() replaces the list and redraws it – the same idea as Lab 12.

package pk.edu.uni.campuspulse.ui;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import pk.edu.uni.campuspulse.Util;
import pk.edu.uni.campuspulse.data.Event;
import pk.edu.uni.campuspulse.databinding.ItemEventBinding;

public class EventAdapter extends RecyclerView.Adapter<EventAdapter.Holder> {

    public interface OnEventClick { void onClick(Event event); }

    private final List<Event> items = new ArrayList<>();
    private final OnEventClick onClick;

    public EventAdapter(OnEventClick onClick) {
        this.onClick = onClick;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setItems(List<Event> list) {
        items.clear();
        items.addAll(list);
        notifyDataSetChanged();          // redraw the list
    }

    static class Holder extends RecyclerView.ViewHolder {
        final ItemEventBinding b;
        Holder(ItemEventBinding b) {
            super(b.getRoot());
            this.b = b;
        }
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new Holder(ItemEventBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull Holder h, int position) {
        Event e = items.get(position);
        ZonedDateTime t = Util.parseTime(e.startsAt);
        h.b.tvDay.setText(t.format(DateTimeFormatter.ofPattern("dd")));
        h.b.tvMonth.setText(t.format(DateTimeFormatter.ofPattern("MMM")).toUpperCase());
        h.b.tvTitle.setText(e.title);
        h.b.tvMeta.setText(t.format(DateTimeFormatter.ofPattern("EEE, h:mm a")) + " · "
                + (e.venue != null ? e.venue : "Venue TBA"));
        h.b.tvCategory.setText(e.category);
        h.itemView.setOnClickListener(v -> onClick.onClick(e));
    }

    @Override
    public int getItemCount() {
        return items.size();
    }
}

4.3 Home screen – fragment_home.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- Gradient welcome card -->
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_margin="16dp" android:background="@drawable/bg_gradient"
        android:orientation="vertical" android:padding="20dp">
        <TextView android:id="@+id/tvHello" android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:textColor="@color/white" android:textSize="22sp" android:textStyle="bold" />
        <TextView android:id="@+id/tvCount" android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:textColor="@color/white" android:alpha="0.9" />
    </LinearLayout>

    <HorizontalScrollView android:layout_width="match_parent" android:layout_height="wrap_content"
        android:scrollbars="none" android:paddingHorizontal="16dp">
        <com.google.android.material.chip.ChipGroup android:id="@+id/chips"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            app:singleLine="true" app:singleSelection="true" app:selectionRequired="true"
            app:checkedChip="@+id/chipAll">
            <com.google.android.material.chip.Chip android:id="@+id/chipAll" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="All" style="@style/Widget.Material3.Chip.Filter" />
            <com.google.android.material.chip.Chip android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:text="Academic" style="@style/Widget.Material3.Chip.Filter" />
            <com.google.android.material.chip.Chip android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:text="Sports" style="@style/Widget.Material3.Chip.Filter" />
            <com.google.android.material.chip.Chip android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:text="Tech" style="@style/Widget.Material3.Chip.Filter" />
            <com.google.android.material.chip.Chip android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:text="Cultural" style="@style/Widget.Material3.Chip.Filter" />
        </com.google.android.material.chip.ChipGroup>
    </HorizontalScrollView>

    <TextView android:id="@+id/tvEmpty" android:layout_width="match_parent" android:layout_height="wrap_content"
        android:gravity="center" android:padding="32dp" android:text="@string/no_events" android:visibility="gone" />

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout android:id="@+id/swipe"
        android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1">
        <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler"
            android:layout_width="match_parent" android:layout_height="match_parent"
            android:clipToPadding="false" android:paddingBottom="16dp" />
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</LinearLayout>

4.4 ui/HomeFragment.java

package pk.edu.uni.campuspulse.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.chip.Chip;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;

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

import pk.edu.uni.campuspulse.EventDetailActivity;
import pk.edu.uni.campuspulse.Prefs;
import pk.edu.uni.campuspulse.R;
import pk.edu.uni.campuspulse.data.Event;
import pk.edu.uni.campuspulse.data.Repository;
import pk.edu.uni.campuspulse.databinding.FragmentHomeBinding;

public class HomeFragment extends Fragment {
    private FragmentHomeBinding b;
    private final EventAdapter adapter = new EventAdapter(this::openDetail);
    private List<Event> all = new ArrayList<>();

    public HomeFragment() {
        super(R.layout.fragment_home);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        b = FragmentHomeBinding.bind(view);
        String name = Prefs.getFullName() != null ? Prefs.getFullName() : "there";
        b.tvHello.setText(getString(R.string.hello_name, name));
        b.recycler.setLayoutManager(new LinearLayoutManager(requireContext()));
        b.recycler.setAdapter(adapter);
        b.swipe.setOnRefreshListener(this::load);
        b.chips.setOnCheckedStateChangeListener((group, checkedIds) -> showList());
    }

    @Override
    public void onResume() {
        super.onResume();
        load();               // also refreshes after adding/deleting an event
    }

    public void load() {
        if (b == null) return;
        b.swipe.setRefreshing(true);
        Repository.events(new Repository.Result<List<Event>>() {
            @Override
            public void ok(List<Event> events) {
                if (b == null) return;               // the screen was closed meanwhile
                b.swipe.setRefreshing(false);
                all = events;
                showList();
            }

            @Override
            public void fail(String message) {
                if (b == null) return;
                b.swipe.setRefreshing(false);
                Snackbar.make(b.getRoot(), message, Snackbar.LENGTH_LONG).setAction("Retry", v -> load()).show();
            }
        });
    }

    private void showList() {
        int chipId = b.chips.getCheckedChipId();
        String category = null;
        if (chipId != View.NO_ID && chipId != R.id.chipAll) {
            Chip chip = b.chips.findViewById(chipId);
            category = chip.getText().toString();
        }
        List<Event> list = new ArrayList<>();
        for (Event e : all) {
            if (category == null || category.equals(e.category)) list.add(e);
        }
        adapter.setItems(list);
        b.tvEmpty.setVisibility(list.isEmpty() ? View.VISIBLE : View.GONE);
        b.tvCount.setText(getResources().getQuantityString(R.plurals.events_count, list.size(), list.size()));
    }

    private void openDetail(Event e) {
        // Lab 4 – pass the whole event to the next screen as a JSON extra
        Intent i = new Intent(requireContext(), EventDetailActivity.class);
        i.putExtra("event", new Gson().toJson(e));
        startActivity(i);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        b = null;                 // avoid memory leaks
    }
}

4.5 Detail screen – EventDetailActivity

Create Empty Views Activity EventDetailActivity. Layout activity_event_detail.xml:

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

    <com.google.android.material.appbar.MaterialToolbar android:id="@+id/toolbar"
        android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" />

    <ScrollView android:layout_width="match_parent" android:layout_height="match_parent">
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
        android:orientation="vertical" android:padding="16dp">

        <TextView android:id="@+id/tvTitle" android:layout_width="match_parent" android:layout_height="wrap_content"
            android:textAppearance="?attr/textAppearanceHeadlineSmall" android:textStyle="bold" />
        <com.google.android.material.chip.Chip android:id="@+id/chipCategory" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:clickable="false" />

        <!-- Countdown card (Lab 13) -->
        <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_marginTop="12dp" android:background="@drawable/bg_gradient"
            android:orientation="vertical" android:padding="20dp" android:gravity="center">
            <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:text="STARTS IN" android:textColor="@color/white" android:letterSpacing="0.2" />
            <TextView android:id="@+id/tvCountdown" android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:textColor="@color/white" android:textSize="30sp" android:textStyle="bold"
                android:fontFamily="monospace" />
        </LinearLayout>

        <TextView android:id="@+id/tvWhen" android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_marginTop="16dp" android:textSize="16sp" />
        <TextView android:id="@+id/tvVenue" android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_marginTop="4dp" android:textSize="16sp" />
        <TextView android:id="@+id/tvDescription" android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_marginTop="12dp" />

        <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_marginTop="16dp" android:orientation="horizontal">
            <Button android:id="@+id/btnMap" android:layout_width="0dp" android:layout_weight="1"
                android:layout_height="wrap_content" android:text="Map" />
            <Button android:id="@+id/btnCall" android:layout_width="0dp" android:layout_weight="1"
                android:layout_height="wrap_content" android:layout_marginHorizontal="8dp" android:text="Call" />
            <Button android:id="@+id/btnWebsite" android:layout_width="0dp" android:layout_weight="1"
                android:layout_height="wrap_content" android:text="Website" />
        </LinearLayout>
        <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
            android:orientation="horizontal">
            <Button android:id="@+id/btnSms" style="@style/Widget.Material3.Button.OutlinedButton"
                android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content"
                android:text="Share by SMS" />
            <Button android:id="@+id/btnEmail" style="@style/Widget.Material3.Button.OutlinedButton"
                android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content"
                android:layout_marginStart="8dp" android:text="Email organiser" />
        </LinearLayout>
        <Button android:id="@+id/btnDelete" style="@style/Widget.Material3.Button.TextButton"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_marginTop="8dp" android:text="Delete my event" android:visibility="gone" />
    </LinearLayout>
    </ScrollView>
</LinearLayout>

EventDetailActivity.java

package pk.edu.uni.campuspulse;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.gson.Gson;

import pk.edu.uni.campuspulse.data.Event;
import pk.edu.uni.campuspulse.data.Repository;
import pk.edu.uni.campuspulse.databinding.ActivityEventDetailBinding;

public class EventDetailActivity extends AppCompatActivity {
    private ActivityEventDetailBinding b;
    private Event event;
    private CountDownTimer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        b = ActivityEventDetailBinding.inflate(getLayoutInflater());
        setContentView(b.getRoot());
        Util.applyInsets(b.getRoot(), true);
        setSupportActionBar(b.toolbar);
        if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        b.toolbar.setNavigationOnClickListener(v -> finish());

        // Lab 4 – read the extra sent by HomeFragment
        event = new Gson().fromJson(getIntent().getStringExtra("event"), Event.class);

        b.tvTitle.setText(event.title);
        b.chipCategory.setText(event.category);
        b.tvWhen.setText("🗓  " + Util.niceTime(event.startsAt));
        b.tvVenue.setText("📍  " + (event.venue != null ? event.venue : "Venue to be announced"));
        b.tvDescription.setText(event.description != null ? event.description : "");

        // Buttons work only when the data exists
        b.btnMap.setEnabled(event.lat != null && event.lng != null);
        b.btnCall.setEnabled(notBlank(event.contactPhone));
        b.btnWebsite.setEnabled(notBlank(event.linkUrl));
        b.btnEmail.setEnabled(notBlank(event.contactEmail));
        boolean mine = event.userId != null && event.userId.equals(Prefs.getUserId());
        b.btnDelete.setVisibility(mine ? View.VISIBLE : View.GONE);

        String place = event.venue != null ? event.venue : event.title;
        b.btnMap.setOnClickListener(v -> Util.openMap(this, event.lat, event.lng, place));    // Lab 14
        b.btnCall.setOnClickListener(v -> Util.dial(this, event.contactPhone));               // Lab 6
        b.btnWebsite.setOnClickListener(v -> Util.browse(this, event.linkUrl));               // Lab 6
        b.btnSms.setOnClickListener(v -> Util.sms(this, shareText()));                        // Lab 11
        b.btnEmail.setOnClickListener(v -> Util.email(this, event.contactEmail,               // Lab 11
                "About: " + event.title, "Hello,\n\nI have a question about " + event.title + ".\n\n"));
        b.btnDelete.setOnClickListener(v -> confirmDelete());
    }

    private static boolean notBlank(String s) {
        return s != null && !s.trim().isEmpty();
    }

    // Lab 13 – the countdown runs only while the screen is visible (saves battery)
    @Override
    protected void onStart() {
        super.onStart();
        long millisLeft = Util.parseTime(event.startsAt).toInstant().toEpochMilli() - System.currentTimeMillis();
        if (millisLeft <= 0) {
            b.tvCountdown.setText(R.string.started);
            return;
        }
        timer = new CountDownTimer(millisLeft, 1_000) {
            @Override
            public void onTick(long left) {
                b.tvCountdown.setText(Util.countdown(left));
            }

            @Override
            public void onFinish() {
                b.tvCountdown.setText(R.string.started);
            }
        }.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (timer != null) timer.cancel();
    }

    private String shareText() {
        return "📣 " + event.title + "\n🗓 " + Util.niceTime(event.startsAt)
                + "\n📍 " + (event.venue != null ? event.venue : "TBA")
                + "\n— shared from " + getString(R.string.app_name);
    }

    private void confirmDelete() {
        new MaterialAlertDialogBuilder(this)
                .setTitle("Delete this event?")
                .setMessage("Everyone will stop seeing it.")
                .setNegativeButton("Cancel", null)
                .setPositiveButton("Delete", (dialog, which) ->
                        Repository.deleteEvent(event.id, new Repository.Result<Void>() {
                            @Override
                            public void ok(Void nothing) {
                                Util.toast(EventDetailActivity.this, "Deleted");
                                finish();
                            }

                            @Override
                            public void fail(String message) {
                                Util.toast(EventDetailActivity.this, message);
                            }
                        }))
                .show();
    }
}

Manifest – Android Studio already added EventDetailActivity; add parentActivityName so Up goes to the main screen:

<activity android:name=".EventDetailActivity" android:exported="false"
    android:parentActivityName=".MainActivity" />

Check before moving on

Adapt it to your project

Short and long questions

1. Project viva: How does the detail screen show a live countdown?

Model answer

It parses starts_at with Time.parse, computes milliseconds left, and in onStart creates a CountDownTimer(millisLeft, 1000) whose onTick formats the remaining time with Time.countdown; onFinish shows "Happening now". The timer is cancelled in onStop to save battery.

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

Previous: Project Step 3 – Sign-in and Registration Screens with an Offline Data Layer (Labs 4, 7, 10) · Next: Project Step 5 – Post an Event: Date/Time Pickers, Current Location and Notification (Labs 6, 7, 15)

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