PROGRAMMING FOR MOBILE PLATFORMS

Site: Newgate University Minna - Elearning Platform
Course: Mobile Application Development
Book: PROGRAMMING FOR MOBILE PLATFORMS
Printed by: Guest user
Date: Sunday, 29 March 2026, 10:28 PM

1. Introduction to programming languages

Introduction to programming languages:

Java and Kotlin for Android

Introduction to Java in Mobile Development

Java’s Role:

Android Development: Java was the primary language for Android apps until Kotlin’s rise (2017). It remains widely used in legacy systems and enterprise apps.

Cross-Platform: Tools like Codename One enable Java-based cross-platform apps (iOS/Android).

Why Learn Java for Mobile?

o Legacy Codebases: Many Android apps still use Java.

o Foundational Knowledge: Understanding Java aids in learning Kotlin/Android internals.

Key Concepts and Tools:

  1. Java Fundamentals: A solid understanding of core Java concepts is essential. This includes:

A.  Object-Oriented Programming (OOP): Classes, objects, inheritance, polymorphism, encapsulation, abstraction. Android development heavily relies on OOP principles.

B.  Data Types and Variables: Understanding primitive data types (int, float, boolean, etc.) and how to declare and use variables.

C.  Control Flow: if-else statements, switch statements, for loops, while loops, and how to control the execution flow of your program.

D.  Collections: Working with data structures like Lists, Maps, and Sets to store and manage collections of data.

E.   Exception Handling: Using try-catch blocks to handle errors and prevent your app from crashing.

F.   Threads and Concurrency: Understanding how to create and manage threads to perform tasks asynchronously, especially important for UI responsiveness.

G.  Generics: Using generics to write type-safe and reusable code.

Android SDK: The Android Software Development Kit provides the tools and libraries necessary to build Android apps. Key components include:


2. Key concepts and tools

A.    Android Studio: The official Integrated Development Environment (IDE) for Android development. It provides features like code editing, debugging, profiling, and building your app.

B.    Android Emulator: A virtual device that allows you to test your app without needing a physical Android device.

C.    Android APIs: Libraries of pre-built classes and methods that provide access to device features like the camera, GPS, storage, and UI elements.

  1. Android Architecture: Understanding the basic architecture of Android apps is crucial. Key components include:

A.    Activities: Represent a single screen with a user interface.

B.    Fragments: Reusable components that represent a portion of an Activity's UI.

C.    Services: Background processes that perform long-running operations without a UI.

D.    Broadcast Receivers: Listeners for system-wide broadcasts.

E.    Intents: Messages that are used to communicate between different components of an app.

  1. UI Design: Creating user-friendly and visually appealing interfaces is essential. Key concepts include:

A.    XML Layouts: Defining the structure and appearance of your UI using XML files.

B.    UI Widgets: Using pre-built UI elements like buttons, text fields, lists, and images.

C.    Layout Managers: Arranging UI widgets within your layouts.

D.    Material Design: Following Google's design guidelines for creating consistent and intuitive user experiences.


3. Key concept and tools

  1. Data Storage: Android provides various options for storing data:

A.    Shared Preferences: Storing small amounts of key-value data.

B.    SQLite Databases: Storing structured data in a local database.

C.    Files: Storing data in files on the device's storage.

D.    Cloud Storage: Using cloud services like Firebase or AWS to store data remotely.

  1. Networking: Many mobile apps need to communicate with remote servers. Key concepts include:

A.    HTTP Requests: Making requests to web servers to retrieve or send data.

B.    JSON and XML: Working with data formats commonly used for web communication.

C.    Networking Libraries: Using libraries like Retrofit or Volley to simplify network operations.

  1. Testing: Thorough testing is crucial for ensuring the quality of your app. Key concepts include:

A.    Unit Testing: Testing individual components of your app.

B.    Integration Testing: Testing how different components of your app work together.

C.    UI Testing: Testing the user interface of your app.

Publishing: Once your app is ready, you can publish it on the Google Play Store. This involves creating a developer account, preparing your app's listing, and submitting it for review.

4. Example: A Simple Android App (Conceptual Outline)

Example: A Simple Android App (Conceptual Outline)

Let's imagine a simple app that displays a list of to-do items.

  1. UI (XML Layout): You would create an XML layout file that defines the UI for the app. This might include a RecyclerView to display the list of items and an EditText for the user to enter new items.
  2. Activity (Java Code): You would create an Activity class that handles user interactions and updates the UI. This Activity would:

  • Inflate the XML layout.
  • Set up listeners for UI events (e.g., a button click to add a new item).
  • Retrieve data from a data source (e.g., a SQLite database).
  • Bind the data to the RecyclerView to display the list of items.

  1. Data Storage (SQLite): You would use a SQLite database to store the to-do items.
  2. Adding an Item: When the user clicks the "Add" button, the Activity would:

  • Retrieve the text from the EditText.
  • Create a new to-do item object.
  • Insert the item into the SQLite database.
  • Update the RecyclerView to display the new item.

This is a very simplified example, but it illustrates the basic concepts involved in Android development using Java. There are many more advanced topics to explore, such as working with location services, sensors, animations, and more. The Android developer documentation is your best resource for in-depth information

5. Implementations

Implementations

This is a simple APP

1. Activity (MainActivity.java):

Java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.EditText;

import android.widget.Button;

import android.view.View;

import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import androidx.recyclerview.widget.LinearLayoutManager;

import java.util.ArrayList;

import java.util.List;


public class MainActivity extends AppCompatActivity {

    private EditText editTextItem;

    private Button buttonAdd;

    private RecyclerView recyclerViewItems;

    private List<String> todoItems; // Simple list for now; would use a database later

    private TodoAdapter adapter;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        editTextItem = findViewById(R.id.editTextItem);

        buttonAdd = findViewById(R.id.buttonAdd);

        recyclerViewItems = findViewById(R.id.recyclerViewItems);

 

        todoItems = new ArrayList<>(); // Initialize the list

 

        // RecyclerView setup

        recyclerViewItems.setLayoutManager(new LinearLayoutManager(this)); // Vertical list

        adapter = new TodoAdapter(todoItems); // Create the adapter

        recyclerViewItems.setAdapter(adapter); // Set the adapter


        buttonAdd.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                String newItem = editTextItem.getText().toString().trim();

                if (!newItem.isEmpty()) {

                    todoItems.add(newItem); // Add to the list

                    adapter.notifyItemInserted(todoItems.size() - 1); // Notify adapter

                    editTextItem.setText(""); // Clear the EditText

                } else {

                    Toast.makeText(MainActivity.this, "Please enter an item", Toast.LENGTH_SHORT).show();

                }

            }

        });

    }

}


6. Adapter (TodoAdapter.java): Java

2. Adapter (TodoAdapter.java):

Java

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

 

public class TodoAdapter extends RecyclerView.Adapter<TodoAdapter.TodoViewHolder> {

 

    private List<String> todoItems;

 

    public TodoAdapter(List<String> todoItems) {

        this.todoItems = todoItems;

    }

 

    @Override

    public TodoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false); // Basic list item

        return new TodoViewHolder(view);

    }

 

    @Override

    public void onBindViewHolder(TodoViewHolder holder, int position) {

        String item = todoItems.get(position);

        holder.textViewItem.setText(item);

    }

 

    @Override

    public int getItemCount() {

        return todoItems.size();

    }

 

    public class TodoViewHolder extends RecyclerView.ViewHolder {

        public TextView textViewItem;

 

        public TodoViewHolder(View itemView) {

            super(itemView);

            textViewItem = itemView.findViewById(android.R.id.text1); // Standard text view ID

        }

    }

}

3. Layout (activity_main.xml):

XML

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:padding="16dp"

    tools:context=".MainActivity">

 

    <EditText

        android:id="@+id/editTextItem"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Enter an item" />

 

    <Button

        android:id="@+id/buttonAdd"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Add" />

 

    <androidx.recyclerview.widget.RecyclerView

        android:id="@+id/recyclerViewItems"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:layout_marginTop="16dp" />

 

