Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester
Project Step 2 – Main Screen: Toolbar Menu, Bottom Navigation and Fragments (Labs 5, 8)
Course Project (Java) – Build a Modern Cloud App Step by Step (CampusPulse + 7 ideas) · 90 min read · 6 MCQs to check yourself
Goal
Build the main screen: a Material toolbar with an options menu (Lab 8), a bottom navigation bar that swaps four fragments (Lab 5), and small Notifier and Util classes used by later steps.
2.1 Util.java – small tools used everywhere
New Java class Util in the main package:
package pk.edu.uni.campuspulse;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.Priority;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
/** Small tools used by every screen. */
public final class Util {
private Util() { }
public static void toast(@Nullable Context c, String msg) {
if (c != null) Toast.makeText(c, msg, Toast.LENGTH_SHORT).show();
}
/** Edge-to-edge: keep content away from the status bar (and the navigation bar if bottom = true). */
public static void applyInsets(View root, boolean bottom) {
ViewCompat.setOnApplyWindowInsetsListener(root, (v, insets) -> {
Insets bars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(bars.left, bars.top, bars.right, bottom ? bars.bottom : 0);
return insets;
});
}
// ---------- Built-in apps through intents (Labs 6, 11, 14) ----------
private static void launch(Context c, Intent intent) {
try {
c.startActivity(intent);
} catch (ActivityNotFoundException e) {
toast(c, "No app found for this");
}
}
public static void dial(Context c, String phone) {
launch(c, new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone)));
}
public static void browse(Context c, String url) {
if (!url.startsWith("http")) url = "https://" + url;
launch(c, new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
public static void sms(Context c, String text) { sms(c, text, ""); }
public static void sms(Context c, String text, String phone) {
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phone));
i.putExtra("sms_body", text);
launch(c, i);
}
public static void email(Context c, String to, String subject, String body) {
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
i.putExtra(Intent.EXTRA_EMAIL, new String[]{to});
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT, body);
launch(c, i);
}
public static void openMap(Context c, double lat, double lng, String label) {
String uri = "geo:" + lat + "," + lng + "?q=" + lat + "," + lng + "(" + Uri.encode(label) + ")";
launch(c, new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
}
// ---------- Current location (Lab 15). Call only after the permission is granted ----------
public interface LocationResult { void onLocation(@Nullable Location location); }
@SuppressLint("MissingPermission")
public static void currentLocation(Context c, LocationResult callback) {
LocationServices.getFusedLocationProviderClient(c)
.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null)
.addOnSuccessListener(callback::onLocation)
.addOnFailureListener(e -> callback.onLocation(null));
}
// ---------- Dates and times (stored in the cloud as ISO-8601 text) ----------
public static ZonedDateTime parseTime(String iso) {
return OffsetDateTime.parse(iso).atZoneSameInstant(ZoneId.systemDefault());
}
public static String toIso(LocalDate date, LocalTime time) {
return ZonedDateTime.of(date, time, ZoneId.systemDefault()).toOffsetDateTime().toString();
}
public static String niceTime(String iso) {
return parseTime(iso).format(DateTimeFormatter.ofPattern("EEE d MMM yyyy, h:mm a"));
}
public static String countdown(long ms) {
long s = ms / 1000;
long d = s / 86_400, h = s % 86_400 / 3_600, m = s % 3_600 / 60, sec = s % 60;
return d > 0
? String.format(Locale.US, "%dd %02dh %02dm %02ds", d, h, m, sec)
: String.format(Locale.US, "%02d:%02d:%02d", h, m, sec);
}
// ---------- Friendly error messages ----------
public static String friendly(int httpCode) {
switch (httpCode) {
case 400: return "Wrong email or password, or invalid data.";
case 401:
case 403: return "Not allowed – please sign in again.";
case 422: return "Email already registered or password too short (min 6).";
default: return "Server error (" + httpCode + "). Try again.";
}
}
public static String friendly(Throwable t) {
if (t instanceof IOException) return "No internet connection.";
return t.getMessage() != null ? t.getMessage() : "Something went wrong.";
}
}
2.2 Notifier.java – notifications (Lab 6 bonus)
package pk.edu.uni.campuspulse;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
public final class Notifier {
private static final String CHANNEL = "events";
private Notifier() { }
/** Android 8+ needs a channel before showing notifications. */
public static void createChannel(Context context) {
NotificationChannel channel =
new NotificationChannel(CHANNEL, "Events", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("New and upcoming events");
context.getSystemService(NotificationManager.class).createNotificationChannel(channel);
}
@SuppressLint("MissingPermission") // checked below
public static void show(Context context, String title, String text) {
if (Build.VERSION.SDK_INT >= 33 && ContextCompat.checkSelfPermission(context,
Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return;
PendingIntent open = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), PendingIntent.FLAG_IMMUTABLE);
Notification n = new NotificationCompat.Builder(context, CHANNEL)
.setSmallIcon(R.drawable.ic_pulse)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(open)
.setAutoCancel(true)
.build();
NotificationManagerCompat.from(context).notify((int) System.currentTimeMillis(), n);
}
}
Now remove the // in front of Notifier.createChannel(this); in CampusPulseApp.
2.3 Menus
res/menu/bottom_nav.xml (right-click res → New → Android Resource File → type Menu):
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/nav_home" android:icon="@drawable/ic_home" android:title="Home" />
<item android:id="@+id/nav_add" android:icon="@drawable/ic_add" android:title="Add" />
<item android:id="@+id/nav_feedback" android:icon="@drawable/ic_feedback" android:title="Feedback" />
<item android:id="@+id/nav_profile" android:icon="@drawable/ic_person" android:title="Profile" />
</menu>
res/menu/main_menu.xml (Lab 8 – options menu):
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/action_refresh" android:icon="@drawable/ic_refresh"
android:title="Refresh" app:showAsAction="ifRoom" />
<item android:id="@+id/action_dark" android:title="Dark mode" android:checkable="true"
app:showAsAction="never" />
<item android:id="@+id/action_about" android:title="About" app:showAsAction="never" />
<item android:id="@+id/action_logout" android:title="Sign out" app:showAsAction="never" />
</menu>
2.4 Main layout – activity_main.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">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="@string/app_name" />
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottomNav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="@menu/bottom_nav" />
</LinearLayout>
2.5 Four placeholder fragments
Create a package ui (right-click the main package → New → Package). In it create four fragments: New → Fragment → Fragment (Blank) named HomeFragment, AddEventFragment, FeedbackFragment, ProfileFragment (Android Studio also creates their layouts fragment_home.xml, …). For now leave the generated layouts; Steps 4–6 replace them. Make each class as simple as this (same for the other three, with their own layout):
package pk.edu.uni.campuspulse.ui;
import androidx.fragment.app.Fragment;
import pk.edu.uni.campuspulse.R;
public class HomeFragment extends Fragment {
public HomeFragment() {
super(R.layout.fragment_home);
}
}
(Delete the extra generated code such as newInstance, ARG_PARAM1 and onCreateView.)
2.6 MainActivity – toolbar, menu and bottom navigation
package pk.edu.uni.campuspulse;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.splashscreen.SplashScreen;
import androidx.fragment.app.Fragment;
import pk.edu.uni.campuspulse.databinding.ActivityMainBinding;
import pk.edu.uni.campuspulse.ui.AddEventFragment;
import pk.edu.uni.campuspulse.ui.FeedbackFragment;
import pk.edu.uni.campuspulse.ui.HomeFragment;
import pk.edu.uni.campuspulse.ui.ProfileFragment;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private final ActivityResultLauncher<String> notificationPermission =
registerForActivityResult(new ActivityResultContracts.RequestPermission(), granted -> { });
@Override
protected void onCreate(Bundle savedInstanceState) {
SplashScreen.installSplashScreen(this);
super.onCreate(savedInstanceState);
// Step 3 adds the "not signed in → AuthActivity" check here.
EdgeToEdge.enable(this);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
Util.applyInsets(binding.getRoot(), false); // the bottom bar handles the bottom inset itself
// Lab 5 – bottom navigation swaps fragments inside one activity
binding.bottomNav.setOnItemSelectedListener(item -> {
int id = item.getItemId();
Fragment fragment;
if (id == R.id.nav_add) fragment = new AddEventFragment();
else if (id == R.id.nav_feedback) fragment = new FeedbackFragment();
else if (id == R.id.nav_profile) fragment = new ProfileFragment();
else fragment = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
setTitle(id == R.id.nav_home ? getString(R.string.app_name) : item.getTitle());
return true;
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, new HomeFragment()).commit();
}
askNotificationPermission();
}
/** Used by fragments, e.g. "go to Home after publishing". */
public void openTab(int id) {
binding.bottomNav.setSelectedItemId(id);
}
private void askNotificationPermission() {
if (Build.VERSION.SDK_INT >= 33 && ContextCompat.checkSelfPermission(this,
Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS);
}
}
// ---------- Lab 8 – options menu ----------
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
menu.findItem(R.id.action_dark).setChecked(Prefs.isDarkMode());
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
Fragment current = getSupportFragmentManager().findFragmentById(R.id.container);
if (current instanceof HomeFragment) ((HomeFragment) current).load();
else openTab(R.id.nav_home);
Util.toast(this, "Refreshing…");
return true;
} else if (id == R.id.action_dark) {
Prefs.setDarkMode(!Prefs.isDarkMode()); // the screen redraws in the new mode
return true;
} else if (id == R.id.action_about) {
startActivity(new Intent(this, AboutActivity.class));
return true;
} else if (id == R.id.action_logout) {
signOut();
return true;
}
return super.onOptionsItemSelected(item);
}
public void signOut() {
Util.toast(this, "Signed out");
// Step 3 replaces this with: Repository.signOut(); open AuthActivity; finish();
}
}
Until Step 4 and Step 6 exist, load() and AboutActivity will show errors. To run now, temporarily replace the bodies of the action_refresh and action_about branches with Util.toast(this, "…"); return true;. (Lab 8 asked for a message when a menu item is selected – this is it.)
Manifest – add, above <application>:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
Check before moving on
- Bottom navigation switches between four screens; the toolbar title changes.
- Menu shows Refresh (icon), Dark mode, About and Sign out; each shows a message.
- Dark mode switches the whole app and is remembered after restarting (SharedPreferences).
- On Android 13+ the app asks for notification permission once.
Adapt it to your project
Rename the tabs: BloodLink – Requests, Post, Feedback, Me; ThriftHub – Shop, Sell, Feedback, Me; CleanCity – Reports, Report, Feedback, Me. Only the android:title values change.
Short and long questions
1. Project viva: Explain how MainActivity shows a different fragment for each bottom-navigation tab.
Model answer
setOnItemSelectedListener on BottomNavigationView receives the tapped MenuItem; a when on item.itemId creates the matching fragment (Home, Add, Feedback, Profile) and supportFragmentManager.beginTransaction().replace(R.id.container, fragment).commit() puts it in the FrameLayout; the toolbar title is updated.
This lesson ends with a quiz of 6 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: Project Step 1 – Modern Starter: Material 3 Theme, Splash Screen, Resources and Preferences (Labs 1, 3, 10) · Next: Project Step 3 – Sign-in and Registration Screens with an Offline Data Layer (Labs 4, 7, 10)
All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester