Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester
Project Step 5 – Post an Event: Date/Time Pickers, Current Location and Notification (Labs 6, 7, 15)
Course Project (Java) – Build a Modern Cloud App Step by Step (CampusPulse + 7 ideas) · 120 min read · 5 MCQs to check yourself
Date and time pickers in Android (video code is Kotlin – same MaterialDatePicker in Java)
Goal
Let users post a new event: a Material form (Lab 7) with a date picker and time picker, a "Use my location" button that reads the phone's GPS (Lab 15), and a notification "Event published" (Lab 6) after saving.
5.1 Permissions (Manifest, above <application>)
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
5.2 Layout – fragment_add_event.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="16dp">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Post an event" android:textAppearance="?attr/textAppearanceHeadlineSmall" />
<com.google.android.material.textfield.TextInputLayout android:id="@+id/tilTitle"
android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="12dp"
android:hint="Title" app:counterEnabled="true" app:counterMaxLength="120"
style="@style/Widget.Material3.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText android:id="@+id/etTitle"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:inputType="textCapSentences" android:maxLength="120" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="8dp" android:hint="Description"
style="@style/Widget.Material3.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText android:id="@+id/etDescription"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:inputType="textMultiLine|textCapSentences" android:minLines="3" android:gravity="top" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="8dp" android:hint="Category"
style="@style/Widget.Material3.TextInputLayout.OutlinedBox.ExposedDropdownMenu">
<com.google.android.material.textfield.MaterialAutoCompleteTextView android:id="@+id/etCategory"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:inputType="none" app:simpleItems="@array/categories" />
</com.google.android.material.textfield.TextInputLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginTop="8dp" android:orientation="horizontal">
<Button android:id="@+id/btnDate" style="@style/Widget.Material3.Button.TonalButton"
android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content"
android:text="Pick date" />
<Button android:id="@+id/btnTime" style="@style/Widget.Material3.Button.TonalButton"
android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content"
android:layout_marginStart="8dp" android:text="Pick time" />
</LinearLayout>
<com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="8dp" android:hint="Venue"
style="@style/Widget.Material3.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText android:id="@+id/etVenue"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:inputType="textCapWords" />
</com.google.android.material.textfield.TextInputLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginTop="4dp" android:gravity="center_vertical" android:orientation="horizontal">
<TextView android:id="@+id/tvLocation" android:layout_width="0dp" android:layout_weight="1"
android:layout_height="wrap_content" android:text="📍 No location added" />
<Button android:id="@+id/btnLocation" style="@style/Widget.Material3.Button.TextButton"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Use my location" />
</LinearLayout>
<com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="8dp" android:hint="Contact phone (optional)"
style="@style/Widget.Material3.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText android:id="@+id/etPhone"
android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="phone" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="8dp" android:hint="Contact email (optional)"
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:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="8dp" android:hint="Website / registration link (optional)"
style="@style/Widget.Material3.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText android:id="@+id/etLink"
android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textUri" />
</com.google.android.material.textfield.TextInputLayout>
<Button android:id="@+id/btnPublish" android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginTop="16dp" android:text="Publish event" />
</LinearLayout>
</ScrollView>
5.3 ui/AddEventFragment.java
package pk.edu.uni.campuspulse.ui;
import android.Manifest;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.datepicker.CalendarConstraints;
import com.google.android.material.datepicker.DateValidatorPointForward;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.timepicker.MaterialTimePicker;
import com.google.android.material.timepicker.TimeFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import pk.edu.uni.campuspulse.MainActivity;
import pk.edu.uni.campuspulse.Notifier;
import pk.edu.uni.campuspulse.R;
import pk.edu.uni.campuspulse.Util;
import pk.edu.uni.campuspulse.data.Event;
import pk.edu.uni.campuspulse.data.Repository;
import pk.edu.uni.campuspulse.databinding.FragmentAddEventBinding;
public class AddEventFragment extends Fragment {
private FragmentAddEventBinding b;
private LocalDate date;
private LocalTime time;
private Double lat, lng;
// Lab 15 – ask for location permission, then read the location
private final ActivityResultLauncher<String[]> locationPermission = registerForActivityResult(
new ActivityResultContracts.RequestMultiplePermissions(), result -> {
if (result.containsValue(true)) readLocation();
else Util.toast(getContext(), "Location permission denied");
});
public AddEventFragment() {
super(R.layout.fragment_add_event);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
b = FragmentAddEventBinding.bind(view);
b.etCategory.setText(getResources().getStringArray(R.array.categories)[0], false);
// Rotation: restore what the user picked (week 7 – orientation changes)
if (savedInstanceState != null) {
String d = savedInstanceState.getString("date");
String t = savedInstanceState.getString("time");
if (d != null) date = LocalDate.parse(d);
if (t != null) time = LocalTime.parse(t);
if (savedInstanceState.containsKey("lat")) {
lat = savedInstanceState.getDouble("lat");
lng = savedInstanceState.getDouble("lng");
}
}
updateLabels();
b.btnDate.setOnClickListener(v -> pickDate());
b.btnTime.setOnClickListener(v -> pickTime());
b.btnLocation.setOnClickListener(v -> locationPermission.launch(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}));
b.btnPublish.setOnClickListener(v -> publish());
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (date != null) outState.putString("date", date.toString());
if (time != null) outState.putString("time", time.toString());
if (lat != null && lng != null) {
outState.putDouble("lat", lat);
outState.putDouble("lng", lng);
}
}
private void pickDate() {
MaterialDatePicker<Long> picker = MaterialDatePicker.Builder.datePicker()
.setTitleText("Event date")
.setCalendarConstraints(new CalendarConstraints.Builder()
.setValidator(DateValidatorPointForward.now()).build())
.build();
picker.addOnPositiveButtonClickListener(millis -> {
date = Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate();
updateLabels();
});
picker.show(getChildFragmentManager(), "date");
}
private void pickTime() {
MaterialTimePicker picker = new MaterialTimePicker.Builder()
.setTimeFormat(TimeFormat.CLOCK_12H)
.setHour(10).setMinute(0)
.setTitleText("Start time")
.build();
picker.addOnPositiveButtonClickListener(v -> {
time = LocalTime.of(picker.getHour(), picker.getMinute());
updateLabels();
});
picker.show(getChildFragmentManager(), "time");
}
private void readLocation() {
b.tvLocation.setText("📍 Finding you…");
Util.currentLocation(requireContext(), location -> {
if (b == null) return; // screen already closed
if (location == null) {
b.tvLocation.setText("📍 Location unavailable – turn on GPS and try again");
} else {
lat = location.getLatitude();
lng = location.getLongitude();
updateLabels();
}
});
}
private void updateLabels() {
if (date != null) b.btnDate.setText(date.format(DateTimeFormatter.ofPattern("EEE d MMM yyyy")));
if (time != null) b.btnTime.setText(time.format(DateTimeFormatter.ofPattern("h:mm a")));
if (lat != null && lng != null) b.tvLocation.setText(String.format(Locale.US, "📍 %.5f, %.5f", lat, lng));
}
/** Text of a field, or null when empty (null fields are not sent to the server). */
private static String text(EditText v) {
String s = String.valueOf(v.getText()).trim();
return s.isEmpty() ? null : s;
}
private void publish() {
String title = String.valueOf(b.etTitle.getText()).trim();
b.tilTitle.setError(title.length() >= 3 ? null : "At least 3 characters");
if (b.tilTitle.getError() != null) return;
if (date == null || time == null) {
Util.toast(getContext(), "Pick the date and time");
return;
}
Event event = new Event();
event.title = title;
event.description = text(b.etDescription);
event.category = String.valueOf(b.etCategory.getText());
event.startsAt = Util.toIso(date, time);
event.venue = text(b.etVenue);
event.lat = lat;
event.lng = lng;
event.contactPhone = text(b.etPhone);
event.contactEmail = text(b.etEmail);
event.linkUrl = text(b.etLink);
b.btnPublish.setEnabled(false);
Repository.addEvent(event, new Repository.Result<Event>() {
@Override
public void ok(Event saved) {
if (!isAdded()) return; // the user left this screen
// Lab 6 – notification
Notifier.show(requireContext(), "Event published 🎉", saved.title + " · " + Util.niceTime(saved.startsAt));
Util.toast(getContext(), "Published!");
((MainActivity) requireActivity()).openTab(R.id.nav_home);
}
@Override
public void fail(String message) {
if (b != null) b.btnPublish.setEnabled(true);
Util.toast(getContext(), message);
}
});
}
@Override
public void onDestroyView() {
super.onDestroyView();
b = null;
}
}
Emulator location: in the emulator's ⋮ → Location panel, search a place (e.g. Faisal Mosque, Islamabad) and press Set location before tapping Use my location.
Check before moving on
- The date picker blocks past dates; the chosen date and time show on the buttons.
- Use my location asks for permission once, then shows coordinates.
- Rotating the phone keeps the title, date, time and location.
- Publish shows a notification and returns to Home where the new event appears; opening it shows your Delete button and the map works.
Adapt it to your project
- CleanCity: rename the screen to Report a problem; make Use my location required (
if (lat == null) { Util.toast(getContext(), "Add the location"); return; }). - BloodLink: the category dropdown becomes the blood group; the date is Needed by.
- CampusRide: venue = pickup point; add a Seats field (store it in the description, or add a column in Step 7).
Short and long questions
1. Project viva: Describe the steps to attach the current location to a new event.
Model answer
Declare ACCESS_FINE/COARSE_LOCATION in the manifest; on button tap launch RequestMultiplePermissions; if granted, call FusedLocationProviderClient.getCurrentLocation(PRIORITY_HIGH_ACCURACY, null); on success save latitude and longitude, show them, and include lat/lng in the Event sent to Supabase.
This lesson ends with a quiz of 5 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: Project Step 4 – Events List and Detail: RecyclerView, Countdown, Map, Call, Web, SMS and Email (Labs 4, 6, 11–14) · Next: Project Step 6 – Profile, Feedback with Undo Countdown, and HTML5 About Page (Labs 2, 3, 6, 11, 13, 15, 17)
All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester