Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester
Week 4 Lab 4 – Create Two Activities and Move Between Them
Week 4 – iOS: Architecture and Framework · 120 min read · 11 MCQs to check yourself
Philipp Lackner – Intents and intent filters (Android Basics)
Activities and the activity lifecycle (watch how the back stack changes)
Objective
Add a second activity to CampusMate, open it with an explicit Intent, pass data (name and roll number) to it, and return a reply back to the first screen. CLOs: CLO-2 (develop multi-screen apps), CLO-1 (activity lifecycle and back stack).
What you will build in CampusMate
| Screen | Class | What it does |
|---|---|---|
| Screen 1 | MainActivity |
Student enters name + roll number → taps Open my profile |
| Screen 2 | SecondActivity |
Shows "Welcome Ali (23-BSCS-015)", lets the student type a status and Send back |
| Screen 1 again | MainActivity |
Shows "Status: Ready for the MAD quiz" |
MainActivity ──Intent + extras (NAME, ROLL)──▶ SecondActivity
▲ │
└──────── result (STATUS) + finish() ─────────────┘
Workflow
| Step | What you do | File |
|---|---|---|
| 1 | Create SecondActivity with the wizard | New → Activity |
| 2 | Design screen 1 (inputs + button) | activity_main.xml |
| 3 | Design screen 2 (welcome + status) | activity_second.xml |
| 4 | Send data with an explicit Intent | MainActivity.java |
| 5 | Read data and send a result back | SecondActivity.java |
| 6 | Watch the back stack in Logcat | Logcat filter LIFE |
| 7 | Run and test | Emulator |
Lab 3's student card is not lost – copy it into a new branch/folder first, or simply keep working in the same project; this lab replaces
activity_main.xmlwith a form.
Step 1 – Create the second activity
Right-click com.example.campusmate → New → Activity → Empty Views Activity → Name: SecondActivity, Language Java → Finish.
Android Studio creates three things:
SecondActivity.javares/layout/activity_second.xml- An entry in AndroidManifest.xml:
<activity android:name=".SecondActivity" android:exported="false" />
If you ever create an activity class by hand, you must add this manifest line yourself – otherwise the app crashes with ActivityNotFoundException.
Step 2 – Screen 1 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:fitsSystemWindows="true"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CampusMate – Sign in"
android:textSize="22sp"
android:textStyle="bold" />
<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Your name"
android:inputType="textPersonName" />
<EditText
android:id="@+id/etRoll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Roll number (e.g. 23-BSCS-015)" />
<Button
android:id="@+id/btnOpen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="Open my profile" />
<TextView
android:id="@+id/tvStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:textSize="18sp" />
</LinearLayout>
Step 3 – Screen 2 layout (activity_second.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:fitsSystemWindows="true"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:id="@+id/tvWelcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:textStyle="bold" />
<EditText
android:id="@+id/etStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Your status, e.g. Ready for the MAD quiz" />
<Button
android:id="@+id/btnSendBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send back" />
<Button
android:id="@+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</LinearLayout>
Step 4 – MainActivity.java: send data, receive the result
package com.example.campusmate;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText etName, etRoll;
private TextView tvStatus;
// Receives the result when SecondActivity finishes
private final ActivityResultLauncher<Intent> profileLauncher =
registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == RESULT_OK && result.getData() != null) {
String status = result.getData().getStringExtra("STATUS");
tvStatus.setText("Status: " + status);
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("LIFE", "Main onCreate");
etName = findViewById(R.id.etName);
etRoll = findViewById(R.id.etRoll);
tvStatus = findViewById(R.id.tvStatus);
Button btnOpen = findViewById(R.id.btnOpen);
btnOpen.setOnClickListener(v -> openProfile());
}
private void openProfile() {
String name = etName.getText().toString().trim();
String roll = etRoll.getText().toString().trim();
if (name.isEmpty()) { // simple validation
etName.setError("Please enter your name");
return;
}
// EXPLICIT intent: we name the exact class to open
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("NAME", name); // key–value data
intent.putExtra("ROLL", roll);
profileLauncher.launch(intent); // use startActivity(intent) if no result is needed
}
@Override protected void onPause() { super.onPause(); Log.d("LIFE", "Main onPause"); }
@Override protected void onStop() { super.onStop(); Log.d("LIFE", "Main onStop"); }
@Override protected void onRestart() { super.onRestart(); Log.d("LIFE", "Main onRestart"); }
}
Step 5 – SecondActivity.java: read data, send the result back
package com.example.campusmate;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Log.d("LIFE", "Second onCreate");
// 1. read the extras that MainActivity put in the Intent
String name = getIntent().getStringExtra("NAME");
String roll = getIntent().getStringExtra("ROLL");
TextView tvWelcome = findViewById(R.id.tvWelcome);
tvWelcome.setText("Welcome " + name + " (" + roll + ")");
EditText etStatus = findViewById(R.id.etStatus);
// 2. send a result back and close this screen
findViewById(R.id.btnSendBack).setOnClickListener(v -> {
Intent reply = new Intent();
reply.putExtra("STATUS", etStatus.getText().toString());
setResult(RESULT_OK, reply);
finish(); // go back to MainActivity
});
// 3. just go back
findViewById(R.id.btnBack).setOnClickListener(v -> finish());
}
@Override protected void onDestroy() { super.onDestroy(); Log.d("LIFE", "Second onDestroy"); }
}
Step 6 – Watch the back stack (Logcat filter LIFE)
| Action | Expected log |
|---|---|
| Open the app | Main onCreate |
| Tap Open my profile | Main onPause → Second onCreate → Main onStop |
| Tap Send back (or Back) | Main onRestart → Second onDestroy |
MainActivity is not destroyed when SecondActivity opens – it waits on the back stack.
Step 7 (bonus) – Up arrow
In the manifest: <activity android:name=".SecondActivity" android:parentActivityName=".MainActivity" android:exported="false" /> and in SecondActivity.onCreate():
if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Run and test
| Test | Expected result |
|---|---|
| Tap Open with empty name | Red error "Please enter your name" |
| Enter "Ali", "23-BSCS-015" → Open | Screen 2: "Welcome Ali (23-BSCS-015)" |
| Type a status → Send back | Screen 1 shows "Status: …" |
| Screen 2 → Back | Screen 1 unchanged |
Common errors and fixes
| Problem | Fix |
|---|---|
| ActivityNotFoundException | SecondActivity missing from AndroidManifest.xml |
| "Welcome null (null)" | Key mismatch – putExtra("NAME") and getStringExtra("NAME") must be identical (case-sensitive) |
| Result never shows | Use profileLauncher.launch(intent) (not startActivity) and call setResult(RESULT_OK, …) before finish() |
Short and long questions
1. (Viva) What steps are required to add a second activity to an app?
Model answer
Create the activity class (extending AppCompatActivity) and its XML layout, set the layout with setContentView, and declare the activity in AndroidManifest.xml (Android Studio's New → Activity wizard does all three).
2. (Viva) What is the difference between an explicit and an implicit intent?
Model answer
An explicit intent names the exact component class to start (used inside your own app); an implicit intent declares only an action and data (e.g. ACTION_VIEW with a URL) and lets the system find a suitable app through intent filters.
3. (Viva) What did Logcat show when you opened the second activity and pressed Back?
Model answer
Opening: Main onPause → Second onCreate/onStart/onResume → Main onStop. Back: Second onPause → Main onRestart/onStart/onResume → Second onStop/onDestroy. MainActivity stayed on the back stack and was not recreated.
4. (Viva) Write Java code to open SecondActivity and pass a name.
Model answer
Intent i = new Intent(this, SecondActivity.class); i.putExtra("NAME", name); startActivity(i); – and in SecondActivity read it with String name = getIntent().getStringExtra("NAME");.
This lesson ends with a quiz of 11 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: Week 4 Theory – iOS – Architecture, Frameworks, App Lifecycle and Development Tools · Next: Assignment 1 (Weeks 1–4) – "My Department" Multi-Screen App and Platform Report
All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester