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

Supabase Week Lab – Create a Supabase Backend and Read/Write It from Android with Retrofit

Supabase Week – Cloud Data Tier for Android (extra week after Week 13) · 150 min read · 12 MCQs to check yourself

Supabase 101: REST APIs made simple

Supabase – Getting started with Android and Supabase (uses the official Kotlin client; our lab uses Retrofit)

Lab objective

Create a Supabase project with a notices table, protect it with Row Level Security, test its REST API, then build a small Android app SupaNotes that lists and adds notices using Retrofit – the same skills your course project needs.

You need: a free Supabase account (sign in with GitHub or email at supabase.com), Android Studio, an emulator or phone with internet.

Step 1 – Create the project

  1. Supabase dashboard → New project → name mad-lab, set a strong database password (save it), choose the region nearest to Pakistan (e.g. Mumbai or Singapore) → Create.
  2. Wait 1–2 minutes until the project is ready.
  3. Open Project Settings → API Keys and copy the publishable key (sb_publishable_…). Open Project Settings → Data API (or the Connect button) and copy the Project URL (https://xxxx.supabase.co).

Step 2 – Create the table and its rules (SQL Editor)

Open SQL Editor → New query, paste and press Run:

create table public.notices (
  id         bigint generated always as identity primary key,
  created_at timestamptz not null default now(),
  author     text not null default 'Anonymous' check (char_length(author) <= 40),
  body       text not null check (char_length(body) between 3 and 200)
);

alter table public.notices enable row level security;

-- Anyone using the app (even without signing in) may read notices
create policy "anyone can read notices" on public.notices
  for select to anon, authenticated using (true);

-- Anyone may add a notice (the CHECK constraints above limit its size)
create policy "anyone can add notices" on public.notices
  for insert to anon, authenticated with check (true);

insert into public.notices (author, body) values
  ('Admin', 'Welcome to SupaNotes!'),
  ('CR BSCS-5', 'Mobile App Development quiz on Monday.');

Open Table Editor → notices – you should see the two rows.

In this lab anyone may add notices, to keep it simple. In the course project only signed-in users can write, and only their own rows.

Step 3 – Test the API before writing Android code

Browser test won't work (the key must go in a header), so use curl (Windows PowerShell: use curl.exe) or Postman:

curl "https://YOUR-PROJECT.supabase.co/rest/v1/notices?select=*&order=id.desc" \
  -H "apikey: sb_publishable_YOUR_KEY"

Expected: a JSON array of notices. Now add one:

curl -X POST "https://YOUR-PROJECT.supabase.co/rest/v1/notices" \
  -H "apikey: sb_publishable_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -H "Prefer: return=representation" \
  -d '{"author":"Ali","body":"Testing from curl"}'

Postman: method GET/POST, the same URL, add the headers in the Headers tab, and for POST choose Body → raw → JSON.

Response Meaning
200 / 201 with JSON Success
401 / 42501 "permission denied" / "row-level security" No policy allows this action
400 "violates check constraint" Your data broke a CHECK rule (e.g. body too short)
404 Wrong table name or URL

Step 4 – Android project

  1. New Project → Empty Views Activity → name SupaNotes, package pk.edu.uni.supanotes, language Java, minimum SDK API 26. (The Gradle build file uses Kotlin DSL syntax – that is normal; your app code is Java.)
  2. Put your keys in local.properties (project root – this file is not uploaded to Git):
SUPABASE_URL=https://YOUR-PROJECT.supabase.co
SUPABASE_KEY=sb_publishable_YOUR_KEY
  1. In app/build.gradle.kts add at the very top import java.util.Properties, then:
val localProps = Properties().apply {
    val f = rootProject.file("local.properties")
    if (f.exists()) f.inputStream().use { load(it) }
}

android {
    // … keep what Android Studio created …
    defaultConfig {
        // … keep existing lines, then add:
        buildConfigField("String", "SUPABASE_URL", "\"${localProps.getProperty("SUPABASE_URL", "")}\"")
        buildConfigField("String", "SUPABASE_KEY", "\"${localProps.getProperty("SUPABASE_KEY", "")}\"")
    }
    buildFeatures {
        viewBinding = true
        buildConfig = true
    }
}

dependencies {
    // … keep existing lines, then add:
    implementation("com.squareup.retrofit2:retrofit:2.11.0")
    implementation("com.squareup.retrofit2:converter-gson:2.11.0")
    implementation("androidx.recyclerview:recyclerview:1.3.2")
}

Press Sync Now. (If Android Studio suggests newer versions, accepting them is fine.) 4. AndroidManifest.xml – above <application>:

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

Step 5 – Model and API interface

Notice.java

package pk.edu.uni.supanotes;

import com.google.gson.annotations.SerializedName;

public class Notice {
    public Long id;                                          // Long (not long) so it can be null
    @SerializedName("created_at") public String createdAt;
    public String author;
    public String body;

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

    public Notice(String author, String body) {
        this.author = author;
        this.body = body;
    }
}

SupabaseApi.java

package pk.edu.uni.supanotes;

import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public interface SupabaseApi {
    @GET("rest/v1/notices?select=*&order=id.desc")
    Call<List<Notice>> notices();

    @Headers("Prefer: return=representation")
    @POST("rest/v1/notices")
    Call<List<Notice>> add(@Body Notice notice);

    /** One shared Retrofit object for the whole app. */
    static SupabaseApi create() {
        // Adds the publishable key to EVERY request
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(chain -> chain.proceed(chain.request().newBuilder()
                        .header("apikey", BuildConfig.SUPABASE_KEY)
                        .build()))
                .build();
        return new Retrofit.Builder()
                .baseUrl(BuildConfig.SUPABASE_URL.replaceAll("/+
quot;, "") + "/") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build() .create(SupabaseApi.class); } }

Gson leaves out null fields, so id and created_at are not sent – the database fills them in. That is why id is a Long object, not a long (a long can never be null).

Step 6 – Layout (activity_main.xml)

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

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

    <EditText android:id="@+id/etAuthor" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Your name" />
    <EditText android:id="@+id/etBody" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Write a notice (3–200 characters)"
        android:inputType="textMultiLine|textCapSentences" />

    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button android:id="@+id/btnAdd" android:layout_width="0dp" android:layout_weight="1"
            android:layout_height="wrap_content" android:text="Post" />
        <Button android:id="@+id/btnRefresh" android:layout_width="0dp" android:layout_weight="1"
            android:layout_height="wrap_content" android:layout_marginStart="8dp" android:text="Refresh" />
    </LinearLayout>

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

    <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler"
        android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" />
</LinearLayout>

item_notice.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:paddingVertical="10dp">
    <TextView android:id="@+id/tvBody" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:textSize="16sp" />
    <TextView android:id="@+id/tvAuthor" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:textSize="12sp" android:alpha="0.7" />
</LinearLayout>

Step 7 – Adapter and activity

NoticeAdapter.java

package pk.edu.uni.supanotes;

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

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

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

import pk.edu.uni.supanotes.databinding.ItemNoticeBinding;

public class NoticeAdapter extends RecyclerView.Adapter<NoticeAdapter.Holder> {
    private final List<Notice> items = new ArrayList<>();

    @SuppressLint("NotifyDataSetChanged")
    public void submit(List<Notice> list) {
        items.clear();
        items.addAll(list);
        notifyDataSetChanged();
    }

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

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

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position) {
        Notice n = items.get(position);
        String date = n.createdAt != null ? n.createdAt.substring(0, 10) : "";
        holder.b.tvBody.setText(n.body);
        holder.b.tvAuthor.setText("— " + n.author + " · " + date);
    }

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

MainActivity.java

package pk.edu.uni.supanotes;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import java.util.List;

import pk.edu.uni.supanotes.databinding.ActivityMainBinding;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding b;
    private final NoticeAdapter adapter = new NoticeAdapter();
    private final SupabaseApi api = SupabaseApi.create();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        b = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(b.getRoot());
        b.recycler.setLayoutManager(new LinearLayoutManager(this));
        b.recycler.setAdapter(adapter);

        b.btnRefresh.setOnClickListener(v -> load());
        b.btnAdd.setOnClickListener(v -> post());
        load();
    }

    private void load() {
        b.progress.setVisibility(View.VISIBLE);
        // enqueue = run in the background; the callback comes back on the main thread
        api.notices().enqueue(new Callback<List<Notice>>() {
            @Override
            public void onResponse(@NonNull Call<List<Notice>> call, @NonNull Response<List<Notice>> response) {
                b.progress.setVisibility(View.GONE);
                if (response.isSuccessful() && response.body() != null) adapter.submit(response.body());
                else toast("Could not load: HTTP " + response.code());
            }

            @Override
            public void onFailure(@NonNull Call<List<Notice>> call, @NonNull Throwable t) {
                b.progress.setVisibility(View.GONE);
                toast("Could not load: " + t.getMessage());
            }
        });
    }

    private void post() {
        String body = b.etBody.getText().toString().trim();
        if (body.length() < 3) {
            b.etBody.setError("At least 3 characters");
            return;
        }
        String author = b.etAuthor.getText().toString().trim();
        if (author.isEmpty()) author = "Anonymous";

        b.btnAdd.setEnabled(false);
        api.add(new Notice(author, body)).enqueue(new Callback<List<Notice>>() {
            @Override
            public void onResponse(@NonNull Call<List<Notice>> call, @NonNull Response<List<Notice>> response) {
                b.btnAdd.setEnabled(true);
                if (response.isSuccessful()) {
                    b.etBody.getText().clear();
                    toast("Posted!");
                    load();
                } else {
                    toast("Could not post: HTTP " + response.code());
                }
            }

            @Override
            public void onFailure(@NonNull Call<List<Notice>> call, @NonNull Throwable t) {
                b.btnAdd.setEnabled(true);
                toast("Could not post: " + t.getMessage());
            }
        });
    }

    private void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}

