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

Project Step 8 – Connect the App to Supabase with Retrofit (Lab 12 + Supabase Week)

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

Supabase tutorial for beginners (2026) – dashboard, tables, auth

Goal

Connect the app to Supabase. You add three small classes in data/ and replace Repository.java. No screen changes – they already call Repository. This is why we separated the presentation tier from the data tier.

Labs used: 12 (Retrofit, RecyclerView), Supabase week, week 14 theory (threading: Retrofit enqueue() runs the call on a background thread and returns the answer on the main thread).

8.1 Internet permission (Manifest, above <application>)

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

8.2 Auth models – data/Auth.java

package pk.edu.uni.campuspulse.data;

import com.google.gson.annotations.SerializedName;

import java.util.Map;

/** The JSON that Supabase Auth sends and receives. */
public final class Auth {
    private Auth() { }

    public static class Credentials {
        public String email;
        public String password;
        public Map<String, String> data;            // saved as user_metadata on sign-up (null on sign-in)

        public Credentials(String email, String password, Map<String, String> data) {
            this.email = email; this.password = password; this.data = data;
        }
    }

    public static class RefreshBody {
        @SerializedName("refresh_token") public String refreshToken;
        public RefreshBody(String refreshToken) { this.refreshToken = refreshToken; }
    }

    public static class User {
        public String id;
        public String email;
        @SerializedName("user_metadata") public Map<String, Object> metadata;
    }

    public static class Session {
        @SerializedName("access_token") public String accessToken;
        @SerializedName("refresh_token") public String refreshToken;
        public User user;
    }
}

8.3 The API – data/SupabaseApi.java

package pk.edu.uni.campuspulse.data;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Query;

public interface SupabaseApi {
    // ----- Auth -----
    @POST("auth/v1/signup")
    Call<Auth.Session> signUp(@Body Auth.Credentials body);

    @POST("auth/v1/token?grant_type=password")
    Call<Auth.Session> signIn(@Body Auth.Credentials body);

    @POST("auth/v1/token?grant_type=refresh_token")
    Call<Auth.Session> refresh(@Body Auth.RefreshBody body);

    // ----- Data (PostgREST) – the user's token is added by Network.java -----
    @GET("rest/v1/events?select=*&order=starts_at.asc")
    Call<List<Event>> events();

    @Headers("Prefer: return=representation")
    @POST("rest/v1/events")
    Call<List<Event>> addEvent(@Body Event event);

    @DELETE("rest/v1/events")
    Call<Void> deleteEvent(@Query("id") String idFilter);      // "eq.<id>"

    @POST("rest/v1/feedback")
    Call<Void> sendFeedback(@Body Feedback feedback);
}

8.4 Retrofit setup – data/Network.java

