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

Project Step 3 – Sign-in and Registration Screens with an Offline Data Layer (Labs 4, 7, 10)

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

Authentication with Supabase – how sign-in works (we connect it in Step 8)

Goal

Add the sign-in and registration screens (Labs 4 and 7). The app opens the sign-in screen when nobody is signed in, remembers the email (Lab 10), and passes data between activities with intents and extras. We also create the data layer – for now it works offline; Step 8 connects it to Supabase without changing any screen.

3.1 Data models – data/Event.java and data/Feedback.java

Create a package data and in it the class Event:

package pk.edu.uni.campuspulse.data;

import com.google.gson.annotations.SerializedName;

/** One record of the app. Rename the fields' meaning for your own project (see Step 0).
 *  Fields left null are not sent to the server – the database fills them in. */
public class Event {
    public String id;
    @SerializedName("user_id") public String userId;
    public String title;
    public String description;
    public String category = "General";
    @SerializedName("starts_at") public String startsAt;   // ISO-8601, e.g. 2026-12-12T10:00+05:00
    public String venue;
    public Double lat;                                      // Double (not double) so it can be null
    public Double lng;
    @SerializedName("contact_phone") public String contactPhone;
    @SerializedName("contact_email") public String contactEmail;
    @SerializedName("link_url") public String linkUrl;

    public Event() { }   // Gson needs an empty constructor

    public Event(String id, String userId, String title, String description, String category, String startsAt,
                 String venue, Double lat, Double lng, String contactPhone, String contactEmail, String linkUrl) {
        this.id = id; this.userId = userId; this.title = title; this.description = description;
        this.category = category; this.startsAt = startsAt; this.venue = venue; this.lat = lat; this.lng = lng;
        this.contactPhone = contactPhone; this.contactEmail = contactEmail; this.linkUrl = linkUrl;
    }
}

data/Feedback.java

package pk.edu.uni.campuspulse.data;

public class Feedback {
    public int rating;
    public String category;
    public String message;
    public Double lat;
    public Double lng;

    public Feedback(int rating, String category, String message, Double lat, Double lng) {
        this.rating = rating; this.category = category; this.message = message; this.lat = lat; this.lng = lng;
    }
}

@SerializedName maps the Java field name to the database column name (snake_case). Gson (part of Retrofit) turns these objects into JSON and back.

3.2 Sample data – data/SampleData.java

package pk.edu.uni.campuspulse.data;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

import pk.edu.uni.campuspulse.Util;

/** Used until the cloud is connected in Step 8. Dates are relative to today, so they never go stale. */
public final class SampleData {
    private SampleData() { }

    private static String at(long days, int hour) {
        return Util.toIso(LocalDate.now().plusDays(days), LocalTime.of(hour, 0));
    }

    public static List<Event> events() {
        List<Event> list = new ArrayList<>();
        list.add(new Event("1", "demo", "Tech Talk: AI on Phones", "How on-device AI works – with live demos.", "Tech",
                at(2, 10), "Seminar Hall, Block C", 33.6844, 73.0479, "0511234567", "cs@example.edu.pk", "https://www.example.edu.pk"));
        list.add(new Event("2", "demo", "Inter-Department Cricket Final", "CS vs EE. Bring your department colours!", "Sports",
                at(4, 15), "University Ground", 33.6870, 73.0500, "03001234567", null, null));
        list.add(new Event("3", "demo", "Career Fair 2026", "40+ companies, CV clinic and mock interviews.", "Academic",
                at(7, 9), "Convention Centre", 33.6938, 73.0652, null, "careers@example.edu.pk", "https://www.example.edu.pk/careers"));
        list.add(new Event("4", "demo", "Qawwali Night", "An evening of music on the lawn.", "Cultural",
                at(10, 19), "Central Lawn", 33.6850, 73.0490, null, null, null));
        return list;
    }
}

3.3 Repository – the only door to data (offline version)

data/Repository.java – every screen talks to this class only. Data can take time to arrive, so each method takes a callback (Result<T>): ok(value) on success or fail(message) on error. The screen never waits and never freezes.

package pk.edu.uni.campuspulse.data;

import android.os.Handler;
import android.os.Looper;

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

import pk.edu.uni.campuspulse.Prefs;

