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

Week 7 Lab 7 – Design a Registration Form Using TextView, EditText, Button and RadioButton

Week 7 – Screen Components and Orientation · 150 min read · 12 MCQs to check yourself

Coding in Flow – ConstraintLayout: understanding constraints

Screen rotation and preserving state (for Step 6)

Objective

Design a complete student registration form with TextView, EditText, RadioButton, CheckBox and Button; read and validate every input in Java; show a summary; and keep the summary when the phone is rotated. CLOs: CLO-2 (develop user interfaces), CLO-3 (UI behaviour on different screen orientations).

What you will build in CampusMate

RegisterActivity – a new student registers before signing in:

Field Widget Rule
Full name EditText (textPersonName) at least 3 characters
Email EditText (textEmailAddress) valid email
Phone EditText (phone) 11 digits, starts with 03
Password EditText (textPassword) at least 6 characters
Gender RadioGroup (Male / Female) one selected
Terms CheckBox must be ticked
Register Button validates, then shows a summary

Workflow

Step What you do File
1 Create RegisterActivity New → Activity
2 Design the form inside a ScrollView activity_register.xml
3 Connect views in Java RegisterActivity.java
4 Validate each field validate() method
5 Show the summary register() method
6 Keep the summary on rotation onSaveInstanceState()
7 Run all test cases Emulator

Step 1 – Create the activity

New → Activity → Empty Views Activity → RegisterActivity (Java). Add a "New student? Register" button on the sign-in screen (Lab 4) that opens it with startActivity(new Intent(this, RegisterActivity.class));.

Step 2 – The form layout (activity_register.xml)

<ScrollView 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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="24dp">

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

        <EditText
            android:id="@+id/etName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:hint="Full name"
            android:inputType="textPersonName" />

        <EditText
            android:id="@+id/etEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"
            android:inputType="textEmailAddress" />

        <EditText
            android:id="@+id/etPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Phone (03xxxxxxxxx)"
            android:inputType="phone"
            android:maxLength="11" />

        <EditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password (min 6 characters)"
            android:inputType="textPassword" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:text="Gender" />

        <RadioGroup
            android:id="@+id/rgGender"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/rbMale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Male" />

            <RadioButton
                android:id="@+id/rbFemale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="24dp"
                android:text="Female" />
        </RadioGroup>

        <CheckBox
            android:id="@+id/cbTerms"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="I agree to the campus rules" />

        <Button
            android:id="@+id/btnRegister"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:text="Register" />

        <Button
            android:id="@+id/btnClear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Clear" />

        <TextView
            android:id="@+id/tvSummary"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:textSize="16sp" />
    </LinearLayout>
</ScrollView>

Professional look (optional): wrap each EditText in a Material TextInputLayout for a floating label and inline errors.

Step 3 – Connect the views (RegisterActivity.java)

package com.example.campusmate;

import android.os.Bundle;
import android.util.Patterns;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class RegisterActivity extends AppCompatActivity {

    private EditText etName, etEmail, etPhone, etPassword;
    private RadioGroup rgGender;
    private CheckBox cbTerms;
    private TextView tvSummary;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        etName = findViewById(R.id.etName);
        etEmail = findViewById(R.id.etEmail);
        etPhone = findViewById(R.id.etPhone);
        etPassword = findViewById(R.id.etPassword);
        rgGender = findViewById(R.id.rgGender);
        cbTerms = findViewById(R.id.cbTerms);
        tvSummary = findViewById(R.id.tvSummary);

        findViewById(R.id.btnRegister).setOnClickListener(v -> register());
        findViewById(R.id.btnClear).setOnClickListener(v -> clearForm());

        if (savedInstanceState != null) {                         // Step 6
            tvSummary.setText(savedInstanceState.getString("SUMMARY", ""));
        }
    }

    // Steps 4–6 below
}

Step 4 – Validate every field