</LinearLayout>


7. Key Improvements and Explanations

Key Improvements and Explanations:

  • RecyclerView: Uses RecyclerView which is the recommended way to display lists in Android. It's much more efficient than older methods like ListView.
  • Adapter: The TodoAdapter class handles the data for the RecyclerView. It takes the list of to-do items and creates the views that are displayed in the list.
  • Layout: A simple LinearLayout is used for the main layout. The RecyclerView is used to display the list.
  • Adding Items: The "Add" button's click listener adds the new item to the todoItems list and then notifies the adapter that the data has changed so the list is updated.
  • Toast: A Toast message is displayed if the user tries to add an empty item.

Next Steps:

  1. Create a new Android Studio project.
  2. Copy and paste the code into the appropriate files.
  3. Run the app on an emulator or physical device.

This is a very basic example. To make a more complete app, you would need to:

  • Implement data persistence: Use a database (like SQLite) or other storage mechanism to save the to-do items so they are not lost when the app is closed.
  • Improve the UI: Make the UI more visually appealing.
  • Add more features: Allow users to delete or edit items.

This improved example provides a more practical starting point for learning Android development.

This link will be helpful:


8. SECOND SIMPLE APP

Here’s a simple Android app project that displays a welcome message and allows the user to navigate to a second screen by clicking a button.

The project consists of:

  1. MainActivity.java – Displays a welcome message and a button to navigate to the second activity.
  2. SecondActivity.java – Displays a different message when navigated to.
  3. activity_main.xml – Layout for MainActivity.
  4. activity_second.xml – Layout for SecondActivity.
  5. AndroidManifest.xml – Declares both activities.

 

1. MainActivity.java (First Screen)

package com.example.simpleapp; // Replace with your actual package name

 

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

 

public class MainActivity extends AppCompatActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        // Find the button in the layout

        Button btnNavigate = findViewById(R.id.btnNavigate);

 

        // Set a click listener to navigate to the second activity

        btnNavigate.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Intent intent = new Intent(MainActivity.this, SecondActivity.class);

                startActivity(intent);

            }

        });

    }

}

What this does:

  • Loads the main layout.
  • Finds the button and sets a click listener.
  • When clicked, it starts SecondActivity.

 

2. SecondActivity.java (Second Screen)

package com.example.simpleapp;

 

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

 

public class SecondActivity extends AppCompatActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_second);

    }

}

What this does:

  • Loads the layout for the second screen.

9. activity_main.xml (UI for MainActivity)

3. activity_main.xml (UI for MainActivity)

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:gravity="center"

    android:padding="20dp">

 

    <!-- Welcome Text -->

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Welcome to My Simple App"

        android:textSize="20sp"

        android:textStyle="bold"

        android:paddingBottom="20dp"/>

 

    <!-- Button to navigate to the second screen -->

    <Button

        android:id="@+id/btnNavigate"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Go to Second Screen"/>

</LinearLayout>

What this does:

  • Displays a welcome message.
  • Has a button to go to the second screen.

 

4. activity_second.xml (UI for SecondActivity)

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:gravity="center"

    android:padding="20dp">

 

    <!-- Message for Second Screen -->

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="This is the Second Screen!"

        android:textSize="20sp"

        android:textStyle="bold"/>

</LinearLayout>

What this does:

  • Displays a message on the second screen.

10. AndroidManifest.xml (Declaring Activities)

5. AndroidManifest.xml (Declaring Activities)

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.simpleapp">

 

    <application

        android:allowBackup="true"

        android:theme="@style/Theme.AppCompat.Light"

        android:label="SimpleApp"

        android:icon="@mipmap/ic_launcher"

        android:roundIcon="@mipmap/ic_launcher_round">

       

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>

            </intent-filter>

        </activity>

 

        <activity android:name=".SecondActivity"/>

    </application>

</manifest>

What this does:

  • Declares MainActivity as the launcher activity.
  • Declares SecondActivity as another activity in the app.

 