Run the app: the notices from Step 2 appear; post one and watch it appear in the Table Editor too.

Step 8 – See Row Level Security working

  1. In the SQL Editor run: drop policy "anyone can add notices" on public.notices;
  2. Press Post in the app → it shows Could not post: HTTP 401 (or 403) – RLS blocks the insert. Reading still works.
  3. Put the policy back (run the create policy "anyone can add notices" … statement again).

Test cases

# Action Expected
1 Open the app The notices are listed, newest first
2 Post "Hi" (2 characters) App shows "At least 3 characters"
3 Post a valid notice "Posted!", list refreshes, row visible in Table Editor
4 Turn on airplane mode, press Refresh "Could not load: …" message, no crash
5 Drop the insert policy, post Error 401/403 – RLS working

Common errors

Error Fix
Unresolved reference: BuildConfig Add buildConfig = true, sync, then Build → Rebuild Project
Expected URL scheme 'http' or 'https' / base URL error SUPABASE_URL missing in local.properties; sync again
401 Unauthorized / "Invalid API key" Wrong or missing publishable key in local.properties
java.net.UnknownHostException No internet on the emulator, or the INTERNET permission is missing
42501 new row violates row-level security policy No insert policy for this role
Project was paused Dashboard → project → Resume project

Deliverables

Short and long questions

1. Lab viva: Your insert works in the Table Editor but fails from the app with 42501. Why?

Model answer

The Table Editor runs with full privileges, but the app runs as anon/authenticated and Row Level Security has no insert policy allowing it. Add a suitable "for insert" policy.

2. Lab viva: Write the curl command to read all notices newest first.

Model answer

curl "https://<project>.supabase.co/rest/v1/notices?select=*&order=id.desc" -H "apikey: <publishable key>"

3. Lab viva: Where are the Supabase URL and key stored in SupaNotes and why?

Model answer

In local.properties, read in build.gradle.kts into BuildConfig fields. local.properties is excluded from Git, so keys are not published with the source code.

4. Lab viva: Why do we call the Supabase API with enqueue() and not execute()?

Model answer

Network calls must not run on the main thread – Android throws NetworkOnMainThreadException and the UI would freeze. enqueue() runs the request on a background thread and calls onResponse or onFailure on the main thread, so the callback can safely update views. execute() is synchronous and is only used on a background thread (for example inside the OkHttp Authenticator).

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

Previous: Supabase Week Theory – Cloud Data Tier for Android: Supabase, SQL, Row Level Security, Auth and REST · Next: Week 14 Theory – Threading; Publishing Android Applications

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