/** OFFLINE version (Steps 3–7). Step 8 replaces this file with the Supabase version – screens stay the same. */
public final class Repository {

    /** Every answer comes back through this callback, on the main (UI) thread. */
    public interface Result<T> {
        void ok(T value);
        void fail(String message);
    }

    private static final Handler main = new Handler(Looper.getMainLooper());
    private static final List<Event> local = SampleData.events();

    private Repository() { }

    /** Pretend a server takes half a second, then answer on the main thread. */
    private static <T> void later(T value, Result<T> result) {
        main.postDelayed(() -> result.ok(value), 500);
    }

    public static void signIn(String email, String password, Result<Boolean> result) {
        Prefs.setAccessToken("offline");
        Prefs.setUserId("me");
        Prefs.setEmail(email);
        later(true, result);                          // true = signed in
    }

    public static void signUp(String email, String password, String name, String role, String department,
                              Result<Boolean> result) {
        Prefs.setFullName(name);
        signIn(email, password, result);
    }

    public static void events(Result<List<Event>> result) {
        List<Event> copy = new ArrayList<>(local);
        copy.sort((a, b) -> a.startsAt.compareTo(b.startsAt));
        later(copy, result);
    }

    public static void addEvent(Event event, Result<Event> result) {
        event.id = UUID.randomUUID().toString();
        event.userId = Prefs.getUserId();
        local.add(event);
        later(event, result);
    }

    public static void deleteEvent(String id, Result<Void> result) {
        local.removeIf(e -> id.equals(e.id));
        later(null, result);
    }

    public static void sendFeedback(Feedback feedback, Result<Void> result) {
        later(null, result);
    }

    public static void signOut() {
        Prefs.clearSession();
    }
}

3.4 Sign-in screen – AuthActivity

New → Activity → Empty Views Activity → AuthActivity (uncheck Launcher Activity). Layout activity_auth.xml:

<ScrollView 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:fillViewport="true">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
    android:orientation="vertical" android:padding="24dp" android:gravity="center_vertical">

    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
        android:background="@drawable/bg_gradient" android:orientation="vertical" android:padding="24dp">
        <ImageView android:layout_width="64dp" android:layout_height="64dp"
            android:src="@drawable/ic_pulse" android:contentDescription="@string/app_name" />
        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="@string/app_name" android:textColor="@color/white"
            android:textSize="28sp" android:textStyle="bold" />
        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="@string/tagline" android:textColor="@color/white" android:alpha="0.85" />
    </LinearLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/tilEmail" android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_marginTop="24dp" android:hint="Email"
        style="@style/Widget.Material3.TextInputLayout.OutlinedBox">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/etEmail" android:layout_width="match_parent" android:layout_height="wrap_content"
            android:inputType="textEmailAddress" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/tilPassword" android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_marginTop="12dp" android:hint="Password" app:endIconMode="password_toggle"
        style="@style/Widget.Material3.TextInputLayout.OutlinedBox">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/etPassword" android:layout_width="match_parent" android:layout_height="wrap_content"
            android:inputType="textPassword" />
    </com.google.android.material.textfield.TextInputLayout>

    <Button android:id="@+id/btnSignIn" android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_marginTop="20dp" android:text="Sign in" />
    <com.google.android.material.progressindicator.LinearProgressIndicator
        android:id="@+id/progress" android:layout_width="match_parent" android:layout_height="wrap_content"
        android:indeterminate="true" android:visibility="gone" />
    <Button android:id="@+id/btnRegister" style="@style/Widget.Material3.Button.TextButton"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:text="New here? Create an account" />
</LinearLayout>
</ScrollView>

AuthActivity.java

package pk.edu.uni.campuspulse;

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

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import pk.edu.uni.campuspulse.data.Repository;
import pk.edu.uni.campuspulse.databinding.ActivityAuthBinding;

public class AuthActivity extends AppCompatActivity {
    private ActivityAuthBinding b;