How to Run This App

  1. Open Android Studio and create a new project.
  2. Copy & Paste the above files into your project.
  3. Run the app on an emulator or a real device.

Expected Behavior:

  • The app launches with a "Welcome to My Simple App" message.
  • Clicking the button navigates to the second screen, which displays "This is the Second Screen!".
This is a fully functional beginner-friendly Android app that introduces activity navigation using intents.

11. KOTLIN VERSION OF THE PROJECT Kotlin

KOTLIN VERSION OF THE PROJECT

Kotlin

package com.example.todolist

 

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.widget.EditText

import android.widget.Button

import android.view.View

import android.widget.Toast

import androidx.recyclerview.widget.RecyclerView

import androidx.recyclerview.widget.LinearLayoutManager

 

class MainActivity : AppCompatActivity() {

 

    private lateinit var editTextItem: EditText // Declare EditText variable (lateinit because it's initialized later)

    private lateinit var buttonAdd: Button // Declare Button variable

    private lateinit var recyclerViewItems: RecyclerView // Declare RecyclerView variable

    private val todoItems = ArrayList<String>() // Initialize the list (Kotlin's ArrayList)

    private lateinit var adapter: TodoAdapter // Declare TodoAdapter variable

 

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main) // Set the layout

 

        editTextItem = findViewById(R.id.editTextItem) // Initialize EditText

        buttonAdd = findViewById(R.id.buttonAdd) // Initialize Button

        recyclerViewItems = findViewById(R.id.recyclerViewItems) // Initialize RecyclerView


        // RecyclerView setup

        recyclerViewItems.layoutManager = LinearLayoutManager(this) // Set layout manager

        adapter = TodoAdapter(todoItems) // Create adapter

        recyclerViewItems.adapter = adapter // Set adapter

 

        buttonAdd.setOnClickListener { // Kotlin's concise way to set a click listener

            val newItem = editTextItem.text.toString().trim() // Get and trim text

            if (newItem.isNotEmpty()) { // Kotlin's way to check for empty string

                todoItems.add(newItem) // Add to list

                adapter.notifyItemInserted(todoItems.size - 1) // Notify adapter

                editTextItem.text.clear() // Clear EditText (Kotlin way)

            } else {

                Toast.makeText(this, "Please enter an item", Toast.LENGTH_SHORT).show() // Show Toast

            }

        }

    }

}

 // Adapter (TodoAdapter.kt):

 

import android.view.LayoutInflater

import android.view.View

import android.view.ViewGroup

import android.widget.TextView

import androidx.recyclerview.widget.RecyclerView

 

class TodoAdapter(private val todoItems: List<String>) : RecyclerView.Adapter<TodoAdapter.TodoViewHolder>() {

 

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {

        val view = LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false)

        return TodoViewHolder(view)

    }

 

    override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {

        val item = todoItems[position] // Kotlin's way to access list items

        holder.textViewItem.text = item

    }

    override fun getItemCount(): Int {

        return todoItems.size

    }

 

    class TodoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val textViewItem: TextView = itemView.findViewById(android.R.id.text1) // Initialize TextView

    }

}


12. Key Kotlin Changes and Explanations

Key Kotlin Changes and Explanations:

  • lateinit: Used for properties that will be initialized later (in onCreate). This avoids null checks.
  • val vs. var: val for read-only variables, var for mutable variables.
  • Kotlin Collections: ArrayList<String>() is how you create an ArrayList in Kotlin. Kotlin also has other collection types like List, MutableList, Map, etc.
  • Concise Click Listener: buttonAdd.setOnClickListener { ... } is a more compact way to set a click listener.
  • String Checks: newItem.isNotEmpty() is a cleaner way to check if a string is not empty.
  • Clearing EditText: editTextItem.text.clear() is the Kotlin way to clear the text.
  • List Access: todoItems[position] is how you access elements in a list.
  • Null Safety: Kotlin has a strong type system that helps prevent null pointer exceptions. lateinit and other features are designed to work with null safety in mind.

activity_main.xml (Layout): This remains the same as the Java version.