Two OkHttp helpers do the hard work for every request: an interceptor adds the apikey header (and the user's token on data requests), and an authenticator refreshes an expired token automatically when the server answers 401.

package pk.edu.uni.campuspulse.data;

import androidx.annotation.NonNull;

import java.io.IOException;

import okhttp3.Authenticator;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import pk.edu.uni.campuspulse.BuildConfig;
import pk.edu.uni.campuspulse.Prefs;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public final class Network {
    private static SupabaseApi api;

    private Network() { }

    public static synchronized SupabaseApi api() {
        if (api == null) api = build(true);
        return api;
    }

    private static SupabaseApi build(boolean withUser) {
        OkHttpClient.Builder client = new OkHttpClient.Builder()
                .addInterceptor(chain -> {
                    Request.Builder request = chain.request().newBuilder()
                            .header("apikey", BuildConfig.SUPABASE_KEY);        // every request
                    String token = Prefs.getAccessToken();
                    boolean dataRequest = chain.request().url().encodedPath().startsWith("/rest/");
                    if (withUser && token != null && dataRequest) {
                        request.header("Authorization", "Bearer " + token);    // the signed-in user
                    }
                    return chain.proceed(request.build());
                });
        if (withUser) client.authenticator(new TokenRefresher());
        return new Retrofit.Builder()
                .baseUrl(BuildConfig.SUPABASE_URL.replaceAll("/+
quot;, "") + "/") .client(client.build()) .addConverterFactory(GsonConverterFactory.create()) .build() .create(SupabaseApi.class); } /** OkHttp calls this automatically when the server answers 401 (the access token has expired). */ private static class TokenRefresher implements Authenticator { @Override public Request authenticate(Route route, @NonNull Response response) throws IOException { String refresh = Prefs.getRefreshToken(); if (refresh == null || response.priorResponse() != null) return null; // give up – no endless loop retrofit2.Response<Auth.Session> r = build(false).refresh(new Auth.RefreshBody(refresh)).execute(); if (!r.isSuccessful() || r.body() == null || r.body().accessToken == null) return null; Repository.saveSession(r.body()); return response.request().newBuilder() .header("Authorization", "Bearer " + r.body().accessToken) .build(); // OkHttp retries with this } } }

8.5 Replace data/Repository.java (the cloud version)

Delete the old content and paste:

package pk.edu.uni.campuspulse.data;

import androidx.annotation.NonNull;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pk.edu.uni.campuspulse.Prefs;
import pk.edu.uni.campuspulse.Util;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/** CLOUD version – every screen uses these same methods as in Steps 3–7. */
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 Repository() { }

    /** Runs a Retrofit call on a background thread; Retrofit delivers the answer on the main thread. */
    private static <T> void run(Call<T> call, Result<T> result) {
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(@NonNull Call<T> c, @NonNull Response<T> response) {
                if (response.isSuccessful()) result.ok(response.body());
                else result.fail(Util.friendly(response.code()));
            }

            @Override
            public void onFailure(@NonNull Call<T> c, @NonNull Throwable t) {
                result.fail(Util.friendly(t));
            }
        });
    }

    /** Saves the tokens and profile. Returns true when the user is signed in. */
    static boolean saveSession(Auth.Session s) {
        if (s == null || s.accessToken == null) return false;
        Prefs.setAccessToken(s.accessToken);
        Prefs.setRefreshToken(s.refreshToken);
        if (s.user != null) {
            Prefs.setUserId(s.user.id);
            Prefs.setEmail(s.user.email);
            Object name = s.user.metadata != null ? s.user.metadata.get("full_name") : null;
            if (name instanceof String) Prefs.setFullName((String) name);
        }
        return true;
    }

    /** Turns a Session answer into "signed in? true/false". */
    private static Result<Auth.Session> toSignedIn(Result<Boolean> result) {
        return new Result<Auth.Session>() {
            @Override public void ok(Auth.Session s) { result.ok(saveSession(s)); }
            @Override public void fail(String message) { result.fail(message); }
        };
    }

    public static void signIn(String email, String password, Result<Boolean> result) {
        run(Network.api().signIn(new Auth.Credentials(email, password, null)), toSignedIn(result));
    }

    /** ok(true) = signed in straight away; ok(false) = the user must confirm their email first. */
    public static void signUp(String email, String password, String name, String role, String department,
                              Result<Boolean> result) {
        Map<String, String> profile = new HashMap<>();
        profile.put("full_name", name);
        profile.put("role", role);
        profile.put("department", department);
        Prefs.setFullName(name);
        run(Network.api().signUp(new Auth.Credentials(email, password, profile)), toSignedIn(result));
    }

    public static void events(Result<List<Event>> result) {
        run(Network.api().events(), result);
    }

    public static void addEvent(Event event, Result<Event> result) {
        run(Network.api().addEvent(event), new Result<List<Event>>() {
            @Override public void ok(List<Event> saved) {
                result.ok(saved != null && !saved.isEmpty() ? saved.get(0) : event);
            }
            @Override public void fail(String message) { result.fail(message); }
        });
    }

    public static void deleteEvent(String id, Result<Void> result) {
        run(Network.api().deleteEvent("eq." + id), result);
    }

    public static void sendFeedback(Feedback feedback, Result<Void> result) {
        run(Network.api().sendFeedback(feedback), result);
    }

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

You can now delete SampleData.java (or keep it for demos without internet).

8.6 How a request travels

HomeFragment.load()
   └─ Repository.events(callback)                 (enqueue – UI not blocked)
        └─ Retrofit: GET /rest/v1/events?select=*&order=starts_at.asc
             headers: apikey: sb_publishable_…   (interceptor)
                      Authorization: Bearer <user JWT>
        Supabase → checks JWT → PostgREST → PostgreSQL applies RLS → JSON
   ◄─ callback.ok(List<Event>) on the main thread → adapter.setItems() → RecyclerView

8.7 Try it

  1. Uninstall the app from the emulator once (to clear the offline "session"), then run.
  2. Create an account → you land on Home (or confirm your email first if Confirm email is ON).
  3. Supabase → Authentication → Users: your user is there, with full_name, role, department in its metadata.
  4. Post an event → it appears in Home and in the Table Editor → events with your user_id.
  5. Sign in on a second emulator/phone with another account → you see the event but no Delete button; your own events show Delete.
  6. Send feedback → a row appears in feedback.

Common errors

Symptom Fix
"Not allowed – please sign in again" on every request Old offline token: uninstall the app or sign out and in
Empty list but rows exist The select policy is missing, or you are not signed in (anon cannot read)
400 on sign-in Wrong email/password, or email not confirmed yet
422 on sign-up Email already registered or password shorter than 6
42501 … row-level security on insert Insert policy missing, or the table's user_id default is not auth.uid()
Expected URL scheme 'http' or 'https' SUPABASE_URL missing in local.properties; sync Gradle
Dates show the wrong time Always send Time.toIso(...) (with offset); display with Time.nice(...)

Check before moving on

Short and long questions

1. Project viva: What happens when the access token expires while the app is open?

Model answer

The next API call gets HTTP 401. OkHttp automatically calls the TokenRefresher Authenticator in Network.java, which calls /auth/v1/token?grant_type=refresh_token with the saved refresh token, saves the new tokens in SharedPreferences and returns the request with the new Bearer token, so OkHttp retries it once. If refreshing fails it returns null, the error is shown and the user signs in again.

2. Project viva: Why does the app never send userid when posting an event?

Model answer

The column has default auth.uid(), so the database fills it from the signed-in user's JWT, and the insert policy checks auth.uid() = user_id. A user therefore cannot create events in someone else's name even by editing the request.

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

Previous: Project Step 7 – Supabase Backend for Your App: Tables, Row Level Security and Email Sign-in · Next: Project Step 9 – Polish and Test: Errors, Rotation, Dark Mode, Accessibility, Battery and Test Cases

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