    // Lab 4 – open RegisterActivity and receive a result (the new email) back
    private final ActivityResultLauncher<Intent> register = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), result -> {
                if (result.getResultCode() != RESULT_OK) return;
                if (Prefs.isLoggedIn()) {
                    goHome();
                } else {
                    if (result.getData() != null) b.etEmail.setText(result.getData().getStringExtra("email"));
                    Util.toast(this, "Account created. Confirm your email, then sign in.");
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        b = ActivityAuthBinding.inflate(getLayoutInflater());
        setContentView(b.getRoot());
        Util.applyInsets(b.getRoot(), true);

        b.etEmail.setText(Prefs.getEmail());          // Lab 10 – remembered email
        b.btnSignIn.setOnClickListener(v -> signIn());
        b.btnRegister.setOnClickListener(v -> register.launch(new Intent(this, RegisterActivity.class)));
    }

    private void signIn() {
        String email = String.valueOf(b.etEmail.getText()).trim();
        String password = String.valueOf(b.etPassword.getText());
        b.tilEmail.setError(Patterns.EMAIL_ADDRESS.matcher(email).matches() ? null : "Enter a valid email");
        b.tilPassword.setError(password.length() >= 6 ? null : "At least 6 characters");
        if (b.tilEmail.getError() != null || b.tilPassword.getError() != null) return;

        setBusy(true);
        Repository.signIn(email, password, new Repository.Result<Boolean>() {
            @Override
            public void ok(Boolean signedIn) {
                setBusy(false);
                if (signedIn) goHome();
            }

            @Override
            public void fail(String message) {
                setBusy(false);
                b.tilPassword.setError(message);
            }
        });
    }

    private void setBusy(boolean busy) {
        b.progress.setVisibility(busy ? View.VISIBLE : View.GONE);
        b.btnSignIn.setEnabled(!busy);
    }

    private void goHome() {
        startActivity(new Intent(this, MainActivity.class));
        finish();                                     // Back will not return to sign-in
    }
}

3.5 Registration form – RegisterActivity (Lab 7)

Create RegisterActivity (Empty Views Activity). Layout activity_register.xml:

<ScrollView 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">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
    android:orientation="vertical" android:padding="24dp">

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="Create your account" android:textSize="24sp" android:textStyle="bold" />

    <com.google.android.material.textfield.TextInputLayout android:id="@+id/tilName"
        android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp"
        android:hint="Full name" style="@style/Widget.Material3.TextInputLayout.OutlinedBox">
        <com.google.android.material.textfield.TextInputEditText android:id="@+id/etName"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:inputType="textPersonName|textCapWords" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout android:id="@+id/tilEmail"
        android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp"
        android:hint="Email" style="@style/Widget.Material3.TextInputLayout.OutlinedBox">
        <com.google.android.material.textfield.TextInputEditText android:id="@+id/etEmail"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:inputType="textEmailAddress" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout android:id="@+id/tilPassword"
        android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp"
        android:hint="Password (min 6)" app:endIconMode="password_toggle"
        style="@style/Widget.Material3.TextInputLayout.OutlinedBox">
        <com.google.android.material.textfield.TextInputEditText android:id="@+id/etPassword"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:inputType="textPassword" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout android:id="@+id/tilConfirm"
        android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp"
        android:hint="Confirm password" style="@style/Widget.Material3.TextInputLayout.OutlinedBox">
        <com.google.android.material.textfield.TextInputEditText android:id="@+id/etConfirm"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:inputType="textPassword" />
    </com.google.android.material.textfield.TextInputLayout>

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_marginTop="12dp" android:text="I am a" />
    <RadioGroup android:id="@+id/rgRole" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">
        <RadioButton android:id="@+id/rbStudent" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="Student" android:checked="true" />
        <RadioButton android:id="@+id/rbTeacher" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_marginStart="24dp" android:text="Teacher" />
    </RadioGroup>

    <com.google.android.material.textfield.TextInputLayout android:id="@+id/tilDepartment"
        android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp"
        android:hint="Department" style="@style/Widget.Material3.TextInputLayout.OutlinedBox.ExposedDropdownMenu">
        <com.google.android.material.textfield.MaterialAutoCompleteTextView android:id="@+id/etDepartment"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:inputType="none" app:simpleItems="@array/departments" />
    </com.google.android.material.textfield.TextInputLayout>

    <CheckBox android:id="@+id/cbTerms" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_marginTop="8dp"
        android:text="I agree to use the app respectfully" />

    <Button android:id="@+id/btnCreate" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:layout_marginTop="12dp" android:text="Create account" />
    <com.google.android.material.progressindicator.LinearProgressIndicator
        android:id="@+id/progress" android:layout_width="match_parent" android:layout_height="wrap_content"
        android:indeterminate="true" android:visibility="gone" />