Steps:

  1. Create a new Android Studio project and choose Kotlin as the language.
  2. Replace the contents of MainActivity.kt and create TodoAdapter.kt with the code provided above.
  3. Make sure your activity_main.xml layout file is correct.
  4. Run the app.


 Swift for iOS

Swift

import UIKit

 

class ViewController: UIViewController {

 

    @IBOutlet weak var editTextItem: UITextField! // Outlet for the text input

    @IBOutlet weak var buttonAdd: UIButton! // Outlet for the add button

    @IBOutlet weak var tableViewItems: UITableView! // Outlet for the table view

 

    var todoItems: [String] = [] // Array to store to-do items

 

    override func viewDidLoad() {

        super.viewDidLoad()

 

        tableViewItems.dataSource = self // Set the data source for the table view

        tableViewItems.delegate = self // Set the delegate for the table view

 

        buttonAdd.addTarget(self, action: #selector(addItem), for: .touchUpInside) // Add target for button click

    }

 

    @objc func addItem() { // Function to handle adding an item

        guard let newItem = editTextItem.text?.trim(), !newItem.isEmpty else { // Check for empty input

            return // Exit if input is empty

        }

 

        todoItems.append(newItem) // Add the item to the array

        tableViewItems.reloadData() // Reload the table view to display the new item

        editTextItem.text = "" // Clear the text field

    }

}

 

// Conform to UITableViewDataSource and UITableViewDelegate

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return todoItems.count // Return the number of items

    }

 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) // Dequeue a reusable cell

        cell.textLabel?.text = todoItems[indexPath.row] // Set the cell text

        return cell

    }

}

13. Explanation and Key Swift Concepts

Explanation and Key Swift Concepts:

  1. @IBOutlet: Used to connect UI elements in Interface Builder (storyboard or XIB) to code. weak is important to prevent memory leaks.
  2. UITextField, UIButton, UITableView: Standard UIKit classes for text input, buttons, and table views.
  3. [String]: Swift's way to declare an array of strings.
  4. viewDidLoad(): Called after the view is loaded into memory. Used for initial setup.
  5. tableViewItems.dataSource = self and tableViewItems.delegate = self: These lines connect the table view to the ViewController so that the ViewController can provide the data and handle user interactions with the table view.
  6. buttonAdd.addTarget(...): Sets up a target-action relationship. When the button is tapped, the addItem() function will be called. #selector is used to reference the function.
  7. @objc: This attribute is needed because the addItem() function is being used with a selector, which is an Objective-C feature.
  8. guard let ... else { return }: A concise way to check for optional values and exit the function early if a condition is not met (in this case, if the input is empty or nil). This is much cleaner than nested if statements.
  9. todoItems.append(newItem): Adds the new item to the todoItems array.
  10. tableViewItems.reloadData(): Refreshes the table view to show the updated data.
  11. extension ViewController: UITableViewDataSource, UITableViewDelegate: This is how you make your ViewController conform to the protocols that the UITableView needs to function. It allows you to place the UITableView data source and delegate methods in a more organized way.
  12. tableView(_:numberOfRowsInSection:): A required method for UITableViewDataSource. It tells the table view how many rows to display.
  13. tableView(_:cellForRowAt:): Another required method for UITableViewDataSource. It's responsible for creating and configuring the cells that are displayed in the table view. dequeueReusableCell is used for performance; it reuses cells that are no longer visible.

Steps to Create the App:

  1. Create a new Xcode project: Choose "App" under the iOS tab.
  2. Open Main.storyboard: Drag and drop a UITextField, UIButton, and UITableView onto the view.
  3. Create Outlets and Action: Control-drag from the UI elements to the ViewController.swift file to create the @IBOutlet connections and the @IBAction (or the target-action as shown above).
  4. Set up the Table View Cell: In the storyboard, select the prototype cell in the table view. In the Attributes Inspector, give it the identifier "cell".
  5. Copy and paste the code: Replace the contents of ViewController.swift with the code provided above.
Run the app: You should now be able to enter text, tap the "Add" button, and see the items appear in the table view.