private boolean validate() {
    String name = etName.getText().toString().trim();
    String email = etEmail.getText().toString().trim();
    String phone = etPhone.getText().toString().trim();
    String password = etPassword.getText().toString();

    if (name.length() < 3) {
        etName.setError("Enter at least 3 characters");
        return false;
    }
    if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {   // built-in email pattern
        etEmail.setError("Invalid email");
        return false;
    }
    if (!(phone.length() == 11 && phone.startsWith("03"))) {
        etPhone.setError("Phone must be 11 digits starting with 03");
        return false;
    }
    if (password.length() < 6) {
        etPassword.setError("Minimum 6 characters");
        return false;
    }
    if (rgGender.getCheckedRadioButtonId() == -1) {            // -1 = nothing selected
        Toast.makeText(this, "Please select gender", Toast.LENGTH_SHORT).show();
        return false;
    }
    if (!cbTerms.isChecked()) {
        Toast.makeText(this, "Please accept the campus rules", Toast.LENGTH_SHORT).show();
        return false;
    }
    return true;
}

setError() shows a red icon and message on the field – the user sees exactly what to fix.

Step 5 – Register and clear

private void register() {
    if (!validate()) return;                      // stop at the first problem

    RadioButton selected = findViewById(rgGender.getCheckedRadioButtonId());
    String gender = selected.getText().toString();

    String summary = "Registered successfully!\n"
            + "Name: " + etName.getText().toString().trim() + "\n"
            + "Email: " + etEmail.getText().toString().trim() + "\n"
            + "Phone: " + etPhone.getText().toString().trim() + "\n"
            + "Gender: " + gender;
    tvSummary.setText(summary);
    Toast.makeText(this, "Welcome to CampusMate!", Toast.LENGTH_SHORT).show();
}

private void clearForm() {
    etName.setText("");
    etEmail.setText("");
    etPhone.setText("");
    etPassword.setText("");
    rgGender.clearCheck();               // unselect all radio buttons
    cbTerms.setChecked(false);
    tvSummary.setText("");
    etName.requestFocus();
}

Step 6 – Keep the summary when the phone rotates

Rotation destroys and recreates the activity. EditTexts and RadioButtons that have an id restore themselves, but the summary TextView does not. Save it:

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("SUMMARY", tvSummary.getText().toString());
}

It is restored in onCreate (Step 3) from savedInstanceState. Experiment: comment out onSaveInstanceState, register, rotate (Ctrl+← in the emulator) – the summary disappears. Put it back – it stays.

Bonus: for a two-column landscape design create res/layout-land/activity_register.xml with the same ids; Android picks it automatically in landscape.

Step 7 – Test cases

Input Expected result
Name "Al" Error on name
Email "ali@" "Invalid email"
Phone "0300123" Phone error
Password "123" "Minimum 6 characters"
No gender Toast "Please select gender"
Terms unticked Toast "Please accept the campus rules"
All valid Summary + Toast "Welcome to CampusMate!"
Rotate after success Summary still shown
Tap Clear All fields empty, no gender selected

Common errors and fixes

Problem Fix
Crash: "ScrollView can host only one direct child" Put all views inside one LinearLayout inside the ScrollView
Crash in register() on selected.getText() Validate gender first – getCheckedRadioButtonId() is -1 when nothing is selected
Both radio buttons can be selected They are not inside the same RadioGroup

Short and long questions

1. (Viva) Why do we use different inputType values for different fields?

Model answer

inputType shows the most suitable keyboard and behaviour – email keyboard with @, phone dial pad, hidden password characters, capitalised names – making input faster, more accurate and secure.

2. (Viva) List the validations you applied in the form.

Model answer

Name at least 3 characters; email matches Patterns.EMAIL_ADDRESS; phone is 11 digits starting with 03; password at least 6 characters; a gender is selected; the terms checkbox is ticked. Errors are shown with setError or Toasts.

3. (Viva) What did you observe when you rotated the device with and without onSaveInstanceState?

Model answer

Field values and radio selections stayed in both cases because those views have IDs. The result summary stayed only when it was saved in onSaveInstanceState; without it, the recreated activity showed an empty summary.

4. (Viva) How do you get the text of the selected radio button?

Model answer

Read int id = rgGender.getCheckedRadioButtonId();; if it is not -1, call RadioButton rb = findViewById(id); and rb.getText().toString() to get the selected button's label.

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

Previous: Week 7 Theory – Components of a Screen; Adapting to Display Orientation; Managing Changes to Screen Orientation · Next: Week 8 Theory – Utilizing the Action Bar; Creating the User Interface

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