</LinearLayout>
</ScrollView>

RegisterActivity.java

package pk.edu.uni.campuspulse;

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

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

import pk.edu.uni.campuspulse.data.Repository;
import pk.edu.uni.campuspulse.databinding.ActivityRegisterBinding;

public class RegisterActivity extends AppCompatActivity {
    private ActivityRegisterBinding b;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        b = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(b.getRoot());
        Util.applyInsets(b.getRoot(), true);
        b.etDepartment.setText(getResources().getStringArray(R.array.departments)[0], false);
        b.btnCreate.setOnClickListener(v -> create());
    }

    private void create() {
        String name = String.valueOf(b.etName.getText()).trim();
        String email = String.valueOf(b.etEmail.getText()).trim();
        String password = String.valueOf(b.etPassword.getText());
        String confirm = String.valueOf(b.etConfirm.getText());
        String role = b.rbTeacher.isChecked() ? "Teacher" : "Student";
        String department = String.valueOf(b.etDepartment.getText());

        // Validation – show the error under the field (Lab 7)
        b.tilName.setError(name.length() >= 3 ? null : "Enter your full name");
        b.tilEmail.setError(Patterns.EMAIL_ADDRESS.matcher(email).matches() ? null : "Enter a valid email");
        b.tilPassword.setError(password.length() >= 6 ? null : "At least 6 characters");
        b.tilConfirm.setError(confirm.equals(password) ? null : "Passwords do not match");
        if (b.tilName.getError() != null || b.tilEmail.getError() != null
                || b.tilPassword.getError() != null || b.tilConfirm.getError() != null) return;
        if (!b.cbTerms.isChecked()) {
            Util.toast(this, "Please accept the terms");
            return;
        }

        setBusy(true);
        Repository.signUp(email, password, name, role, department, new Repository.Result<Boolean>() {
            @Override
            public void ok(Boolean signedIn) {
                Prefs.setEmail(email);
                // Lab 4 – send the email back to AuthActivity as an extra
                setResult(RESULT_OK, new Intent().putExtra("email", email));
                finish();
            }

            @Override
            public void fail(String message) {
                setBusy(false);
                Util.toast(RegisterActivity.this, message);
            }
        });
    }

    private void setBusy(boolean busy) {
        b.progress.setVisibility(busy ? View.VISIBLE : View.GONE);
        b.btnCreate.setEnabled(!busy);
    }
}

Rotation: typed text survives turning the phone because every EditText has an id – Android saves its state automatically (week 7 theory).

3.6 Send signed-out users to the sign-in screen

In MainActivity.onCreate, replace the comment "Step 3 adds…" with:

if (!Prefs.isLoggedIn()) {                        // Lab 4 – move to another activity
    startActivity(new Intent(this, AuthActivity.class));
    finish();
    return;
}

and replace signOut() with:

public void signOut() {
    Repository.signOut();
    startActivity(new Intent(this, AuthActivity.class));
    finish();
}

(add import pk.edu.uni.campuspulse.data.Repository;).

Check before moving on

Adapt it to your project

Change the registration fields to suit your idea: BloodLink – add a Blood group dropdown; CampusRide – I am a Driver / Passenger; HealthMate – Age and Gender. Pass extra fields to signUp(...) – in Step 8 they are saved in the user's profile on Supabase.

Short and long questions

1. Project viva: What is the Repository pattern and how did it help in Step 8?

Model answer

The Repository is a single class that hides where data comes from; screens call functions like events() and addEvent(). In Steps 3–7 it used local sample data; in Step 8 only Repository.java was replaced with the Supabase version and no screen code changed.

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

Previous: Project Step 2 – Main Screen: Toolbar Menu, Bottom Navigation and Fragments (Labs 5, 8) · Next: Project Step 4 – Events List and Detail: RecyclerView, Countdown, Map, Call, Web, SMS and Email (Labs 4, 6, 11–14)

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