0% found this document useful (0 votes)
18 views116 pages

Ida All

The document provides an overview of mobile app development, focusing on portable devices, their types, evolution, and impact on society. It discusses key features, applications, hardware, software, and the components of mobile applications, emphasizing the importance of mobile apps in everyday life and business success. Additionally, it introduces Android as an open-source operating system, detailing its architecture and development environment.

Uploaded by

Varun Shivan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views116 pages

Ida All

The document provides an overview of mobile app development, focusing on portable devices, their types, evolution, and impact on society. It discusses key features, applications, hardware, software, and the components of mobile applications, emphasizing the importance of mobile apps in everyday life and business success. Additionally, it introduces Android as an open-source operating system, detailing its architecture and development environment.

Uploaded by

Varun Shivan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

Module: Introduction to Mobile App Development

Lesson 1: Introduction to Software Development for


Portable Devices

Topic: Overview of Portable Devices

1. Introduction to Portable Devices

Portable devices are compact, lightweight computing devices designed for ease of
mobility.

These devices allow users to perform computing tasks from virtually anywhere,
supporting various functions like communication, entertainment, and productivity.
Their popularity has surged due to the convenience they offer in daily life, making
them indispensable in both personal and professional contexts.
2. Types of Portable Devices

Portable devices are classified into several categories based on their functionality:

● Smartphones: Multi-functional devices primarily used for communication but


also support apps, internet browsing, and multimedia.
● Tablets: Larger screens compared to smartphones, primarily used for media
consumption, reading, and light computing tasks.
● E-readers: Devices specifically designed for reading digital books, offering
features like e-ink displays to minimise eye strain.
● Portable Gaming Consoles: Dedicated devices for gaming, optimised for
delivering enhanced graphics, sound, and control systems.
3. Evolution of Portable Devices

● Early Days: The earliest portable devices, like Personal Digital Assistants
(PDAs) and early mobile phones, had limited functionality, such as managing
contacts and making voice calls.
● Modern Era: Advances in technology have enabled portable devices to have
powerful processors, high-resolution displays, and extensive connectivity
options, enabling multitasking, high-speed internet access, and immersive
experiences.
● Future Trends: Upcoming innovations, such as foldable screens, augmented
reality (AR), and 5G connectivity, are set to further enhance the functionality
and interactivity of portable devices.

4. Operating Systems for Portable Devices

● Early Days: Operating systems for portable devices started with simple
systems focused on basic functionality, such as Palm OS for PDAs and
Symbian for early smartphones.
● Modern Era: Android, developed by Google, is an open-source operating
system widely used for its flexibility across different manufacturers, while
Apple’s iOS offers a proprietary, secure, and seamless user experience. Other
OS options include Windows Mobile and specialised systems like Kindle OS.
● Future Trends: Future operating systems are expected to focus on improving
AI integration, better resource management, and supporting new hardware
advancements like AR and IoT capabilities.

5. Impact of Portable Devices on Society

Portable devices have significantly transformed daily life, enabling communication,


remote work, education, and entertainment. They have fostered a digital culture where
information is readily accessible. However, they also present challenges like
over-reliance on screens, privacy issues, and digital security concerns.
Topic 2: Applications of Portable Devices

1. Key Features of Portable Devices


Portable devices are defined by several key features that contribute to their
widespread adoption:

● Mobility: Compact size and lightweight design make these devices highly
portable, allowing users to access applications, data, and the internet while on
the move.
● Connectivity: Equipped with cellular, Wi-Fi, Bluetooth, and sometimes even
satellite communication, these devices enable users to stay connected
anywhere and anytime.
● Versatility: With features like cameras, GPS, sensors, and access to millions
of apps, portable devices cater to a wide range of needs, from communication
to entertainment, productivity, and more.

2. Communication and Social Connectivity


Portable devices have transformed how people communicate and engage socially:

● Instant Messaging and Video Calls: Apps like WhatsApp, Skype, and Zoom
facilitate instant communication, allowing for seamless text, voice, and video
interactions.
● Social Media Integration: Devices support social media platforms like
Facebook, Instagram, and Twitter, enabling users to share updates, photos, and
videos, as well as engage with content globally.

3. Productivity and Entertainment


Portable devices support a variety of applications designed to boost productivity and
provide entertainment:

● Productivity Apps: Devices offer tools for email management, cloud storage,
scheduling, note-taking, and collaborative work through apps like Microsoft
Office, Google Drive, and Evernote.
● Entertainment Apps: Streaming platforms like Netflix, Spotify, and YouTube
offer a wide range of multimedia content, while gaming apps provide
interactive entertainment options.

4. Education and Learning


Portable devices have significantly impacted education, making learning more
accessible and interactive:

● E-learning Platforms: Apps like Coursera, Khan Academy, and Duolingo


allow users to engage in online courses, tutorials, and language learning from
anywhere.
● E-books and Digital Libraries: Platforms like Kindle, Google Books, and
other digital libraries provide access to a vast amount of educational content,
facilitating self-paced learning and research.
Topic 3: Hardware of Portable Devices

1. Overview of Hardware in Portable Devices


Portable devices rely on hardware components specifically designed for efficiency
and low power consumption. The hardware architecture aims to balance performance
with battery life, making it suitable for mobility and daily use. Components like
processors, memory, storage, and displays are optimised to work efficiently in a
compact form factor.

2. Processors for Portable Devices


Processors are the core computing units in portable devices, managing both
processing power and energy efficiency.

● Types of Processors:
o ARM Processors: Known for their Reduced Instruction Set
Computing (RISC) architecture, these processors are widely used in
smartphones and tablets for their performance efficiency and energy
savings.
o x86 Processors: Found in high-performance tablets and 2-in-1
devices, these processors offer compatibility with desktop applications
but may consume more power compared to ARM processors.
● Key Features:

o Multi-core Architecture: Multi-core processors enable better


multitasking, improving the device's ability to run multiple
applications simultaneously.
o Integrated Graphics: These processors often include integrated
graphics units, which enhance the visual experience and support
high-resolution displays and graphical tasks.

3. Memory and Storage for Portable Devices


Memory and storage play a crucial role in determining the performance and capacity
of portable devices.
● Memory (RAM): Provides temporary storage for running applications. RAM
sizes range from 2GB in budget devices to 12GB or more in high-end devices,
impacting the device’s ability to handle multiple apps simultaneously.
● Storage:

o Internal Storage: Uses flash memory technologies like eMMC


(embedded MultiMediaCard) and UFS (Universal Flash Storage),
offering faster data access and reliability.
o Expandable Storage: Many devices support expandable storage via
microSD cards, allowing users to increase capacity for additional apps,
media, and files.

● Key Features:

o Speed: Faster memory and storage significantly enhance a device's


responsiveness and overall performance.
o Capacity: Devices with higher storage capacities can store more
applications, multimedia files, and data.

4. Display and Touchscreen for Portable Devices


The display and touchscreen are key interaction points for portable devices,
influencing user experience.

● Types of Displays: Portable devices feature various types of displays, such as


LCD (Liquid Crystal Display), OLED (Organic Light Emitting Diode), and
AMOLED (Active Matrix OLED), each offering different levels of color
vibrancy, energy consumption, and resolution.
● Touchscreen Technologies: Capacitive touchscreens are the most common in
modern devices, providing multi-touch capabilities, better responsiveness, and
support for gestures like pinch-to-zoom and swiping.
Topic 4: Software of Portable Devices

1. Operating Systems for Portable Devices


Operating systems (OS) are fundamental to portable devices, enabling efficient
communication between hardware and software components. They handle tasks like
memory management, process scheduling, and device control to ensure smooth
performance.

● Key Characteristics:
o Multitasking: Allows running multiple apps simultaneously.
o User Interface: Provides a graphical interface that makes interaction
intuitive.
o Security: Offers features like encryption, app permissions, and secure
boot to protect user data.
● Examples:

o Android: An open-source OS is known for its customisation, wide app


ecosystem, and compatibility with various devices.
o iOS: Apple’s proprietary OS, recognised for its secure environment,
smooth user experience, and exclusive compatibility with Apple
devices.

2. Application requirements for Portable Devices


Efficient memory and storage management are crucial for the performance of portable
devices.
● Memory (RAM): Provides temporary storage for running applications,
enabling quick data access and faster app loading.

o Configurations: Range from 2GB in basic devices to 12GB or more in


high-end models, affecting the device's ability to handle multitasking.

● Storage Types:

o Internal Storage: Utilises flash memory types like eMMC (embedded


MultiMediaCard) and UFS (Universal Flash Storage) for faster data
access and reliable performance.
o Expandable Storage: Portable devices often support expandable
storage via microSD cards, allowing users to increase their storage
capacity for apps, media, and files.

● Key Features:

o Speed: Faster memory and storage contribute to a more responsive


device experience.
o Capacity: Higher storage capacities enable users to store more
applications, multimedia, and files.

3. User Interaction with Portable Devices


Displays and touchscreens are essential components that shape user interaction and
experience.

● Display Types:

o LCD (Liquid Crystal Display): Offers good colour accuracy and


brightness, widely used in smartphones and tablets.
o OLED (Organic Light-Emitting Diode): Provides better contrast,
faster refresh rates, and deeper blacks, enhancing media consumption.

● Touchscreen Technologies:

o Capacitive Touchscreens: Respond to the electrical properties of the


human body, enabling precise multi-touch functionality.
o Resistive Touchscreens: Respond to pressure, making them suitable
for stylus input but less sensitive than capacitive screens.

● Key Features:

o Resolution: Higher-resolution displays provide sharper visuals and


enhance the viewing experience.
o Durability: Advanced screen technologies offer better resistance to
scratches and impacts, ensuring longevity.
Topic 5: Components of Mobile Application

1. Overview of Mobile Application Components


Mobile applications consist of various components that work together to deliver a
cohesive user experience. These components can be broadly categorised into user
interface elements, background processing components, and data
storage/communication mechanisms. Each plays a distinct role in creating functional
and responsive apps.

2. User Interface (UI) Components


UI components are responsible for user interaction and visual presentation. They help
users navigate, input data, and receive feedback.

● Examples of UI Components:
o Button: Allows users to trigger specific actions, such as submitting a
form or navigating to another screen.
o Text Field: Enables users to input text data, such as entering a
username or password.
o Image: Displays visual content within the app, enhancing the app’s
appearance and providing context to users.
● Mobile App Screen: A typical mobile app screen is composed of these UI
elements, organised in a layout that provides intuitive navigation and
functionality.

3. Background Processing Components


These components manage operations that run behind the scenes, without direct user
interaction.

● Definition: Background components handle tasks like fetching data from a


server, playing music, or performing calculations.
● Purpose: They ensure that long-running tasks do not disrupt the user
interface, maintaining the app's responsiveness.
● Examples:
o Services: Used for long-running operations like playing music or
downloading files.
o AsyncTask (in older Android versions): Used to perform background
tasks like network operations while keeping the UI responsive.

4. Data Storage and Communication Components


These components manage data storage and communication within the app and with
external services.

● Data Storage:
o Definition: Mechanisms to store and retrieve data for later use,
ensuring data persistence across sessions.
o Examples:

▪ Databases (e.g., SQLite): Store structured data.


▪ File Storage: For saving images, documents, and other files.
▪ Shared Preferences: Used for storing simple key-value pairs,
such as user settings or app preferences.

● Communication:

o Definition: Handles data exchange within the app and with external
services.
o Examples:

▪ Network Requests: Facilitate interaction with remote servers


via APIs.
▪ Broadcast Receivers: Listen for and respond to system-wide
broadcast announcements or app-specific broadcasts.

o Purpose: Enables seamless interaction between different parts of the


app and external systems, supporting functionalities like data
synchronisation and real-time updates.
Topic 6: Need for Mobile Apps

1. Mobile Apps: Enhancing Everyday Life


Mobile apps have become an essential part of modern life, serving various purposes
and offering significant convenience.

● Ubiquity in Daily Life: Mobile apps are used for a wide range of tasks, from
communication to shopping, making everyday activities more efficient and
manageable.
● Wide Range of Uses: Apps cater to diverse needs such as:
o Communication: Apps like WhatsApp, Zoom, and Skype enable
instant messaging, video calls, and social media interaction.
o Entertainment: Platforms like Netflix, YouTube, and Spotify provide
streaming services for video and music content.
o Finance: Banking apps, mobile wallets, and investment tools facilitate
financial management and transactions.
o Health: Apps for fitness tracking, telemedicine, and mental well-being
help users maintain a healthier lifestyle.
o Shopping: E-commerce apps streamline online shopping, allowing
users to browse, purchase, and track orders seamlessly.
2. Mobile Apps: Driving Business Success
Mobile apps play a crucial role in boosting business performance and customer
engagement.

● Increased Customer Engagement: Apps allow businesses to engage with


customers directly, offering personalised content, notifications, and loyalty
rewards.
● Enhanced Sales and Revenue: E-commerce and service-based apps simplify
the purchasing process, often leading to increased sales and revenue for
businesses.
● Brand Visibility and Accessibility: Having a mobile app enhances brand
visibility and provides users with 24/7 access to services, improving customer
satisfaction and retention.

3. Growth and Future Trends in Mobile Apps


The mobile app market is rapidly growing, driven by advancements in technology and
increasing user demand.

● Market Growth: The mobile app industry is projected to expand


significantly, with gaming, social media, and shopping apps leading in
popularity.

● Emerging Trends:

o 5G Integration: Faster connectivity will enable more sophisticated


apps with improved performance and real-time interactions.
o AI and Machine Learning: Enhanced personalisation, predictive
analytics, and smarter app functionalities.
o Augmented Reality (AR): More apps will leverage AR for immersive
experiences in gaming, education, and e-commerce.
o IoT Integration: Apps that control smart devices, making homes,
vehicles, and workplaces more connected and efficient.
Module: Introduction to Mobile App Development
Lesson 2: Introduction to Android

Topic 1: Overview of Android

1. What is Android?
Android is an open-source mobile operating system developed by Google, based on
the Linux kernel. It is designed primarily for touchscreen devices like smartphones
and tablets, but it is also used in various devices like smart TVs, wearables, and cars.

● Features:
o Offers a rich app ecosystem with millions of apps available on the
Google Play Store.
o Supports diverse hardware, making it adaptable across various device
types and manufacturers.
o Provides a customisable user interface, allowing manufacturers and
users to personalise their devices.

2. Architecture Layers in Android


Android's architecture is designed with layers that ensure modularity, security, and
ease of development:

● Applications: These are the user-facing apps like email, SMS, maps, and
browsers. They utilise the underlying layers to interact with the hardware and
system services.
● Application Framework: Provides APIs for managing UI, resources,
notifications, and other core functionalities. It enables developers to build
dynamic applications.
● Libraries: These are C/C++ libraries that provide essential functions like data
storage, graphics rendering, and web browsing. Key libraries include WebKit,
OpenGL, and SQLite.
● Android Runtime (ART): The runtime environment that includes core
libraries and the Dalvik Virtual Machine, which allows apps to run efficiently.
● Linux Kernel: Serves as the hardware abstraction layer, managing device
drivers, memory, power management, and other fundamental system
functions.

3. Development Environment
The development environment for Android app development includes tools and
frameworks that facilitate app creation, testing, and debugging:

● Android Studio: The official Integrated Development Environment (IDE) for


Android, based on IntelliJ IDEA. It offers tools for designing UIs, writing
code, testing apps, and deploying them.
● Languages:

o Java and Kotlin: The primary programming languages for Android


app development.
o C++ Support: Through the Android Native Development Kit (NDK),
which allows developers to implement parts of the app using native
code.

● Key Tools:
o Android SDK (Software Development Kit): Provides tools and
libraries necessary for developing Android apps.
o Emulators: Simulate Android devices on a computer, allowing
developers to test apps across different device configurations.
o ADB (Android Debug Bridge): A command-line tool that facilitates
communication with Android devices, useful for debugging and
running commands.
Topic 2: Android Versions

1. Early Android Versions


These versions laid the foundation for Android’s core functionalities, gradually
introducing more advanced features:

● Android 1.0 and 1.1: Released in 2008 and early 2009, these initial versions
had basic functions, including Google apps like Gmail, Maps, and YouTube.
● Android Cupcake (1.5): Introduced in April 2009, it featured the first
on-screen keyboard and support for third-party app widgets.
● Android Donut (1.6): Released in September 2009, this version offered an
improved user interface, universal search, and support for different screen
sizes.
● Android Éclair (2.0, 2.1): Released in late 2009 and early 2010, Éclair
introduced Google Maps navigation, improved speed, and support for
HTML5.
● Android Froyo (2.2): Launched in May 2010, Froyo introduced USB
tethering, Wi-Fi hotspot functionality, and performance optimisations.
● Android Gingerbread (2.3): Released in December 2010, this version offered
an enhanced UI, better keyboard, and support for NFC.

2. Mid-Android Versions
These versions focused on significant UI improvements, better performance, and
additional features:

● Android Honeycomb (3.0, 3.1, 3.2): Released in 2011, Honeycomb was


designed specifically for tablets, featuring a holographic UI and improved
multitasking.
● Android Ice Cream Sandwich (4.0): Launched in October 2011, it brought
virtual buttons, improved copy-paste functionality, and a more unified design.
● Android Jelly Bean (4.1, 4.2, 4.3): Starting in mid-2012, Jelly Bean
introduced Project Butter for smoother performance, expandable notifications,
and Google Now.
● Android KitKat (4.4): Released in October 2013, KitKat improved
performance on low-end devices, added immersive mode, and introduced “OK
Google” voice search.
● Android Lollipop (5.0, 5.1): Launched in November 2014, Lollipop brought
a new Material Design interface, improved notifications, and better battery
management.
● Android Marshmallow (6.0): Released in October 2015, Marshmallow
introduced Doze mode for battery saving and a new app permissions model.

3. Latest Android Versions


These versions offer significant improvements in performance, privacy, and user
experience:

● Android Nougat (7.0, 7.1): Released in 2016, it featured multi-window


support, an improved Doze mode, and Vulkan API for better graphics.
● Android Oreo (8.0, 8.1): Launched in 2017, Oreo introduced
picture-in-picture mode, notification channels, and autofill APIs.
● Android Pie (9.0): Released in 2018, Pie added a new gesture-based
navigation system, digital well-being features, and enhanced AI for adaptive
battery and brightness.
● Android 10: Launched in September 2019, this version introduced a
system-wide dark mode, new gesture navigation, and improved privacy
controls.
● Android 11: Released in September 2020, it included a dedicated
conversations section in notifications, built-in screen recording, and one-time
permissions.
● Android 12: Launched in October 2021, it introduced the “Material You”
design, an enhanced privacy dashboard, and faster performance.
● Android 13 (Tiramisu): Released in August 2022, it focused on improved
privacy controls, new notification permissions, and support for multilingual
users.
● Android 14 (Upside Down Cake): Expected in 2024, it aims to enhance
performance, refine the user interface, and introduce advanced security
features.
Topic 3: Challenges in Developing Android Apps

1. Device Fragmentation
Device fragmentation refers to the wide variety of Android devices with different
screen sizes, hardware specifications, and OS versions.

● Impact: Developers must ensure that apps run smoothly across different
devices, accounting for variations in performance, screen resolution, and
software compatibility.
● Solution: Using adaptive design techniques, thorough testing across multiple
devices, and leveraging features like constraint layouts can help handle device
fragmentation effectively.

2. Security Concerns
Security is a significant challenge due to the open-source nature of Android, making it
more vulnerable to attacks.

● Key Concerns:

o Malware and Viruses: Apps from unofficial sources may contain


malware, posing security risks.
o Data Privacy: Ensuring user data protection and compliance with
regulations (like GDPR) can be challenging.

● Solution: Implementing secure coding practices, using data encryption, and


following Google’s security guidelines can enhance app security.

3. Continuous Updates and Compatibility


Android’s frequent OS updates and compatibility requirements pose challenges for
app developers:

● Frequent OS Updates: With regular updates, developers must keep apps


compatible with the latest Android versions while supporting older devices.
● Cross-Compatibility Challenges: Apps must function correctly across
different Android versions, which may have unique features or limitations.
● Legacy Support and Maintenance: Ensuring support for older Android
versions often adds to development and maintenance efforts.
● Solution: Regularly updating apps, using backwards-compatible APIs, and
performing extensive testing on multiple Android versions can maintain
compatibility and improve user experience.

4. User Interface (UI) Design


Designing an intuitive and responsive user interface that adapts well to various screen
sizes and resolutions can be challenging.

● Responsive Layouts: Following Android’s Material Design guidelines and


using responsive layout techniques can help create adaptive UIs that offer a
consistent experience across devices.
● Usability Testing: Continuous testing and user feedback are essential to
improve UI design and ensure that it meets user expectations.
Topic 4: Major Components of Android Platform

1. Key Components of Android


The Android platform consists of essential components that manage various app
functionalities and ensure smooth user interaction:

● Activities: Represent the user interface screen that allows user interaction.
Each activity is typically focused on a single task, like browsing photos or
sending emails.
● Services: Handle background operations that do not require a user interface,
such as playing music, syncing data, or handling network operations.

2. Data Management Components


1. Content Providers

● Purpose: Content providers manage access to a structured set of


data and enable data sharing between different applications. They
serve as a centralised repository for data storage, allowing apps to
read and modify data securely.
● Usage Examples: Content providers are often used for sharing
contacts, images, or other data that needs to be accessible across
apps. Apps like contacts, calendars, and media libraries use
content providers for data access.

2. Broadcast Receivers

● Purpose: Broadcast receivers listen for and respond to


system-wide broadcast announcements. They enable apps to
handle events like incoming calls, device boot completion, low
battery warnings, and changes in network connectivity.
● Usage Examples: Broadcast receivers are commonly used for
triggering background tasks in response to system events or
changes in device state, such as showing notifications when a
new message arrives.
3. Communication and Interaction Components
These components manage communication between app elements and enable user
interaction:

● Intents: Facilitate communication between different components like


activities, services, and broadcast receivers. Intents allow data to be passed
between components and help initiate specific actions like starting a new
activity or service.
● Widgets: Miniature application views that can be embedded within other
applications, usually on the home screen. They provide quick access to app
functionalities, like a weather widget displaying current weather conditions.

4. User Notifications Components


User notifications inform users about events that require their attention, even when
the app is not actively in use.

● Notification Manager: Manages and displays notifications in the Android


system bar. It allows users to interact with notifications, such as viewing or
responding to messages.
● Toast Messages: Short, temporary pop-up messages that provide brief
feedback or information to users without interrupting their activity.
Topic 5: Need for Android Apps

1. The Growth and Popularity of Android


Android has become the world’s most popular mobile platform, with over a billion
active devices globally. The open-source nature of Android, built on a Linux-based
architecture and backed by Google, makes it a comprehensive platform that supports a
wide range of devices, including smartphones, tablets, smart TVs, and wearables.

● Versatility: Android supports a powerful development framework that allows


developers to use Java and XML for creating diverse applications.
● Variety of Devices: From entry-level phones to high-end devices, Android
operates on a broad spectrum, making it accessible to a large global audience.

2. The Market Demand for Android Apps


There is a substantial demand for Android apps due to the growing number of
smartphone and tablet users worldwide.

● Consumer Demand: Users consistently seek innovative and functional apps


that cater to various needs like entertainment, productivity, and health.
● Business Opportunities: The expanding Android market offers ample
opportunities for developers and businesses to tap into different sectors,
increasing their reach and revenue potential.
● Global Reach: With Android’s large user base, app distribution becomes
easier on a global scale, allowing developers to target a diverse audience
across different regions.

3. Benefits of Developing Android Apps


Android app development offers several benefits, making it an attractive choice for
developers:

● Open-Source Platform: Android’s open-source nature encourages


innovation, providing developers with a vast range of tools and libraries to
create versatile apps.
● Flexibility and Customisation: The platform allows developers to design
highly customisable user interfaces, enhancing the user experience based on
specific requirements.Integration with Google Services: Android apps can
seamlessly integrate with Google services like Maps, Drive, and more,
improving app functionality through Google APIs.
Topic 6: Device Compatibility in Android App
Development

1. Hardware Compatibility
Android devices have diverse hardware capabilities, including differences in
processors, RAM, sensors, and other components. This variability can pose challenges
when developing apps that perform well across all devices.

● Challenges:
o Ensuring that the app performs optimally on devices with different
hardware configurations.
o Supporting various hardware features like cameras, GPS, and sensors
without compromising functionality.
● Solutions:

o Feature Detection: Implement checks to determine the availability of


certain hardware features and adjust app behaviour accordingly.
o Graceful Degradation: Design the app to maintain core functionality
even if certain hardware features are unavailable.
o Code Optimisation: Focus on efficient memory usage and
performance to accommodate devices with lower hardware
specifications.
o Extensive Testing: Test the app on a broad range of devices to identify
potential issues and ensure consistent performance.

2. Software Version Compatibility


Different devices run different versions of the Android operating system, making it
challenging to ensure smooth app functionality across versions.

● Challenges:

o Supporting both older and newer OS versions.


o Handling deprecated APIs while introducing new features.
● Solutions:

o Backward Compatibility Libraries: Use libraries like AndroidX to


maintain compatibility with older versions of Android.
o Regular Updates: Continuously update the app to integrate new
Android features while retaining support for older versions.
o Thorough Testing: Test the app on various OS versions using
emulators and real devices to detect compatibility issues.

3. Device Fragmentation
Device fragmentation refers to the wide variety of Android devices in terms of screen
sizes, resolutions, and hardware specifications. This presents challenges for app
developers aiming for compatibility across numerous devices.

● Challenges:

o Ensuring the app's UI and performance work well on different screen


sizes and resolutions.
o Identifying and resolving bugs or performance issues that may arise
from varied hardware setups.

● Solutions:

o Android Studio’s Emulator: Use emulators to simulate various


device configurations, allowing for efficient testing of different screen
sizes and hardware specifications.
o Responsive Layouts: Implement responsive UI design patterns that
adapt to different screen sizes and orientations.
MODULE NAME: Debugging and User
Interface
Lesson 1: Basics of Android Application
Development

Topic 1: Programming Language for Android


(Kotlin) Overview
Introduction to Kotlin
Kotlin is a modern, statically-typed programming language designed by JetBrains. It
is fully interoperable with Java and officially supported by Google for Android
development since 2017.

● Statically-Typed Language: It checks the types of variables at compile time,


catching errors early and making the code more reliable.
● JetBrains Design: Developed by JetBrains, the creator of IntelliJ IDEA,
Kotlin was designed to address common issues in Java and boost developer
productivity.
● Java Interoperability: Kotlin integrates seamlessly with Java, enabling
developers to use both languages within the same project.
● Google’s Endorsement: Official support from Google since 2017 has
accelerated its adoption, making it a primary language for Android
development.

Key Features of Kotlin


Kotlin offers several key features that enhance the Android development process:

● Concise Syntax: Kotlin reduces boilerplate code, making development faster


and more efficient.

Example: Java’s verbose code for a data class can be written concisely in
Kotlin

data class User(var name: String)

● Null Safety: Kotlin’s type system differentiates between nullable and


non-nullable types, helping to prevent NullPointerExceptions.

Example:

var name: String = "John" // Non-nullable


var nullableName: String? = null // Nullable
● Extension Functions: Allows adding new functionality to existing classes
without altering their source code.

Example

fun String.addHello(): String = "Hello, $this"


println("World".addHello()) // Outputs "Hello, World"

● Coroutines: Provides an efficient way to handle asynchronous programming,


making background tasks easier to manage.

Example

import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}

Advantages of Using Kotlin for Android Development


Kotlin offers multiple advantages that make it a preferred choice for Android
development:

● Seamless Java Interoperability: Allows developers to use existing Java code


and libraries within Kotlin projects.
● Increased Productivity: Kotlin’s concise syntax and powerful language
features reduce coding time and errors.
● Improved Code Safety and Readability: Null safety, smart casts, and data
classes enhance code clarity and prevent common errors.
● Active Community Support: Strong support from JetBrains and Google,
coupled with an active community, provides developers with abundant
resources, libraries, and tools.

Advantages of Kotlin over Java


Kotlin offers several benefits over Java:

● Concise Syntax: Reduces verbosity, making the code easier to read and write.
● Null Safety: Minimises null pointer exceptions, increasing code reliability.
● Extension Functions and Smart Casts: Simplify code by adding
functionality to existing classes and reducing explicit type casting.
● Data Classes and Improved Type Inference: Generate common methods
automatically and reduce explicit type declarations, respectively.
● Coroutines for Async Programming: Coroutines provide a more intuitive
and efficient way to manage asynchronous tasks.

Popular Applications Developed Using Kotlin


Several well-known apps have been developed using Kotlin, showcasing its versatility
and performance:

● Pinterest: Migrated to Kotlin for better maintainability and productivity.


● Uber: Uses Kotlin to benefit from its concise syntax and improved safety.
● Trello: Leverages Kotlin for a more efficient and readable codebase.
Topic: 2 Android Studio Kotlin
Kotlin Support in Android Studio
Kotlin is natively supported in Android Studio, allowing developers to write Kotlin
code directly without additional plugins or tools. This seamless integration provides
an efficient development experience within a familiar environment.

● Native Support: Since Kotlin’s support is built into Android Studio,


developers can use features like code completion, refactoring tools, syntax
highlighting, and error checking.
● Interoperability with Java: Android Studio supports mixed projects,
enabling developers to call Kotlin code from Java and vice versa, facilitating
incremental migration and mixed-language projects.
● Project Templates: The IDE offers templates and wizards specifically for
Kotlin, making it easy to create new Kotlin projects and apps efficiently.

Enhanced Development Experience


Kotlin’s integration in Android Studio includes several tools that boost productivity
and simplify coding:

● Intelligent Code Completion: Offers context-aware suggestions that help


developers write code faster and with fewer errors.

o Example: In Kotlin, using Ctrl + Space triggers code completion,


making development faster.

● Refactoring Tools: Refactoring tools allow developers to rename variables,


extract methods, and update all references across the codebase automatically.

o Example: Right-clicking on a variable or function and selecting


"Refactor > Rename" ensures that all references are updated correctly.

● Debugging Features: Kotlin-specific debugging tools provide insights into


the app’s runtime behaviour, making it easier to identify and resolve issues.
● Kotlin Project Templates: Android Studio offers built-in templates for
creating basic activities, navigation drawers, and other common app
components, saving time during the initial setup.

Kotlin's Unique Features in Android Studio


Kotlin introduces several features that enhance the Android development process:

● Null Safety: Kotlin minimises the risk of NullPointerExceptions by


distinguishing between nullable and non-nullable types.

Example

var nonNullableName: String = "Chandra" // Cannot hold null


var nullableName: String? = "Shekar" // Can hold null
println(nullableName?.length) // Safe call operator
This approach ensures that potential null values are explicitly handled, reducing
runtime crashes.

● Extension Functions: Developers can add new functions to existing classes


without modifying their source code.

Example

fun String.addHello(): String = "Hello, $this"


println("World".addHello()) // Outputs "Hello, World"

● Coroutines: Kotlin’s coroutines simplify asynchronous programming, providing


a straightforward way to handle background tasks without blocking the main
thread.

Example

import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
val data = fetchData()
println("Data received: $data")
}
println("Request sent!")
}

suspend fun fetchData(): String {


delay(1000L) // Simulates network delay
return "Hello, World!"
}

● Interoperability Tools: Android Studio includes built-in tools for converting


Java code to Kotlin, making migration easier.

Example:

1. Open the Java file in Android Studio.


2. Go to Code > Convert Java File to Kotlin File.
Topic 3: Interface in Android Studio
Android Studio User Interface Overview

Project View

● Description: Organise and navigate through your project files.


● Details: The Project View allows you to see the structure of your project,
making it easier to find and manage files and directories.

Editor Window

● Description: Write and edit your code with syntax highlighting and error
checking.
● Details: The Editor Window is where you write your code. It provides features
like syntax highlighting, error checking, and code completion to enhance
productivity and reduce errors.

Tool Windows

● Description: Access additional tools like the Logcat, Terminal, and Device
File Explorer.
● Details: Tool Windows provide access to various tools that aid in
development, such as Logcat for logging, Terminal for command line tasks,
and Device File Explorer for navigating the file system on your device.

Key Components of the Interface

Toolbar

● Description: Quick access to common actions like running, debugging, and


syncing your project.
● Details: The Toolbar contains buttons for common tasks like running your
app, debugging, and syncing your project with Gradle files. It provides quick
access to frequently used actions.

Navigation Bar

● Description: Navigate through your project hierarchy quickly.


● Details: The Navigation Bar allows you to quickly move through your
project’s hierarchy, making it easier to switch between different files and
directories.

Status Bar

● Description: Provides information about the current state of your project and
environment.
● Details: The Status Bar displays information about the current state of your
project, such as warnings, errors, and the status of background tasks.
Logcat

● Description: View and filter logs from your running application for
debugging.
● Details: Logcat is a tool that displays logs from your running application. You
can filter logs by tag, priority, and other criteria to debug your app effectively.

Customising the Interface for Productivity

Themes and Appearance

● Description: Customise the look and feel of the IDE to reduce eye strain and
improve focus.
● Details: You can change the theme of Android Studio to suit your preferences.
Options include light, dark, and high-contrast themes. You can also customise
font sizes and colours to create a comfortable coding environment.
● Procedure:

1. Open Preferences/Settings:

▪ Go to File > Settings (or Android Studio > Preferences on


macOS).

2. Appearance & Behavior:

▪ In the Settings/Preferences dialogue, navigate to Appearance &


Behavior > Appearance.

3. Select Theme:

▪ Under the Theme dropdown, choose from several built-in


themes such as Light, Darcula, or High Contrast.

4. Customise Fonts and Colours:

▪ Navigate to Editor > Colour Scheme to customise the font size,


style, and colours for different code elements.

5. Apply and Restart:

▪ Click Apply and OK to save the changes. Restart Android


Studio if necessary to apply the new theme.

Keyboard Shortcuts

● Description: Configure and use keyboard shortcuts to speed up common


tasks.
● Details: Keyboard shortcuts can be configured to perform tasks quickly. You
can customise existing shortcuts or create new ones to fit your workflow,
reducing the need to navigate through menus.
● Procedure:

1. Open Keymap Settings:

▪ Go to File > Settings (or Android Studio > Preferences on


macOS) and navigate to Keymap under the Appearance &
Behavior section.

2. Select a Keymap:

▪ Android Studio comes with several predefined keymaps such as


Default, Eclipse, Emacs, and Visual Studio.

3. Search for Actions:

▪ In the Keymap settings, search for specific actions using the


search bar (e.g., "Run" to find the shortcut for running your
application).

4. Customise Shortcuts:

▪ Right-click on the action and select Add Keyboard Shortcut.


Enter the desired key combination and click OK. Resolve any
conflicts if the shortcut is already in use.

5. Export and Import Keymaps:

▪ Export your customised keymap by clicking on the Export


button and saving the keymap file. Import a keymap by
clicking on the Import button and selecting the keymap file.

Tool Window Layouts

● Description: Arrange and save tool window layouts that fit your workflow.
● Details: You can customise the layout of tool windows to create an efficient
workspace. Save your preferred layout and switch between different layouts
depending on your current task.

Plugins

● Description: Extend the functionality of Android Studio with a wide range of


plugins available from the JetBrains repository.
● Details: Plugins add additional functionality to Android Studio. You can
browse and install plugins from the JetBrains repository to enhance your
development experience.
Topic 5: First Android Application Overview
Steps to Create a New Android Project in Android Studio

● Open Android Studio: Launch Android Studio and select "New Project"
from the welcome screen.

● Choose Project Template: In the "Create New Project" window, select an


appropriate project template, such as "Empty Activity," which provides a basic
setup for the project.

● Configure Project Settings: Enter the following information:

o Name: Set a name for the application (e.g., "FirstApplicationDev").


o Package Name: Define a unique package name (e.g.,
"com.example.firstapplicationdev").
o Save Location: Choose a directory to save the project.
o Language: Select Kotlin as the programming language.
o Minimum SDK: Choose the minimum API level, such as "API 21:
Android 5.0 (Lollipop)," to ensure compatibility with a wide range of
devices.

● Click "Finish" to create the project and start coding.

Naming the Project and Configuring the Initial Setup

● Naming the Project: Choose a meaningful project name that reflects the
purpose of the app. This name is used for internal project organisation and
displayed in the IDE.

● Configuring Initial Setup:


o Gradle Files: Android Studio automatically generates the build files
(e.g., build.gradle) necessary to configure dependencies and other
settings.
o Project Structure: The IDE sets up the project structure, including
directories for Java/Kotlin code, resources, and layout files.

Overview of the XML Code Used for the Layout

The layout for the first Android app is defined in XML, primarily in the
activity_main.xml file.

Key Components of XML Layout:

● LinearLayout: Organises UI elements vertically or horizontally.


● TextView: Displays static text, such as "Hello World," which is set as the
default text when creating a new project.
● Button: This can be added to trigger actions, such as navigating to a new
screen or displaying a message.

Example XML code

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World" />
</LinearLayout>

Explanation of the MainActivity Class

● The MainActivity class serves as the entry point of the application.


● Package Definition: Sets the package name, e.g.,
com.example.firstapplicationdev.

● Imports:

o Uses AppCompatActivity for backwards-compatible features.


o Uses Bundle to handle the saved instance state of the activity.

● Class Structure:

o MainActivity inherits from AppCompatActivity.


o onCreate() Method: This method initialises the activity and sets the
layout file using setContentView(R.layout.activity_main).

Example Kotlin code

package com.example.firstapplicationdev

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
Final Output in the Emulator

● After running the project, the app launches in the Android emulator or a
connected device.
● Expected Output: A simple interface displaying "Hello World" as defined in
the XML layout.
● Verifying the Output: Ensure that the app runs smoothly without errors, and
the UI appears as expected in the emulator.
Topic 6: Running the Application on Emulator
Need for an Emulator and Its Role in Testing Android Applications

● An Android emulator provides a virtual environment that mimics an actual


Android device, allowing developers to test their applications without needing
physical hardware.

● Key Benefits of Using an Emulator:

o Virtual Environment: Emulators replicate the behaviour and


characteristics of real devices, offering a convenient way to test
applications.
o Cost-Effective: Emulators eliminate the need for purchasing multiple
physical devices for testing, making the development process more
economical.
o Efficient Debugging: Emulators provide tools like Logcat, screen
capture, and device simulation (e.g., battery levels, network speed),
helping developers identify and fix issues quickly.

Steps to Set Up a New Virtual Device (AVD) Using the Device Manager in
Android Studio

Setting up an Android Virtual Device (AVD) allows developers to test apps on


different Android versions, screen sizes, and hardware configurations.

Step 1: Open Device Manager

● In Android Studio, go to the "Tools" menu and select "Device Manager."


● This will open the Device Manager window, where you can create, manage,
and launch AVDs.

Step 2: Create a New Virtual Device

● Click the "Create Device" button to start setting up a new virtual device.
● Choose a device model from the list of available options, including various
phone models, tablets, and other Android devices with different screen sizes
and resolutions.
● After selecting the device model, click "Next."

Step 3: Select a System Image

● You will be prompted to choose a system image, determining the version of


Android the virtual device will run.
● Select an Android version from the list; if the desired system image isn’t
downloaded, you can download it directly from this window.
● Click "Next" after selecting the system image.
● Additional Details:

o API Level: Defines the Android version.


o ABI (Application Binary Interface): Specifies the processor
architecture.
o Target: Indicates the overall Android version and additional features
(e.g., Google Play) the virtual device will use.

Step 4: Configure the Device

● Configure the hardware specifications of your virtual device, such as RAM,


internal storage, and other settings.
● Optionally, name your AVD for easy identification.
● Click "Finish" to complete the setup.

Step 5: Launch the Emulator

● Once the AVD is created, it will appear in the list of devices in the Device
Manager.
● To start the emulator, click the "Play" (green triangle) button next to the virtual
device in the list.
● The emulator will launch, displaying a virtual Android device on your screen,
allowing you to test your app.
MODULE NAME: Debugging and user
interface
Lesson 2: Debugging and Views in Android
Topic: Debugging Overview
Set a Breakpoint

● In Android development, a breakpoint is a marker that pauses the execution of


code at a specific line, allowing developers to inspect the current state of the
app.
● To set a breakpoint, open the MainActivity.kt file in Android Studio. Click in
the left margin next to the line you want to pause, such as
setContentView(R.layout.activity_main). This action places a red dot,
indicating that the breakpoint is active.
● Breakpoints help in diagnosing issues, as they allow you to observe the
behaviour of the app in real time, inspect variables, and understand the flow of
execution at critical points. This process is especially useful when dealing with
unexpected errors or logic flaws.

Start Debugging

● Once the breakpoint is set, you can begin the debugging process. Go to the
"Run" menu in Android Studio and select "Debug."
● Running the app in debug mode will start it as usual, but it will pause
execution at the set breakpoint. This enables you to check how variables
change over time, verify logic, and monitor interactions within the app.
● During debugging, you can step through the code line by line to identify where
unexpected behaviour starts. This helps in isolating the cause of errors and
verifying fixes before implementing them across the codebase.

Inspect the Application State

● When a breakpoint is hit, the Debugger window opens at the bottom of


Android Studio. This window displays detailed information about the current
state of the application, including variables, memory allocation, and the call
stack (which shows the sequence of method calls leading up to the
breakpoint).
● You can hover over variables to view their current values or add them to the
"Watches" section for continuous monitoring. This allows for a clearer
understanding of how data is changing as the app runs.
● This inspection helps in checking whether the app is handling data correctly
and can be used to verify conditions and loops, especially in more complex
functions.
Step Over, Step Into, and Step Out

● These debugging commands allow you to navigate through the code while
paused at a breakpoint:
o Step Over (F8): Executes the current line of code without diving into
any methods called by it, making it useful when you want to bypass
functions and continue to the next line.
o Step Into (F7): Moves into a method call, allowing you to examine its
internal execution line by line. This is ideal when you need to
understand the inner workings of a custom function.
o Step Out (Shift+F8): Exits the current method and returns to the caller
method, useful when you are done inspecting the inner method and
want to continue debugging the outer code.
● Understanding these commands helps in analysing the code flow and verifying
the correct execution of methods.

View Logcat Output

● Logcat is a built-in tool in Android Studio that displays logs generated by the
app, system, and debugging commands.
● It allows you to filter logs to show messages related to your app, making it
easier to locate specific errors or warnings. Logs include error messages, stack
traces, and custom log messages defined in the code using Log.d(), Log.i(), or
Log.e().
● Analysing Logcat output is essential for diagnosing issues that may not trigger
breakpoints, such as background processes, network requests, or exceptions
that occur outside the visible execution flow.
● Using Logcat effectively helps identify bugs, analyse app behaviour, and
verify that data handling and network communications are working as
expected.

Resume Execution

● Once you have finished inspecting the application state and variables, you can
resume execution by pressing F9 or selecting the "Resume Program" button.
This continues running the app until the next breakpoint or the end of
execution.
● This command is helpful when you want to test the app’s behaviour beyond
the current breakpoint or after making small code changes during debugging.
● Properly understanding how to resume and control execution flow is key to
efficient debugging, as it allows developers to focus on relevant code sections
and avoid repeatedly starting and stopping the app.
Topic: Version Control Integration
Introduction to Version Control

What is Version Control?

Version Control Systems (VCS) are tools that help track changes in the
codebase over time, allowing developers to manage project history,
collaborate effectively, and revert to previous versions when necessary.
Common VCS include Git, SVN (Subversion), and Mercurial, with Git
being the most widely used in modern development.

Why Use Version Control?

Track Changes: Easily monitor who made changes, what was changed,
and when.
Collaboration: Multiple developers can work on the same project
simultaneously without overwriting each other's work.
Backup and Recovery: Version control provides a backup of the codebase
and allows reverting to earlier versions if something goes wrong.

Version Control in Android Studio

Built-in Support:

Android Studio comes with built-in support for Git, the most popular
version control system. It allows developers to perform Git operations
directly within the IDE without needing to use the command line.

Key Features:

Commit and Push: Save your changes locally and upload them to a
remote repository like GitHub.
Branching and Merging: Work on different features in separate branches
and merge them into the main codebase when ready.
View History: Inspect the history of changes to understand the evolution
of the project.

Basic Workflow in Android Studio

1. Initialise or Clone a Repository:


Start by either initialising a new Git repository for your project or cloning
an existing one from a platform like GitHub.

2. Make Changes:
As you develop your app, make changes to your code. Android Studio will
track these changes and mark files as modified.

3. Commit Changes:
After reviewing your changes, commit them with a meaningful message
describing what was done. This saves the changes to your local repository.

4. Push to Remote:
Push your commits to a remote repository so that your code is backed up
and accessible to collaborators.

5. Pull and Merge:


Pull the latest changes from the remote repository and resolve any
conflicts if multiple developers have made changes to the same files.
Topic: Overview of Views in Android
View - Introduction

● Concept of Views:

o A 'View' in Android represents the fundamental building block of the


User Interface (UI). It refers to the android.view.View class, which
serves as the superclass for all UI components such as TextView,
ImageView, Button, etc.
o Every view can be visualised as a rectangle on the screen that displays
some type of content. Although this rectangle is invisible, it determines
the space occupied by the view on the screen.

● Essential Attributes:

o android:layout_height and android:layout_width are mandatory


attributes that define the height and width of the view. They determine
the size of the rectangular space occupied by the view.
o Other commonly used attributes include:
▪ gravity and layout_gravity: These attributes determine the
alignment of content within the view and the view's alignment
within its parent container, respectively.
▪ padding: It adds space inside the view, creating a buffer
between the content and the view's boundary.
▪ margin: Adds space outside the view, separating it from
adjacent views.

● Understanding the Basics:

o Grasping the concept of views is crucial for creating intuitive and


functional user interfaces, as all Android UI components are built upon
the View class. Views are responsible for rendering everything from
text to images and user interactions.

XML Syntax for Creating a View

● Defining Views in XML:

o In Android, views are often defined using XML, which is a markup


language that specifies the layout and attributes of the views.
o For example, a basic TextView in XML might look like this:

<TextView
android:id="@+id/sampleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="18sp"
android:padding="8dp" />
o This syntax includes defining essential attributes like id, layout_width,
layout_height, and additional attributes like text, textSize, and padding.

● Benefits of XML Layouts:

o XML provides a clear, hierarchical structure for defining UI


components, making it easier to visualise the layout structure.
o It separates the UI design from the code, allowing designers and
developers to work independently on the interface and functionality.

● Key Considerations:

o XML layouts support rapid UI changes and testing, making them a


popular choice for defining views in Android development.
Understanding XML syntax is foundational for effective UI design in
Android.

Most Commonly Used Android View Classes

● List of Common View Classes:

o Android offers various view classes that serve different UI purposes,


including:

▪ TextView: Displays non-editable text.


▪ EditText: Allows user input.
▪ Button: Triggers an action when clicked.
▪ ImageView: Displays images.
▪ ImageButton: A button with an image.
▪ CheckBox: A checkable box for user selection.
▪ RadioButton: Allows selection from a group of options.
▪ ListView: Displays a scrollable list of items.
▪ GridView: Shows items in a grid format.
▪ ScrollView: Enables scrolling through a long list of items.
▪ DatePicker and Spinner: Allow users to select dates or
choose from a list of options.

● Understanding View Classes:

o Each of these classes extends the View class, inheriting common


properties while adding specific attributes or methods that suit their
intended functionality.
o For instance, TextView has attributes like textSize and textColor, while
EditText includes additional attributes like hint and inputType.
Topic: Text view and Edit text in Android
Introduction to TextView

● Overview:

o TextView is a user interface element used to display text to the user. It


is non-editable and is typically used for static text like labels,
instructions, or messages in an Android application.
o It acts as a basic building block for displaying static information and is
highly customisable to match the design of the app.

● Common Properties:

o text: Sets the actual text content displayed in the TextView.


o textSize: Sets the size of the displayed text (measured in 'sp' units to
support scaling).
o textColor: Changes the colour of the text, specified using hexadecimal
or predefined colour resources.
o gravity: Aligns the text within the TextView, such as center, left, or
right.
o maxLines: Limits the number of lines displayed; useful for restricting
text display in a compact layout.

● Example XML Layout:

o A basic TextView in XML:

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="18sp"
android:textColor="#000000"
android:padding="8dp" />

Creating a TextView in Java/Kotlin Code:

o In the activity's Kotlin code, you can reference a TextView and set its
text as follows: kotlin

val textView = findViewById<TextView>(R.id.textView)


textView.text = "Hello, Android!"

o This shows how to access and modify the TextView dynamically,


which is useful for changing content based on user interaction or other
events.
Introduction to EditText

● Overview:

o EditText is an input field in Android that allows users to enter and


modify text. It is used for collecting input, such as usernames,
passwords, or any other textual data.
o Unlike TextView, it is editable and provides a way for users to interact
directly with the UI by entering information.

● Common Properties:

o hint: Displays a hint text inside the input box, which disappears once
the user starts typing.
o inputType: Specifies the type of input expected, such as text, number,
password, or email.
o textColor: Sets the colour of the entered text.
o textSize: Sets the size of the text entered by the user.
o maxLength: Limits the maximum number of characters that can be
entered.

● Example XML Layout:

o A basic EditText in XML:

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:inputType="text"
android:maxLength="20"
android:padding="8dp" />

Creating an EditText in Java/Kotlin Code:

o In the activity's Kotlin code, you can access the EditText and retrieve
the input text:Kotlin

val editText = findViewById<EditText>(R.id.editText)


val inputText = editText.text.toString()

o This code demonstrates how to capture user input from the EditText
field, which is essential for processing form data or handling login
details.
Topic: Buttons in Android

Complete code

XML code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_centerInParent="true"/>
</RelativeLayout>

Mainactivity.kt
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_centerInParent="true"/>
</RelativeLayout>

Setting Up the Button in Android

● Initialising the Button:


o In Android, a Button is a UI component that triggers an action when
clicked.
o To set up a button, first define it in the XML layout file and then
reference it in the Kotlin code using findViewById.
o Example of finding the button reference in Kotlin:

val button = findViewById<Button>(R.id.button)

o Here, R.id.button refers to the ID of the button defined in the XML


layout, enabling interaction with the button in Kotlin

Defining the Button Layout in XML

● XML Code for Button Layout:

o Buttons are defined using the <Button> tag in the XML layout file.
Essential attributes include:

▪ android:id: Assigns a unique ID to the button, used for


referencing in the code.
▪ android:layout_width and android:layout_height: Define the
button's dimensions.
▪ android:text: Sets the text displayed on the button.
▪ android:layout_centerInParent: Centers the button within its
parent layout.

o Example XML code for a button:

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_centerInParent="true" />

o The wrap_content value for width and height makes the button size
adjust to the text it contains while centering it in the parent layout
provides a clean and centered design.

Adding Interactivity with OnClickListener

● Setting an OnClickListener:

o To make the button interactive, set an OnClickListener in the Kotlin


code. This listener defines the action that will occur when the button is
clicked.
o Example of setting an OnClickListener: kotlin

button.setOnClickListener {
// Show a simple toast message when the button is clicked
Toast.makeText(this, "Button Clicked!",
Toast.LENGTH_SHORT).show()
}

o In this example, a toast message saying "Button Clicked!" is displayed


when the button is pressed.
o The Toast.makeText() function creates a short pop-up message, and the
show() method displays it on the screen.
Topic: Scroll view in Android
A ScrollView is used in Android to allow users to scroll through a list of items that
exceed the screen's height.
It’s commonly used when you have a lot of content that doesn’t fit on the screen.

XML code
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

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

<!-- 30 TextView items to enable scrolling -->


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 1"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 2"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 3"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 4"
android:textSize="18sp"
android:padding="8dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 5"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 6"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 7"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 8"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 9"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 10"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 11"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 12"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 13"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 14"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 15"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 16"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 17"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 18"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 19"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 20"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 21"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 22"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 23"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 24"
android:textSize="18sp"
android:padding="8dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 25"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 26"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 27"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 28"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 29"
android:textSize="18sp"
android:padding="8dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 30"
android:textSize="18sp"
android:padding="8dp" />

</LinearLayout>
</ScrollView>

Mainactivity.kt
package com.example.buttondemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ScrollView

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Reference the ScrollView by its ID


val scrollView = findViewById<ScrollView>(R.id.scrollView)

// Scroll to the bottom to check if scrolling is working


scrollView.post {
scrollView.fullScroll(ScrollView.FOCUS_DOWN)
}
}
}

Setting Up ScrollView in XML

● Overview of ScrollView:

o ScrollView is used in Android to enable scrolling through content that


exceeds the visible screen height. It allows users to access all items,
even if they don’t fit on the screen at once.
o It is commonly used when displaying long lists, forms, or any layout
containing more elements than can be shown at once.

● Structure of ScrollView:

o A ScrollView must wrap another layout (e.g., LinearLayout), which


contains the items to be scrolled. It supports vertical scrolling by
default.

● XML Code for ScrollView:

o Here’s an example of a basic ScrollView setup:

<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

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

<!-- Multiple TextView elements for scrollable content -->


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 1" />

<!-- Additional items continue... -->


</LinearLayout>
</ScrollView>

o In this example, the ScrollView wraps a vertically oriented


LinearLayout containing multiple TextView elements, allowing the
user to scroll vertically through the items.

Implementing ScrollView in Kotlin

● Referencing the ScrollView:

o To implement the ScrollView in Kotlin, reference it in the


MainActivity using findViewById.
o Example of accessing the ScrollView in Kotlin:
val scrollView = findViewById<ScrollView>(R.id.scrollView)

● Scrolling Programmatically:

o You can programmatically scroll to the bottom of the content using the
following code: kotlin

scrollView.post {
scrollView.fullScroll(ScrollView.FOCUS_DOWN)
}

o This code snippet ensures that the ScrollView scrolls to the bottom of
the content, useful for testing or automatically displaying the latest
items when new content is added.

Emulator ScrollView Output

● Testing in Emulator:

o When running the app on an emulator or device, swipe up and down to


test the scrolling functionality. Even if the scrollbar is not visible, the
content should be scrollable.
o The ScrollView is often used in forms, lists, and long articles, making
it a vital component for creating a user-friendly interface.​
MODULE NAME: Building Layouts with XML

LESSON 1: Building Layouts with XML


Overview of Android UI Components

Introduction to Android UI Components

● What are UI Components?


o Android UI components are the building blocks that create an
interactive user interface in Android applications.
o These components range from basic elements like TextView, EditText,
and ImageView to more complex layouts like LinearLayout,
RelativeLayout, and ConstraintLayout.
o The primary goal of UI components is to facilitate user interaction with
the app, allowing users to view, enter, or modify information.

Common Android UI Components

● Basic UI Components:
o TextView: Displays static text that users cannot edit.
o EditText: Allows users to input and modify text, making it suitable for
forms or user input fields.
o Button: A clickable element that triggers an action when pressed.
o ImageView: Displays images and icons within the app.
● Examples of Interactions:
o UI components like CheckBox, RadioButton, SeekBar, and Switch
allow users to select options, adjust values, and toggle states,
enhancing interactivity in the app.

Layouts in Android

● LinearLayout:
o Aligns child views in a single direction, either vertically or
horizontally.
o Key properties:
▪ orientation: Defines whether the alignment is vertical or
horizontal.
▪ gravity: Adjusts the content alignment within the layout.
▪ weight: Distributes space among child views proportionally.
● RelativeLayout:
o Positions child views relative to each other or the parent container.
o Key properties:
▪ layout_alignParentTop: Aligns the view to the top of the parent.
▪ layout_centerInParent: Centers the view within the parent.
▪ layout_below: Places a view below another specified view.
● ConstraintLayout:
o Offers more flexibility and efficiency for creating complex UIs.
o Key properties:
▪ constraintTop_toTopOf: Aligns the top of one view to another.
▪ constraintBottom_toBottomOf: Aligns the bottom of one view
to another.
▪ layout_constraintHorizontal_bias: Adjusts the horizontal
alignment within the layout.

Advanced UI Components

● RecyclerView:
o Used to display a large set of data efficiently by recycling views that
are no longer visible.
o It supports list and grid structures, making it ideal for handling
dynamic content.
● CardView:
o Provides a container with rounded corners and shadow effects, offering
a card-like layout for presenting information in a structured format.
● Toolbar:
o A flexible, customisable view that replaces the traditional ActionBar,
allowing more features like menus, navigation icons, and custom titles.
o It supports background customisation, custom views, and menu
integration, making it a key part of advanced UI design.

User Interaction Components

● CheckBox:
o Allows users to select multiple options from a set, with properties like
text and checked indicating the label and selection state.
● RadioButton:
o Used for single-option selection, often grouped within a RadioGroup to
ensure only one option is selectable at a time.
● SeekBar:
o A slider that lets users select a value within a defined range.
o Properties include max for setting the maximum value and progress for
indicating the current value.
● Switch:
o Represents a toggle between on and off states, with properties like
textOn, textOff, and checked to define its behaviour.

Customising UI Components

● Customisation Techniques:
o UI components can be styled using attributes like colour, size, padding,
and margins to enhance their appearance and interactivity.
o XML styles and themes can be applied to achieve a consistent design
across the app.
o Developers can extend existing components to create custom
behaviour and layouts.
Using XML to Define Layouts

Introduction to XML Layouts in Android

● Overview:
o XML (Extensible Markup Language) is a widely used tool in Android
for designing user interfaces.
o It provides a structured and clear way to define the layout and
properties of UI components.
o XML layouts separate the user interface design from the application
logic, ensuring better maintainability and clarity.

Structure of an XML Layout File

● Root Element:
o The root element serves as the base container in an XML layout file
and is typically a ViewGroup like:
▪ LinearLayout: Aligns children in either vertical or horizontal
direction.
▪ RelativeLayout: Positions children relative to each other or the
parent.
▪ ConstraintLayout: Allows flexible positioning of views.
● View Elements:
o These are the child elements within the root, representing UI
components such as TextView, Button, ImageView, etc.
o Attributes:
▪ Each view element has multiple attributes that define its
properties, such as:
▪ Size: layout_width, layout_height.
▪ Colour: background, textColor.
▪ Alignment: gravity, layout_gravity.

Commonly Used Layouts

● LinearLayout:
o Aligns child views in a vertical or horizontal sequence.
o Attributes include orientation, gravity, and weight to control layout
behaviour.
● RelativeLayout:
o Positions child views relative to other views or the parent container.
o Common attributes are layout_alignParentTop, layout_centerInParent,
and layout_below.
o It provides more flexible positioning compared to LinearLayout.

Advanced Layouts

● ConstraintLayout:
oA flexible layout that allows complex positioning of views.
oIt reduces the need for nested layouts, improving the app’s
performance.
o Key attributes include:
▪ constraintStart_toStartOf and constraintEnd_toEndOf: Define
positioning relative to other views or parent edges.
▪ layout_constraintHorizontal_bias: Adjusts horizontal
alignment, providing more precise positioning.
● FrameLayout:
o Designed to hold a single child view but can be used for stacking
views on top of each other.
o It is commonly used for displaying a single item or overlaying multiple
views.

Best Practices for XML Layouts

● Efficient Design:
o Use a flat hierarchy by minimising nested layouts to improve
performance.
o Prefer using ConstraintLayout over deeply nested layouts for more
complex UI designs.
● Consistency:
o Define styles and themes in XML to ensure a consistent look across the
app.
o Use styles defined in styles.xml for reusability and better
maintainability.
● Resource Management:
o Store frequently used values like colours, dimensions, and strings in
resource files (colors.xml, dimens.xml, etc.).
o This approach makes it easier to update and manage design changes.

Linear Layout

Types of Linear Layout Orientation

● Overview:
o LinearLayout is a basic Android layout that aligns child views in a
single direction—either vertically or horizontally.
o There are two types of orientation:
▪ Vertical Linear Layout: Arranges children vertically in a line,
one after another.
▪ Horizontal Linear Layout: Arranges children horizontally in a
line, one after another.

Main Attributes in Linear Layout

● Orientation:
o The android:orientation attribute specifies the direction of alignment. It
can take two values:
▪ Vertical: Aligns children vertically.
▪ Horizontal: Aligns children horizontally.
● Gravity:
o Controls the alignment of the layout within the parent container.
Common values include start, end, left, right, centre, top, and bottom.
● layout_weight:
o Specifies the relative importance of each child view within the
LinearLayout.
o Distributes extra space among children based on the weight value. For
example, if two buttons have weights of 1 and 2, the second button will
take up twice as much space as the first.
● weightSum:
o Represents the total sum of the weights of child views. It ensures that
all child views are proportionally sized according to their weights.
o Setting weightSum is necessary when defining weights for children to
achieve consistent layout behaviour.

Relative Layout

Introduction to RelativeLayout

● Overview:
o RelativeLayout is a flexible Android layout that positions child views
relative to one another or the parent container.
o It allows for complex UI designs, making it useful for dynamic
interfaces.

Key Properties of RelativeLayout

● Aligning with Parent:


o Attributes that align child views with the parent include:
▪ layout_alignParentTop: Aligns the view to the top of the
parent.
▪ layout_alignParentBottom: Aligns the view to the bottom of
the parent.
▪ layout_alignParentLeft or layout_alignParentStart: Aligns
the view to the left/start of the parent.
▪ layout_alignParentRight or layout_alignParentEnd: Aligns
the view to the right/end of the parent.
● Centering Views:
o Attributes that centre views within the parent include:
▪ layout_centerInParent: Centers the view within the parent.
▪ layout_centerHorizontal: Centers the view horizontally.
▪ layout_centerVertical: Centers the view vertically.
● Positioning Relative to Sibling Views:
o Aligns views relative to other child views:
▪ layout_below: Positions a view below another view.
▪ layout_above: Positions a view above another view.
▪ layout_toLeftOf or layout_toStartOf: Positions a view to the
left/start of another view.
▪ layout_toRightOf or layout_toEndOf: Positions a view to the
right/end of another view.

Overlapping Views

● Creating Overlaps:
o RelativeLayout allows overlapping views by positioning them in the
same space or using properties like layout_alignTop.
o This feature is useful for designing complex UIs that require elements
to overlap or stack on top of each other.
MODULE NAME: Building Layouts with XML

LESSON 2: Activities and Intents in Android


Introduction to Activities

What is an Activity?

● Definition:
o An Activity is a core component of an Android application,
representing a single screen with a user interface (UI).
o It acts as the entry point for user interactions and manages the app's UI.
o Each activity is associated with a window where the UI components
are drawn, allowing users to interact with the application.

Role of Activities

● Primary Building Blocks:


o Activities serve as the fundamental building blocks of an Android app.
o Users interact with different activities to perform various tasks within
the app.
o Examples include:
▪ MainActivity: Represents the home screen of the app.
▪ SettingsActivity: Handles settings and configurations.
▪ DetailActivity: Displays detailed views of content.
o An application typically consists of multiple activities that are loosely
connected.
o Usually, one activity is defined as the “main” activity, which is
presented to the user when the app is launched for the first time.
o Each activity can start another activity to perform different tasks,
making navigation seamless within the app.

Activity Stack

● How Activities are Managed:


o The Android system manages activities using an Activity Stack.
o When a new activity starts, the previous activity is paused, but it is
preserved in the stack.
o The new activity is pushed onto the top of the stack and becomes the
currently running activity.
o The previous activity remains below it in the stack and will not come
to the foreground until the new activity exits.
o This stack-based management ensures efficient navigation and
resource management within the app.

Types of Activities
● Activity Templates in Android Studio:
o When creating a new project in Android Studio, developers can choose
from several activity templates, each serving a different purpose.
● Different Types of Activities:
o No Activity: An empty project template with no activity.
o Empty Activity: Provides a basic structure with a single empty screen.
o Gemini API Starter: Offers a starting template for API-based
applications.
o Basic Views Activity: Includes basic view components for a
straightforward UI.
o Bottom Navigation Activity: Provides bottom navigation for easy
switching between sections.
o Empty Views Activity: Contains basic view components without
predefined content.
o Navigation Drawer Views Activity: Adds a navigation drawer for
quick access to different sections.
o Responsive Views Activity: Ensures a responsive layout across
different screen sizes.
o Game Activity (C++): Offers a template for game development using
C++.
o Native C++ Activity: Designed for projects with native C++ code
integration.

Creating an Activity

Introduction to Creating an Activity

● Overview:
o An Activity is a fundamental component in Android that represents a
single screen with a user interface.
o It serves as the entry point for user interactions with the application.
o When a new project is created in Android Studio, a Main Activity is
automatically generated, consisting of two main files:
▪ activity_main.xml: Defines the UI layout of the main activity.
▪ MainActivity.kt / MainActivity.java: Contains the logic for
the main activity.
o Purpose of Creating an Activity:
▪ Activities display content to users and handle user interactions.
▪ Multiple activities are used to build a complete user experience
within an app, allowing navigation between screens and
managing various tasks.

Steps to Create a New Activity

● Step 1: Create a New Activity File


o In Android Studio, right-click on the app folder and select:
▪ New > Activity > Empty Activity or Basic Activity.
o Enter a name for the new activity (e.g., SecondActivity) and click
Finish.
o This creates the new activity files and adds them to the project
structure.

● Step 2: Define the Layout XML


o An XML file associated with the activity is created (e.g.,
activity_second.xml).
o This file defines the UI components and layout for the new activity.

● Step 3: Modify the Java/Kotlin Code


o Open the SecondActivity.java or SecondActivity.kt file.
o The basic code structure for the new activity is automatically
generated.
o You can add custom logic, event handling, and interactions within this
file to make the activity functional.

Declaring the Activity in AndroidManifest.xml

● Register the Activity:


o Every activity must be declared in the AndroidManifest.xml file to be
recognised by the Android system.
o The declaration ensures that the activity can be accessed within the
app.
● Specifying the Launcher Activity:
o The activity that acts as the entry point for the app should have an
intent filter:

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Introduction to Intent

Introduction to Intents

● Overview:
o All Android activities are started or activated using an Intent.
o An Intent is a messaging object used to request an action from another
app component.
o It facilitates communication between components such as:
▪ Activities
▪ Services
▪ Broadcast receivers
▪ Content providers
o Intents act as a bridge between different components, enabling
interaction within the same app or between different apps.
Roles of Intents

● Main Uses of Intents:


o Starting an Activity:
▪ An activity represents a screen where users interact with the
app.
▪ Intents are used to start new activities within the app by calling
the startActivity() method with an Intent object.
o Starting a Service:
▪ A service runs in the background without a user interface.
▪ Intents can be used to start a service by passing the Intent
object to the startService() method.
o Delivering a Broadcast:
▪ Broadcasts notify users about specific tasks or events, such as a
low battery warning.
▪ Intents can send broadcasts to the device by passing the Intent
object to the sendBroadcast() method.

Intent Structure

● Primary Components of an Intent:


o Action: Defines the action to be performed, such as ACTION_VIEW,
ACTION_EDIT, ACTION_MAIN, etc.
o Data: Refers to the data to be operated on, typically represented as a
URI (Uniform Resource Identifier).
o Examples of Action/Data Pairs:
▪ View a web page: ACTION_VIEW with a URI of a web
address.
▪ Call a phone number: ACTION_DIAL with a URI containing
the phone number.
● Secondary Components of an Intent:
o Category: Provides additional information about the action to be
executed.
o Type: Specifies the MIME type of the data.
o Component: Specifies the name of a specific component class to use.
o Extras: A bundle of additional information, used to pass extra data to
the component.

Types of Intents

● Explicit Intents:
o Used to communicate between two activities within the same
application.
o They specifically define the component to be started, such as
transitioning from MainActivity to SecondActivity.
● Implicit Intents:
o Used for communication between components, without specifying a
particular component.
o They rely on the Android system to find a component that can handle
the requested action.
o Example: Showing a location on a map using an implicit intent,
without defining the map app explicitly.

Implicit intents

Introduction to Implicit Intents

● Definition:
o An Implicit Intent allows Android to determine which app component
(activity, service, etc.) is best suited to handle a requested action.
o Unlike explicit intents, which specify a particular component by name,
implicit intents rely on the Android system to match the intent’s action,
data, and category with available components.
o Example Use Cases:
▪ Opening a web page: You want to open a web browser but
don’t specify which browser.
▪ Sending an email: You want to send an email but leave it up to
the system to choose the appropriate email app.
▪ Viewing a location on a map: Users can select any installed
map app to view the location.
▪ Sharing content: Enables sharing of text, images, or files with
any compatible app, allowing users to pick their preferred app
(e.g., WhatsApp, Gmail, etc.).

Basic Structure of an Implicit Intent

● How to Create an Implicit Intent:


o An implicit intent is created by defining the action and, optionally, the
data to be acted upon.
o Action: The general action to be performed, such as viewing, editing,
or sending data.
o Data: The data needed to complete the action, is represented as a URI
(e.g., a web URL or a phone number).
● Common Actions:
o Intent.ACTION_VIEW: Typically used to view something. This
could be a URL in a browser, a contact’s details, or a photo in the
gallery.
o Intent.ACTION_SEND: Used for sharing content (e.g., sending text,
images, or other files to another app).
o Intent.ACTION_DIAL: Opens the phone dialer with a specified
number, allowing the user to manually place a call.
o Intent.ACTION_SENDTO: Sends data to a specific recipient (e.g.,
initiating an email or SMS with the recipient pre-defined).
● Additional Attributes:
o Category: Provides extra information about the action.
o Type: Specifies the MIME type of the data, ensuring the receiving
component knows how to handle the data.
o Component: Allows specifying a particular app component if needed,
although this is rare for implicit intents.
o Extras: Bundle of additional data passed along with the intent,
enabling more context to be delivered (e.g., email subject, SMS text).

Example 1: Opening a Web Page

o Action: Sets the action to Intent.ACTION_VIEW, which signals to the


Android system that the intent should view the given data.
o Data: Converts the string URL into a URI object using Uri.parse(),
making it compatible with the intent.
o Starting the Activity:
▪ The startActivity() method is called, prompting Android to
check which apps can handle this view action. The user is then
presented with a chooser to select the browser or app to open
the web page.
o Benefits:
▪ This approach provides flexibility, allowing users to pick any
installed browser to open the web page.
▪ It also helps in maintaining compatibility across devices and
apps.

Example 2: Sending an Email

o Action: Uses Intent.ACTION_SENDTO, specifically designed for


sending data to a recipient. It ensures that only email apps handle the
intent.
o Data Handling:
▪ The Uri.parse("mailto:") sets the scheme to "mailto:",
indicating that only email apps can respond to this intent.
o Adding Extras:
▪ putExtra() is used to add additional data to the email intent,
such as the recipient’s email address, subject, and body text.
o Starting the Activity:
▪ When the user executes this intent, they are presented with a
list of email apps to complete the action.
o Benefits:
▪ This approach provides a seamless experience by allowing
users to select their preferred email app.
▪ It is effective for pre-filling email fields, saving user input time
and enhancing the overall interaction.

Intent Filters

Introduction to Intent Filters in Android

● What is an Intent Filter?


o An Intent Filter is a declaration in the AndroidManifest.xml file that
specifies the types of intents an activity, service, or broadcast receiver
can respond to.
o
It allows the Android system to determine which components can
handle a particular intent, especially useful with implicit intents.
● Purpose of Intent Filters:
o Enables your app to handle specific actions or data types from other
apps or the system.
o Defines which activities can be started with implicit intents, helping
manage app behaviour more effectively.

Structure of an Intent Filter

● Components of an Intent Filter:


o <action>: Specifies the general action to be performed (e.g., view,
edit, send).
o <category>: Provides additional information about the type of
component that should handle the intent.
o <data>: Defines the type of data the component can handle (e.g.,
MIME types, URI schemes).

Example Structure in AndroidManifest.xml


<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" android:host="www.example.com" />
</intent-filter>

Actions in Intent Filters

● Common Actions:
o android.intent.action.VIEW: Used to view a piece of data, such as a
web page or contact.
o android.intent.action.EDIT: Used to edit a piece of data.
o android.intent.action.SEND: Used to send data to another app, such
as sharing content.
o android.intent.action.MAIN: Marks the main entry point of the app,
used in launcher activities.

Categories in Intent Filters

● Common Categories:
o android.intent.category.DEFAULT: Must be included in filters for
activities that can be launched with implicit intents.
o android.intent.category.LAUNCHER: Specifies that the activity
should appear in the app launcher.
o android.intent.category.BROWSABLE: Allows an activity to be
launched from a web browser.
o android.intent.category.ALTERNATIVE: Provides alternative
actions the user can take in the app.

Data in Intent Filters


● Data Matching Attributes:
o android:scheme: Defines the URI scheme, such as http, https, or tel.
o android:host: Specifies the host in the URI, such as
"www.example.com".
o android:path: Matches a specific path in the URI.
o android:mimeType: Defines the type of data the component can
handle, such as image/* or text/plain.

Starting an Activity with explicit intent

Introduction to Explicit Intents

● What is an Explicit Intent?


o An Explicit Intent is used to start a specific activity or service within
the same application or between known applications.
o The target component is directly specified in the intent, making it
suitable for navigation between activities within the same app.
● When to Use Explicit Intents?
o Navigating between activities: Used to switch screens within the
same app (e.g., navigating from MainActivity to SecondActivity).
o Starting a service within the app: Used to initiate services for
background processing.
o Communicating with a specific component in another app:
Applicable when you have control over the external component.

Creating an Explicit Intent

● Basic Code Structure:


o To create an explicit intent, specify the target activity within the intent

val intent = Intent(this, SecondActivity::class.java)


startActivity(intent)

o Explanation:
▪ Intent(this, SecondActivity::class.java): Defines an intent
that starts SecondActivity from the current context (this).
▪ startActivity(intent): Initiates the SecondActivity,
transitioning from the current activity to the target activity.

Passing Data with Explicit Intents

● Adding Extra Data:


o You can pass additional data to the target activity using the putExtra()
method. This method allows sending key-value pairs that the target
activity can access.
Example:

intent.putExtra("EXTRA_KEY", "Some data")


o In this example, the key "EXTRA_KEY" is associated with the string
"Some data," which can be retrieved in the target activity.

Receiving Data in the Target Activity

● Retrieving Passed Data:


o The target activity can access the data passed via the intent using the
getIntent() method.
Example:

val data = intent.getStringExtra("EXTRA_KEY")

o This code retrieves the string data associated with "EXTRA_KEY"


from the intent, making it available in the target activity.

Example: Navigating Between Activities

● Scenario:
o An app has two activities: MainActivity and SecondActivity.
o The goal is to navigate from MainActivity to SecondActivity when a
button is clicked.
o Implementation:
▪ In MainActivity, create an explicit intent that specifies
SecondActivity as the target

val intent = Intent(this, SecondActivity::class.java)


startActivity(intent)

Add a button in MainActivity with an OnClickListener that triggers this intent.


In SecondActivity, retrieve any passed data using getStringExtra() to
customise the displayed content based on the data received.

Activity Navigation

Introduction to Activity Navigation

● What is Activity Navigation?


o Activity navigation in Android allows users to move from one screen
to another, enabling interactions across different activities within an
app.
o Types of Navigation:
▪ Linear Navigation: Forward and backward movement
between activities, following a sequence.
▪ Non-linear Navigation: Jumping between activities based on
user actions, such as button clicks.

● Why Activity Navigation is Important:


o Enhances user experience by managing the flow of tasks in a
structured manner.
o Helps maintain a seamless and efficient interface across different app
screens.

Basic Navigation Using Intents

● Navigating to Another Activity:


o Use explicit intents to start a specific activity from the current activity.
o Example Code
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)

● In this example, the Intent specifies that the target is SecondActivity, and
calling startActivity(intent) triggers the transition.

Passing Data During Navigation:

● You can pass data to the target activity using the putExtra() method
intent.putExtra("EXTRA_KEY", "Sample Data")
startActivity(intent)

● Here, "Sample Data" is associated with the key "EXTRA_KEY" and is sent to
the target activity.

Retrieving Data in the Target Activity:

The target activity retrieves the passed data using getIntent():

val data = intent.getStringExtra("EXTRA_KEY")

This data can be used to customise the UI or functionality based on the information
received from the previous activity.

Navigation with Back Stack Management

● Understanding the Back Stack:


o The Android system manages activities using a stack-based structure
called the Back Stack.
o Each time a new activity starts, it is pushed onto the stack. The
previous activity remains below and resumes when the top activity
exits.
● Managing Back Stack with Explicit Intents:
o To prevent an activity from being added to the back stack, call finish()
immediately after startActivity():

startActivity(Intent(this, MainActivity::class.java))
finish()
● This ensures that the current activity is not kept in the back stack, which is
useful for activities like splash screens or login screens that should not be
revisited.

Example Code for Back Stack Management:

Scenario: Navigating from a splash screen to the main activity

val intent = Intent(this, MainActivity::class.java)


startActivity(intent)
finish() // Removes splash screen from back stack

Exchanging the data from activates

Introduction to Data Exchange Between Activities

● Overview:
o Data exchange between activities is essential for building interactive
Android applications.
o It allows activities to communicate and share information, such as user
input, across different screens.
o The most common way to exchange data between activities is through
Intents, which are used to navigate and pass information
simultaneously.

Common Scenarios for Data Exchange

● Why Exchange Data Between Activities?


o Passing User Input: For example, moving user-entered data (like
login credentials) from one activity to another.
o Navigating Between Forms: When navigating between forms or
screens, the data entered in the first screen needs to be carried over to
the next screen.
o Modifying Display Based on Previous Activity: Data exchanged
between activities can be used to customise the UI or functionality
based on user selections or actions.

Passing Data with Intents

● Using putExtra() to Pass Data:


o The simplest way to pass data to another activity is by using the
putExtra() method with an explicit intent.
o Example Code for Passing Data:
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("EXTRA_KEY", "Sample Data")
startActivity(intent)

This code sends the string "Sample Data" to SecondActivity under the
key "EXTRA_KEY."
● Supported Data Types:
o Primitives: You can pass primitive types like Int, Boolean, Float, etc.
o Strings: Strings are commonly passed between activities.
o Arrays: Pass arrays of primitives or strings, such as IntArray or
StringArray.
o Serialisable and Parcelable Objects: Complex data objects can be
passed using Serialisable or Parcelable.

Retrieving Data in the Target Activity

● Using getIntent() to Retrieve Data:


o The receiving activity can retrieve the passed data by calling
getIntent():

val data = intent.getStringExtra("EXTRA_KEY")

In this case, SecondActivity retrieves the string associated with


"EXTRA_KEY" and can use it to modify its content or UI.

Advanced Data Passing Techniques

● Using Bundles:
o Bundles are useful when you need to pass multiple pieces of data or
more complex data structures between activities.
o A bundle is essentially a collection of key-value pairs, allowing for a
more structured way of passing data.
o Example Code for Using Bundles:

val bundle = Bundle()


bundle.putString("EXTRA_KEY", "Sample Data")
val intent = Intent(this, SecondActivity::class.java)
intent.putExtras(bundle)
startActivity(intent)

o In this example, the bundle is created, the data is added to the bundle,
and the intent carries the bundle to SecondActivity.

Activity Lifecycle

The Activity Lifecycle represents the series of states that an activity goes through
from the moment it is launched until it is destroyed. Understanding this lifecycle is
crucial for managing resources efficiently, ensuring smooth user interaction, and
handling state changes in Android apps.

Basic Lifecycle Methods

1. onCreate()
o Purpose: Called when the activity is first created. It is where you
should initialise essential components like the UI, data binding, and
setting up listeners.
o Best Practice:
▪ Keep this method efficient by avoiding heavy operations like
network calls or data processing.
▪ Load heavy data in the background using coroutines or
AsyncTasks.
2. onStart()
o Purpose: Called when the activity becomes visible to the user but is
not yet ready for user interaction.
o This is where UI-related operations, like displaying progress
indicators, should be initiated.
o Typically, onStart() is a transitional state before onResume().
3. onResume()
o Purpose: Called when the activity is fully visible and ready for user
interaction.
o At this point, the activity is in the foreground and remains here until it
is paused.
o Best Practice: Resume animations, start camera previews, or initialise
sensors here, as this is when the user can interact with the app.
4. onPause()
o Purpose: Called when the system is about to start another activity,
placing the current activity in the background.
o This is where you should stop animations, release resources like audio
focus, or save unsaved changes.
o Best Practice: Use onPause() to save user data, as the activity might
be killed after this method is called.
5. onStop()
o Purpose: Called when the activity is no longer visible to the user.
o Release resources like threads, animations, or other processes that
consume CPU or memory.
o Best Practice: Handle cleanup of non-critical resources to ensure
minimal memory usage while the app is not visible.
6. onRestart()
o Purpose: Called when the activity transitions from being stopped to
started again. This method is called only after onStop() and before
onStart().
o It is useful for refreshing resources that were released in onStop().
7. onDestroy()
o Purpose: Called before the activity is completely removed from
memory, either when the user finishes the activity or the system
decides to reclaim resources.
o Best Practice: Free up resources that are not handled in onStop(), like
closing database connections or saving persistent data.

Best Practices for Managing the Activity Lifecycle

● Avoid Heavy Operations in onCreate(): Load heavy data asynchronously to


keep onCreate() lightweight and ensure faster startup times.
● Save Critical Data in onPause(): Use this method to save user data, as the
activity might be killed by the system without calling onStop() or onDestroy().
● Release Resources in onStop(): Stop processes that consume resources like
CPU or memory to prevent leaks and improve app performance.
● Handle Edge Cases Gracefully: Test lifecycle transitions thoroughly to
handle unexpected shutdowns or interruptions, ensuring that the app remains
stable.
● Use ViewModels and LiveData: Leverage Android’s architecture
components like ViewModel and LiveData to manage UI-related data
efficiently and survive configuration changes.

Understanding the Activity Lifecycle is essential for building efficient Android apps.
Key methods like onCreate(), onStart(), onResume(), onPause(), onStop(), and
onDestroy() help manage transitions, resources, and user data, ensuring smooth app
performance and better user experience.
Managing Activity States

Introduction to Activity States

What are Activity States?

● Activity states represent the different stages an activity goes through during its
lifecycle, such as created, running, paused, stopped, and destroyed.
● Proper management of these states is crucial for building responsive and
efficient Android applications.
● Understanding how to handle state transitions ensures that the app maintains
user data and manages resources effectively.
● Importance of Managing Activity States:
o Ensures smooth app performance.
o Conserves resources, providing a good user experience.
o Helps preserve user data during configuration changes, like screen
rotation or when the system reclaims resources.
Saving and Restoring Activity State

Saving Activity State:


o Use the onSaveInstanceState() method to save the state before the
activity is stopped or destroyed.
o Example Code for Saving State:

override fun onSaveInstanceState(outState: Bundle) {


super.onSaveInstanceState(outState)
outState.putInt("COUNTER_KEY", counter)
}

● In this example, the counter value is saved with the key "COUNTER_KEY" in
the Bundle, allowing it to be restored later.
Restoring Activity State:
● Use onCreate() or onRestoreInstanceState() to restore the saved state.
Example Code for Restoring State:

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
counter = savedInstanceState.getInt("COUNTER_KEY", 0)
}
}
MODULE NAME: Fragments, User Interaction and
Navigation in Android Development

Lesson 1: Fragments in Android


Topic: What are Fragments

Definition: Fragments are modular sections of an activity that represent a portion of


the UI and behaviour

Purpose: They allow developers to create more flexible and reusable UI components
within activities.
https://techvidvan.com/tutorials/android-fragments/

Component of Activities: Fragments are embedded within activities, and each


fragment has its own lifecycle, distinct from the activity's lifecycle.

Modularity: Break down the UI into smaller, reusable components.


Dynamic UI Changes: Fragments can be dynamically added, removed, or replaced
during runtime.
Support for Multiple Screen Sizes: Fragments allow for flexible UI designs that
adapt to different screen sizes (phones, tablets).
Adaptability: Fragments enable designs that adapt to different screen sizes and
orientations without duplicating code.
Dynamic UI: Fragments can be dynamically added, replaced, or removed during
runtime, allowing for a more interactive user experience.
Resource Management: Fragments help in managing different layouts for different
screen sizes (e.g., single-pane for phones, multi-pane for tablets).

Lifecycle Management: Fragments have their own lifecycle, which can be managed
independently of the parent activity.
State Retention: Fragments can retain their state across configuration changes (e.g.,
screen rotation) without having to reload data.
Efficient Resource Use: By reusing fragments, you avoid recreating and reloading UI
components unnecessarily.

Topic: Creating Fragments

Fragment Class Definition:


The SimpleFragment class extends Fragment, which is the base class for creating
fragments in Android.
● This is the foundational step in creating any fragment: defining the fragment
class.
● onCreateView() Method
● The onCreateView() method is crucial in fragment development. This method is
where the fragment’s UI is created.
● In this method, the fragment's layout is inflated from an XML file, turning it into
a view hierarchy that the fragment will display.
● The parameters inflater, container, and savedInstanceState are used to manage
and attach the fragment's layout to its parent activity.

Important Imports

● The import statement androidx.fragment.app.Fragment brings in the necessary


functionality to use fragments.
● This import is essential for any fragment-based class to work, as it links the
class to the Android Fragment framework.

Adding Fragments

Static Addition via XML:

● Explanation: Use the <fragment> tag in the activity's XML layout to


statically add a fragment.

Dynamic Addition via Kotlin:

● Explanation: Use FragmentManager and FragmentTransaction to


dynamically add a fragment to the activity at runtime.

When to use each method:


Static for fixed layouts, dynamic for user-interactive or conditional layouts.

Topic: Fragment Life Cycle in Android App Development

● Fragment Lifecycle Overview

Introduction to Fragment Lifecycle:

Explanation: Similar to an Activity, a Fragment has its own lifecycle that is closely
tied to the lifecycle of the parent Activity.
Stages: The lifecycle is divided into stages that represent different states of the
Fragment, from creation to destruction.
Lifecycle Diagram Overview
Explanation: The provided diagram illustrates the sequence of lifecycle callbacks that
a Fragment goes through from start to end.
Fragment Start: The lifecycle begins with onAttach() and progresses through
onCreate(), onCreateView(), and other callbacks as the Fragment becomes active.
Fragment End: The lifecycle ends with the onDestroyView(), onDestroy(), and
onDetach() methods.

● Lifecycle Phases (Start to Running)


Fragment Initialisation:
onAttach():
Called when the fragment is associated with its parent activity.
Purpose: Initialise components that need the context of the parent activity.
onCreate():
Called when the fragment is being created. Initialise essential components but do not
inflate the UI here.
Creating the Fragment's View:
onCreateView():
Called to inflate the fragment's UI from an XML layout file.
Purpose: Return the View object that represents the fragment's UI.
Fragment is Ready for Interaction:
onActivityCreated():
Called after the activity’s onCreate() has completed, indicating that the fragment's
view hierarchy is fully created.
onStart():
The fragment becomes visible but not yet interactable.
onResume():
The fragment is now fully visible and interactable, entering the "running" state.

● Lifecycle Phases (Running to End)


onPause():
Called when the fragment is partially obscured, indicating that it is no longer in the
foreground but still visible.
Stopping the Fragment:
onStop():
The fragment is no longer visible, and it has transitioned to the background.
Destroying the Fragment's View:
onDestroyView():
The view hierarchy of the fragment is being removed. This is where you clean up
resources tied to the fragment's view.
onDestroy():
Called when the fragment is being destroyed, but after the view hierarchy has been
removed.
onDetach():
The fragment is completely detached from the activity, and any final cleanup is done.

Topic: Replacing the fragment in the activity with another fragment

● FRAGMENT REPLACEMENT

1. What Fragment Replacement Means in Android:


Fragment replacement in Android refers to the process of removing an existing
fragment in an activity and adding a new one in its place, typically within a
FrameLayout or another container.
This allows the activity's user interface to change dynamically without the need to
create a new activity or reload the entire screen.
How It Works:
The process involves using FragmentTransaction to replace the current fragment with
another. The replace() method is called to specify the new fragment that will take the
place of the existing one, and commit() is used to finalise the transaction, making the
change visible.

2. Why You Might Want to Replace Fragments in an Activity:


Dynamic User Interface:
Replacing fragments allows for a more dynamic and flexible user interface. For
instance, instead of navigating to a new screen (activity), you can change the content
within the same screen by replacing fragments.
This is particularly useful in applications where the layout needs to adapt based on
user interactions, such as selecting items from a list or switching between different
views like tabs.
Efficient Resource Management:
By replacing fragments instead of launching new activities, you save on resources.
Fragment replacement allows you to reuse the existing activity while only changing
the content area, leading to better performance and a smoother user experience.
Improved User Experience:
Users experience a more seamless transition between different views, as the activity
remains consistent while the displayed content changes. This can help maintain
context and reduce cognitive load for the user.
3. Use Cases for Fragment Replacement:
Example 1: Switching Between Content Sections

Scenario: A news app has different sections like "Top Stories," "Sports," and
"Entertainment." Instead of navigating to a new screen for each section, the app can
replace the fragment within the main activity to show the relevant content.
Benefit: This keeps the navigation simple and allows users to quickly switch between
sections without losing context.
Example 2: Master-Detail Layouts
Scenario: In a master-detail layout, where you have a list on the left and details on the
right, clicking an item in the list can replace the fragment on the right side with the
detailed view of the selected item.
Benefit: This allows for a more fluid interaction, particularly on tablets or larger
screens, where both the list and detail views can be shown side by side.
Example 3: Multi-Step Forms or Wizards
Scenario: In a multi-step form or wizard, each step can be represented by a fragment.
As the user completes each step, the current fragment is replaced with the next one.
Benefit: This provides a clear and linear progression for the user without requiring
multiple activities, keeping the experience cohesive and straightforward.
Example 4: Tab Navigation
Scenario: In apps that use tab navigation, selecting a different tab can replace the
current fragment with the fragment corresponding to the selected tab.
Benefit: This allows for efficient content management and quick switching between
different views while maintaining the overall activity context.

● Buttons for fragments


buttonFragment1.setOnClickListener: This listener triggers the replacement of the
current fragment with Fragment1 when the "Show Fragment 1" button is clicked.
buttonFragment2.setOnClickListener: Similarly, this listener replaces the current
fragment with Fragment2 when the "Show Fragment 2" button is clicked.

● FRAGMENT Transaction
supportFragmentManager.beginTransaction(): This initiates a new fragment
transaction, which is necessary for any operations involving fragment changes.
fragmentTransaction.replace(R.id.fragmentContainer, fragment): This line replaces
the current fragment in the fragmentContainer (a FrameLayout in the activity's layout)
with the new fragment passed as a parameter.
fragmentTransaction.commit(): This commits the transaction, making the replacement
effective and visible to the user.

● dynamic fragment addition


It involves creating a fragment class and inflating its layout within the fragment's
onCreateView() method. The fragment would then be added to the activity
dynamically via code, typically using FragmentManager and FragmentTransaction

Fragment Class (FragmentOne): The code snippet shows the FragmentOne class
where the onCreateView() method is overridden to inflate the fragment's layout. This
class represents the fragment itself, not its static addition to an activity.

Inflating Layout (onCreateView()): The layout (R.layout.fragment_one) is being


inflated within the fragment's code. This is a typical setup for a dynamically added
fragment where the layout is associated with the fragment during its creation.

No <fragment> Tag in XML: The provided XML snippet shows the layout for the
fragment, not the static inclusion of the fragment in an activity's layout file using the
<fragment> tag. This indicates that the fragment is designed to be added dynamically
rather than being statically placed in the activity’s layout XML.

Static Addition via XML:

In static addition, fragments are declared in the activity's XML layout file, and they
become part of the activity's view hierarchy when the activity's layout is inflated.
This method is straightforward and useful when the fragment layout is known at
compile time and does not need to change dynamically.

How It Works:
You use the <fragment> element in the XML layout file to define the
fragment that should be included in the activity.
The android:name attribute specifies the class name of the fragment to
instantiate.
Limitations:

Since the fragment is tied directly to the activity's layout, it cannot be easily replaced
or removed at runtime. It’s best suited for simple, static UIs.

Use Case:

Dynamic Fragment Switching in a Single Activity: In a mobile application, users


can seamlessly switch between different content views within a single activity using
buttons. For instance, the program dynamically replaces one fragment with another
(like switching between "Fragment 1" and "Fragment 2") when the user interacts with
the interface. This approach enhances the user experience by keeping the activity
context consistent while allowing the content to change dynamically based on user
actions.

CODE IS GIVEN

Topic: Fragment communication

● Fragment Communication Using LiveData and ViewModel

Shared ViewModel Concept:


ViewModel is a class designed to store and manage UI-related data in a
lifecycle-conscious way.
When fragments within the same activity need to share data, they can utilise a
shared ViewModel. This ViewModel is scoped to the activity, allowing both
fragments to access the same instance.

Using LiveData for Reactive Communication:


LiveData is an observable data holder class. Fragments can observe LiveData
objects for changes, and when data is updated, the UI is automatically refreshed.
LiveData is lifecycle-aware, meaning it only updates the fragment when it is in an
active state (e.g., started or resumed).

Steps for Implementation:

1. Create a Shared ViewModel:

Define a ViewModel class with LiveData properties to hold the data that
fragments need to share.
Example:

class SharedViewModel : ViewModel() {


val selectedData: MutableLiveData<String> = MutableLiveData()
}

2. Access the ViewModel in Fragments:

Both fragments retrieve the shared ViewModel instance using


ViewModelProvider.
Example:

val sharedViewModel =
ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)

3. Update and Observe Data:

One fragment updates the LiveData in the ViewModel, while the other fragment
observes it for changes.
Example:

sharedViewModel.selectedData.observe(viewLifecycleOwner, Observer { data ->


// Update UI with the new data
})

Advantages:

Decoupled Architecture: Fragments don't directly communicate with each other,


leading to a more modular design.
Lifecycle Management: Data is preserved across configuration changes, such as
screen rotations.

● Best Practices for Fragment Communication

Minimise Direct Fragment-to-Fragment Communication: Use the host activity or


ViewModel to mediate communication.
Favour LiveData and ViewModel for Consistency: Provides a reactive and
lifecycle-aware approach.
Avoid Tight Coupling: Design fragments to be reusable and independent of each
other.
Testing and Debugging: Ensure fragment communication flows are thoroughly tested,
especially in complex UIs.
MODULE NAME: Fragments, User Interaction and
Navigation in Android Development

Lesson 2: User Interaction in Android

Topic 1: Clickable images in Android

● Introduction to Clickable Images in Android Studio

Interactive UI: Clickable images enhance user interaction, allowing images to act
as buttons or triggers for actions, improving user experience.
Common Use Cases: Used in image galleries, interactive dashboards, and
applications where visual elements are central to the interface.

Potential Use Cases:

● Image Buttons: Creating custom buttons with images.


● Interactive Maps: Users can click on specific locations/images for more
information.

Customisation Tips:

● Image Styling: Use XML attributes to add borders, shadows, or rounded


corners.
● Advanced Actions: Trigger complex actions like opening new activities,
making network requests, or animating the image.

Key Features:

● Seamless Integration: Easily integrated into any Android project with


minimal code.
● Versatility: Can trigger various actions such as navigating to different screens,
displaying messages, or launching new activities

● Implementation Steps

Content:

● Step 1: Adding the Image Resource


o Drawable Folder: Place your image (e.g., logo.jpg) in the
res/drawable folder.

● Step 2: Defining the Layout

o Layout File (activity_main.xml):


▪ Added an ImageView with attributes like android:src,
android:clickable, and android:contentDescription.
▪ Centered the image using layout_centerInParent.

● Step 3: Handling Click Events

o Kotlin Code (MainActivity.kt):

▪ Used findViewById to reference the ImageView.


▪ Implemented a setOnClickListener to show a Toast message
when the image is clicked.

Purpose of image_desc in strings.xml:

Accessibility:

1. The android:contentDescription attribute in an ImageView (or other UI


elements) is used to provide a textual description of the visual content.
This description is crucial for users who rely on screen readers, such as
visually impaired users.
2. The content description helps these users understand what the image
represents without seeing it.

Localisation:

1. By placing the description in strings.xml, you can easily translate the


text into different languages for localisation. This means you can
support multiple languages without modifying the code.
2. If your app supports multiple languages, you can have different values
for image_desc in various strings.xml files for different locales.

Why Use @string/image_desc Instead of Hardcoding:

● Consistency: Using a string resource like @string/image_desc ensures that all


textual elements are managed in one place (strings.xml). This practice leads to
more maintainable and cleaner code.
● Reusability: If the same description is used in multiple places, you can
reference the same string resource, making updates easier.
● Separation of Concerns: It separates UI design from content, which is a good
practice in software development.

Topic 2: Checkbox in Android

● Introduction to CheckBox in Android

● Significance:

User Input Control: A CheckBox allows users to select one or more


options, commonly used in forms, surveys, and settings.
Versatility: Can be grouped together for multiple selections or used
individually for binary choices.

● Key Features:

Simple UI Element: Easy to implement and integrate into various


Android layouts.

● Implementation Steps

● Step 1: Adding the CheckBox to the Layout

Layout File (activity_main.xml):

▪ Inserted a CheckBox element into the layout.


▪ Added a TextView to display the checkbox’s state.
● Step 2: Handling the CheckBox State

Kotlin Code (MainActivity.kt):

▪ Used findViewById to reference the CheckBox and TextView.


▪ Implemented setOnCheckedChangeListener to update the
TextView based on the checkbox state.

Topic: Radio box in Android

For more information :


https://www.geeksforgeeks.org/android-how-to-add-radio-buttons-in-an-android-appli
cation/

● Introduction to RadioBox in Android

Significance:

Single Selection: A RadioGroup ensures that only one option can be selected from a
set of RadioButton elements.
Common Use Cases: Ideal for scenarios where users must choose only one option
from a predefined list, such as selecting a payment method, choosing a gender option,
or setting preferences.

Key Differences from CheckBox:

Exclusive Selection: Unlike CheckBox, which allows multiple selections,


RadioButton is typically used for single-choice options within a group.
Grouped Control: RadioButton elements are often grouped using RadioGroup to
enforce single selection among multiple options.

Real-Time Examples:
● User Preferences: Allowing users to select one preferred language or theme
in an app’s settings.
● Surveys and Forms: Selecting a single answer from multiple choices, such as
choosing a favourite genre in a survey.
● Payment Options: Choosing a payment method (e.g., credit card, PayPal,
etc.) during checkout

Topic: Introduction to Menus in Android

The code is working with pixel 4 API 28 ….


For more information:
https://www.scaler.com/topics/popup-menu-in-android/

What is a Popup Menu?

A PopupMenu is a floating menu that appears when a user performs a long-click or a


specific action. It provides a list of items for the user to select from, typically
anchored to a specific view.

Use Case:

Ideal for actions related to the selected content, such as editing or deleting an item in a
list.

Why Use Popup Menu?

Provides a non-intrusive way to offer additional actions related to specific content.


Simplifies user interaction by offering contextual options directly tied to a UI
element.

● Implementation in Android Studio

Step 1: Setup Layout (activity_main.xml):

Added a Button with the ID showPopupBtn.


Anchors the PopupMenu to this button.

Step 2: MainActivity.kt Code:

onCreate() method: Initialises the Button and sets up an OnClickListener to


trigger the PopupMenu.
showPopupMenu(view: View) method:

o Inflates the PopupMenu from the main_menu.xml.


o Handles item selection through a listener.

Step 3: Menu Resource (main_menu.xml):

Defined three menu items with unique IDs (option1, option2, option3).
Each item corresponds to an action in the popup menu.
Example Implementation:

Demonstrates the popup menu with options like "Option 1," "Option 2," and "Option
3". Each selection triggers a Toast message confirming the selection.

Real-World Use Cases:

List Item Actions: In a messaging app, a popup menu might offer "Reply,"
"Forward," or "Delete" options when long-pressing a message.
Contextual Editing: In a document editing app, a popup menu might provide "Cut,"
"Copy," or "Paste" options tied to a selected text.

Advantages:

Simplifies the UI by hiding less frequently used actions.


Enhances user experience by providing contextual actions only when needed.
MODULE NAME: Fragments, User Interaction and
Navigation in Android Development

Lesson 3: Navigation in Android


Topic: Introduction to Navigation Component

● Understanding Navigation in Android

● Definition: Navigation in Android refers to the interactions that allow users to


move between different sections or content areas within an application.
● Types of Navigation:
o Linear Navigation: Moving sequentially through a series of screens.
o Hierarchical Navigation: Drilling down into more detailed screens
from a high-level screen.
o Lateral Navigation: Moving between sibling screens, often using tabs
or swiping gestures.
o Backstack Navigation: The ability to move backwards through the
app's history of screens.

● Importance of Effective Navigation

● User Experience (UX):


o Consistency: Ensures users can easily predict where to find
information or actions.
o Efficiency: Streamlines the process of moving through an app,
reducing user effort.
● User Retention:

o Intuitive Navigation: Reduces frustration and keeps users engaged.


o Ease of Use: Encourages users to explore more features and sections
of the app.

Here’s a structured approach to the first topic, "Introduction to Navigation in


Android”

● Common Navigation Structures in Android

● Single Activity vs. Multiple Activities:

o Single Activity Model: Uses fragments to manage different screens


within a single activity. Promotes modularity and reuse.
o Multiple Activities Model: Uses separate activities for different
screens. Simpler for small, less complex apps.

● Fragment-Based Navigation:
o Fragments: Modular components that can be dynamically swapped
within an activity, allowing for more flexible navigation structures.

● Navigational UI Components

● Overview of Navigation UI Elements:


o Action Bar/Toolbar: Provides a consistent place to put the app's main
navigation options.
o Navigation Drawer: A panel that slides in from the side, used for
app-wide navigation.
o Bottom Navigation Bar: Displays the primary navigation destinations
at the bottom of the screen.
o Tabs: Provides lateral navigation between sibling content, often used
with swipe gestures.
● When to Use Which Component:

o Action Bar/Toolbar: For essential navigation and app actions.


o Navigation Drawer: When there are more navigation options than can
fit on a toolbar.
o Bottom Navigation: For primary destinations, typically 3-5, that are
equally important.
o Tabs: For grouping similar content, like different views of the same
data.

Topic: Implementing Navigation

● Introduction to Navigation in Android

Content:

● Overview: Navigation in Android allows users to move between different


screens or activities within an app. It is essential for creating a user-friendly
interface.
● Key Concept: We'll demonstrate a simple example where a user can navigate
from MainActivity to SecondActivity using a button click.

● Setting Up MainActivity

Button for Navigation:

o MainActivity includes a button labeled "Go to Second Activity".


o This button is responsible for triggering navigation to SecondActivity.

val btnNavigate = findViewById<Button>(R.id.btnNavigate)


btnNavigate.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
Intent: An Intent is used to start the SecondActivity when the button is clicked.

● Creating SecondActivity

● Simple UI: SecondActivity displays a message, "Welcome to the Second


Activity!".
● Purpose: This demonstrates the destination of the navigation action from
MainActivity.

Relevant Code Snippet:

<TextView
android:text="Welcome to the Second Activity!"
android:layout_centerInParent="true" />

TextView: A simple TextView is used to show the message in the centre of the
screen.

Slide 4: Configuring AndroidManifest.xml

● Registering Activities:
o Both MainActivity and SecondActivity must be declared in the
AndroidManifest.xml.
o MainActivity is set as the launcher activity.

Relevant Code Snippet:

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

Explanation:

● Launcher Activity: MainActivity is defined as the entry point of the app with
the LAUNCHER category.
● SecondActivity: Registered without an intent filter since it’s only accessed
through navigation.

Topic: Hierarchical navigation

● Understanding Hierarchical Navigation


What is Hierarchical Navigation?

● Definition: Hierarchical navigation refers to a navigation pattern where users


can drill down into more detailed views from a higher-level overview. It is
structured like a tree, where each branch represents a deeper level of content
or options.
● Usage: Commonly used in applications where users need to navigate through
layers of related content, such as settings, file directories, or category-based
apps.

● Real-Time Examples of Hierarchical Navigation

Where is Hierarchical Navigation Used?

Settings Menu:

Example: In an Android device's Settings app, you start with a list of high-level
options (e.g., Wi-Fi, Bluetooth, Display). Selecting one leads to more specific settings
within that category.

File Managers:

Example: File manager apps allow users to start from a root directory (like Internal
Storage) and navigate through folders to access specific files.

E-commerce Apps:

Example: In shopping apps, users might navigate from broad categories (e.g.,
Electronics) to subcategories (e.g., Smartphones), and finally to individual products.

● Benefits and Considerations of Hierarchical Navigation

Advantages and Best Practices

Advantages:
● Clear Structure: Organises content logically, making it easy for users to find
what they’re looking for.
● Scalability: Easily accommodates additional layers of content without
overwhelming the user.
● User Control: Users can backtrack easily, maintaining a sense of orientation
within the app.

Best Practices:
● Avoid Deep Nesting: Limit the number of hierarchical levels to prevent users
from feeling lost.
● Provide Context: Use breadcrumbs, titles, or back buttons to help users
understand where they are in the hierarchy.
● Maintain Consistency: Ensure navigation patterns are consistent across the app
for a smoother user experience.
Module Name: Data Management

Lesson 1: Shared Preferences

Topic 1 : Introduction to Shared preferences


For More Information: https://developer.android.com/training/data-storage/shared-preferences

Introduction to Shared Preferences


What are Shared Preferences?

• Shared Preferences are a simple key-value storage system in Android.


• Primarily used to store small amounts of data such as user preferences, settings, and configurations.
• Ideal for storing primitive data types like booleans, floats, ints, longs, and strings.

Why Use Shared Preferences?


Advantages of Shared Preferences

• Simplicity: Easy to implement for storing simple data.


• Persistence: Data remains available across app sessions, even after the app is closed and reopened.
• Efficiency: Lightweight and fast, making it suitable for small amounts of data.

Use Cases of Shared Preferences


When to Use Shared Preferences

• Storing user settings, such as theme preferences or notification settings.


• Saving user login states or session information.
• Tracking the state of simple tasks (e.g., onboarding completion).

Key Characteristics
Characteristics of Shared Preferences

• Data Storage: Stores data in an XML file within the app’s internal storage.
• Security: Accessible only by the app unless explicitly shared.
• Flexibility: Can be used for both application-wide preferences or specific to an activity or service.
Topic 2: Options for Data storage
Overview of Data Storage Options in Android

Data Storage Options in Android

• Android offers multiple ways to store data, each suited for different use cases.
• Understanding these options helps in choosing the right storage mechanism based on the app’s
requirements.
• Primary storage options include:
o Shared Preferences
o Internal Storage
o External Storage
o SQLite Databases
o Network or Cloud Storage

• Shared Preferences

Purpose: Store simple key-value pairs.

Use Cases: User settings, preferences, flags (e.g., first-time launch).

Characteristics:

▪ Lightweight and easy to use.


▪ Not suitable for complex data or large amounts of data.

Pros:

▪ Simple implementation.
▪ Persistent across app sessions.

Cons:

▪ Limited to primitive data types and strings.


▪ Not secure for sensitive data.

• Internal Storage

Purpose: Store private data within the app's internal memory.

Use Cases: Saving files that should not be accessible to other apps, such as user data, cached files.

Characteristics:

▪ Files are private to the application by default.


▪ Data is removed when the app is uninstalled.

Pros:

▪ Secure, as data is not accessible by other apps.


▪ No additional permissions required.
Cons:

▪ Limited by device storage.


▪ Not suitable for sharing data between apps.

• External Storage

Purpose: Store data on external storage mediums like SD cards or shared storage directories.

Use Cases: Media files (photos, videos), documents, data meant to be shared with other apps.

Characteristics:

▪ Accessible by the user and other apps.


▪ Requires permissions to read/write.

Pros:

▪ Suitable for large files and sharing data between apps.


▪ More storage space compared to internal storage.

Cons:

▪ Less secure, as data is accessible by other apps and users.


▪ Requires runtime permissions (from Android 6.0 onwards).

• SQLite Databases

Purpose: Store structured data in a relational database.

Use Cases: Complex data storage needs, data that requires querying, relationships between data entities.

Characteristics:

▪ Supports SQL queries for data manipulation and retrieval.


▪ Suitable for applications with complex data relationships.

Pros:

▪ Powerful and flexible for handling structured data.


▪ Efficient for searching and managing large datasets.

Cons:

▪ More complex to implement compared to other storage options.


▪ Requires understanding of SQL and database management.

• Network or Cloud Storage

Purpose: Store data on remote servers or cloud services.

Use Cases: Syncing data across devices, backup, accessing data from multiple platforms.
Characteristics:

▪ Data is stored remotely and accessed over the internet.


▪ Requires network connectivity.

Pros:

▪ Accessible from anywhere with an internet connection.


▪ Facilitates data synchronization and backup.

Cons:

▪ Dependent on network availability.


▪ Potential security and privacy concerns.

• Choosing the Right Storage Option

Selecting the Appropriate Storage Method

Considerations:

o Data Size: Small vs. large data.


o Data Complexity: Simple key-value pairs vs. structured relational data.
o Security Needs: Sensitive data requiring protection vs. public data.
o Data Longevity: Temporary vs. persistent storage needs.
o Accessibility: Private to the app vs. shared across apps or devices.

Decision Matrix:

o Shared Preferences: Simple, small, non-sensitive data.


o Internal Storage: Private, file-based, moderate complexity.
o External Storage: Shared, file-based, large or media files.
o SQLite: Complex, relational, structured data.
o Network/Cloud: Remote, syncable, backup or cross-device access.

For more Information:

https://developer.android.com/training/data-storage
Topic 3: Shared preferences vs saved instance state

Understanding Saved Instance State


What is Saved Instance State?

Definition: Saved Instance State is a mechanism to save UI state temporarily when an activity is destroyed and
recreated (e.g., during screen rotation).

Use Cases:

o Preserving UI state (e.g., user input in a form, scroll position).


o Temporary data that only needs to survive configuration changes or short interruptions.

Characteristics:

o Data is only preserved for the current session.


o Automatically saved and restored by Android during configuration changes.
o Understanding Shared Preferences

What are Shared Preferences?

Definition: Shared Preferences are a key-value storage mechanism in Android.

Use Cases:

o Storing user settings or preferences (e.g., dark mode toggle).


o Saving persistent data that needs to be retained even after the app is closed.

Characteristics:

o Data persists across sessions.


o Stored in an XML file within the app's internal storage.
o Best for small, simple data like user preferences or app settings.
o Comparison: Shared Preferences vs. Saved Instance State

Key Differences

• Purpose:
o Shared Preferences: Persistent storage for small, simple data across app sessions.
o Saved Instance State: Temporary storage for UI state during activity lifecycle events.

• Persistence:
o Shared Preferences: Data persists even after the app is closed.
o Saved Instance State: Data is cleared when the app is fully closed or the process is killed.

• Usage:
o Shared Preferences: Best for user settings, app configurations.
o Saved Instance State: Best for UI state, temporary data during configuration changes.

• Implementation:
o Shared Preferences: Manually managed by the developer.
o Saved Instance State: Partially managed by Android, with manual handling for custom data.
Topic 4: Saving the Shared Preferences

Introduction to Saving Shared Preferences


Why Save Data with Shared Preferences?

• Shared Preferences allow you to save key-value pairs in a lightweight and persistent way.
• Ideal for storing user settings, preferences, or small amounts of data that need to be retained across app sessions.
• Simple API provided by Android makes it easy to implement.

Example Use Case

Saving User Input

• Use an EditText to capture user input.


• Save the input when the user clicks a button.
• Data is saved persistently and can be retrieved even after the app is closed and reopened.
• Illustration:
o EditText: User enters their name.
o Button: Saves the name to Shared Preferences.

Give them Scenario first

▪ Scenario Overview: Explain that you’re developing a simple app where the user can enter their name, and this
name should be saved and restored across sessions.
▪ Purpose: Highlight that the goal is to persist user data (e.g., a username) using Shared Preferences, ensuring it is
saved when the user leaves the app and restored when they return.

• Steps to Save Data in Shared Preferences

How to Save Data

o Step 1: Access the SharedPreferences instance.


o Step 2: Create an Editor to make changes.
o Step 3: Save the key-value pair using putString, putInt, etc.
o Step 4: Apply the changes asynchronously using apply().

val sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)


val editor = sharedPreferences.edit()
editor.putString("user_name", "John Doe")
editor.apply()
Topic 5: Restoring the Shared Preferences

Introduction to Restoring Shared Preferences


Why Restore Data from Shared Preferences?

• Restoring data ensures a consistent user experience across sessions.


• Data saved in Shared Preferences can be easily retrieved and used to initialize UI components.
• Commonly used for restoring user settings, last session state, or user preferences.

Steps to Restore Data from Shared Preferences


How to Retrieve Data

• Step 1: Access the SharedPreferences instance.


• Step 2: Retrieve the saved value using getString, getInt, etc.
• Step 3: Use the retrieved value to initialize UI components or other variables

val sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)


val savedName = sharedPreferences.getString("user_name", "")
nameInput.setText(savedName)

Example Use Case


Restoring User Input

• Automatically populate an EditText with the previously saved user name when the app starts.
• Enhances user experience by maintaining continuity across sessions.
• Illustration:
o EditText: Automatically filled with the saved name when the activity is recreated.
Topic 6: SQLite database
For More Information:

https://www.sqlite.org/docs.html

https://developer.android.com/training/data-storage/sqlite

Introduction to SQLite Database in Android


What is SQLite?

Definition: SQLite is a lightweight, self-contained, and serverless relational database management system
embedded in Android.

Purpose: Allows you to store structured data within your app using SQL (Structured Query Language).

Characteristics:

o No separate database server required—integrated within the app.


o Stores data in a single file on the device’s storage.
o Supports standard relational database features such as tables, indices, triggers, and views.

When to Use SQLite in Android


Use Cases for SQLite

Complex Data Relationships: Ideal for apps that need to manage complex relationships between data entities
(e.g., contacts, inventory systems).

Large Datasets: Suitable for handling large amounts of structured data that need efficient querying and
manipulation.

Persistence: Data stored in SQLite persists across app sessions and remains available even if the app is closed
or the device is rebooted.

Offline Capability: Allows the app to store data locally on the device, providing functionality even without
network connectivity.

One famous real-time example of SQLite database usage in Android is WhatsApp.

WhatsApp: Storing Chat Messages

Scenario:

WhatsApp, one of the most popular messaging apps globally, uses SQLite to store chat messages locally on a
user's device.

Each chat conversation is stored as a record in an SQLite database, enabling quick and efficient retrieval of
messages.

This approach allows users to access their chat history even when offline, as the data is stored locally on their
device.
Why SQLite?
Efficiency: SQLite handles large volumes of data efficiently, which is crucial for an app like WhatsApp that
manages thousands of messages for each user.

Persistence: The data remains available even if the app is closed or the device is rebooted, ensuring that users
can always access their chat history.

Offline Access: Users can read and search their chat history without requiring an internet connection, thanks to
the local storage provided by SQLite.

Scalability: SQLite can handle large datasets with complex relationships, such as multiple chat conversations,
multimedia files, and contacts, making it ideal for a messaging platform.

Key Features and Benefits of SQLite


Why Choose SQLite?

ACID Compliance: SQLite supports Atomicity, Consistency, Isolation, and Durability, ensuring reliable and
predictable transactions.

Standard SQL Syntax: Developers can use familiar SQL commands to manage data, making it easy to query,
insert, update, and delete records.

Lightweight and Efficient: Consumes minimal resources, making it ideal for mobile devices.

No Setup Required: Unlike other databases, SQLite requires no configuration or management of a database
server.

Open Source: SQLite is open-source software, meaning it’s free to use and widely supported.
Module Name: Data Management

Lesson 2: File operations in Android

Topic 1: Files in Android

Introduction to File Handling in Android


Overview of File Handling

• Android allows apps to store files either on internal or external storage.


• Files can be categorized into private files (accessible only by the app) and public files (accessible by other
apps).
• Types of Storage:
o Internal Storage: Private to the app, secure, and available even when the app is uninstalled.
o External Storage: Can be shared with other apps, but requires special permissions.

Understanding Internal and External Storage


Internal vs. External Storage

• Internal Storage:
o Private and secure.
o Best for sensitive data.
o Files are deleted when the app is uninstalled.
• External Storage:
o Shared with other apps.
o Suitable for large files like media.
o Requires runtime permissions for read/write access.

Real-World Use Cases


When to Use Each Storage Option

• Internal Storage: Best for sensitive user data, app-specific settings, and small files.
• External Storage: Ideal for storing media files (e.g., photos, videos) that should be accessible to other apps or
users.
• Examples:
o Internal Storage: Saving user preferences, storing cache data.
o External Storage: Saving photos or documents that the user may want to share.

Key Considerations
Choosing the Right Storage Option
Security Needs: Internal storage is best for sensitive or private data.

Data Size: External storage is better suited for large files.

Accessibility: Use external storage if the data needs to be shared with other apps.

Permissions: Remember that external storage requires runtime permissions starting from Android 6.0.

Topic 2: File operations

Introduction to File Operations


Overview of File Operations in Android

File operations involve creating, reading, writing, and deleting files in Android apps.

Files can be stored in different locations: Internal Storage (private to the app) and External Storage (shared with
other apps).

Proper file handling ensures data integrity and security, making it essential for tasks like saving user
preferences, caching data, or storing user-generated content.

Writing to a File in Android


How to Write Data to a File

Use FileOutputStream to write data to files.

For Internal Storage:

val fileOutputStream = openFileOutput("example.txt", MODE_PRIVATE)


fileOutputStream.write("Hello, Android!".toByteArray())
fileOutputStream.close()

For External Storage

val file = File(getExternalFilesDir(null), "example.txt")


file.writeText("Hello, External Storage!")

Always close the FileOutputStream after writing to ensure data is saved correctly.

Reading and Deleting Files in Android


How to Read and Delete Files

Reading from a file is done using FileInputStream or File objects.


For Internal Storage

val fileInputStream = openFileInput("example.txt")


val content = fileInputStream.bufferedReader().use { it.readText() }

For External Storage

val file = File(getExternalFilesDir(null), "example.txt")


val content = file.readText()

To delete a file

deleteFile("example.txt") // Internal Storage


file.delete() // External Storage

Ensure file operations handle exceptions to avoid crashes, particularly with external storage, which may not
always be available.
Topic 3: Internal storage

Introduction to Internal Storage


What is Internal Storage?

Internal Storage is a private storage area for each app.

Files saved in Internal Storage are only accessible by the app that created them.

Use case :

• The code for internal storage allows an Android app to securely save user data (like text files) that is only
accessible within the app itself. This ensures sensitive information remains private and cannot be accessed
by other apps or users. It is ideal for storing personal settings, user preferences, or app-specific data that
should not be shared
• Suitable for storing sensitive data that should not be shared with other apps or users.

Saving Data to Internal Storage


How to Save Data in Internal Storage

Use openFileOutput() method to create and write to files.

Example code snippet to save a text file

val fileOutputStream = openFileOutput("example.txt", MODE_PRIVATE)


fileOutputStream.write("Hello, Internal Storage!".toByteArray())
fileOutputStream.close()

Files are saved in the /data/data/<package_name>/files/ directory.

Reading Data from Internal Storage


How to Read Data from Internal Storage

Use openFileInput() method to read from files.

Example code snippet to read a text file

val fileInputStream = openFileInput("example.txt")


val inputStreamReader = InputStreamReader(fileInputStream)
val bufferedReader = BufferedReader(inputStreamReader)
val stringBuilder = StringBuilder()
bufferedReader.forEachLine { stringBuilder.append(it) }
val fileContents = stringBuilder.toString()

Files can be deleted using deleteFile("example.txt").


Topic4: External storage

Scenario: The code for external storage enables an Android app to save files in a shared space, accessible by other
apps and users, making it suitable for storing media files, documents, or data meant to be shared. This allows the app
to store large files or user-generated content that needs to be accessible outside the app, such as photos or
downloaded files. Proper permission handling ensures safe and controlled access to this shared storage.

Introduction to External Storage


What is External Storage?

• External Storage refers to the shared storage on the device, accessible by multiple apps.
• It can be on the device’s internal memory or an SD card.
• Suitable for storing files that should be accessible outside the app or shared with other apps.

Permissions and Accessing External Storage


Accessing External Storage Safely

External Storage requires runtime permissions in Android 6.0 (API level 23) and above.

Example code to request permissions

if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_CODE)
}

Use getExternalFilesDir() to save files in the app-specific directory on external storage.

Saving and Reading Data from External Storage


How to Save and Read Data in External Storage

Example code to save a file

val file = File(getExternalFilesDir(null), "example.txt")


file.writeText("Hello, External Storage!")

Example code to read the saved file

val file = File(getExternalFilesDir(null), "example.txt")


val fileContents = file.readText()
Be mindful of storage availability and check if external storage is mounted using
Environment.getExternalStorageState().

Topic 5: Permissions for storage

Overview of Storage Permissions


Understanding Storage Permissions in Android

Android requires apps to request permissions to access shared storage for security reasons.

Internal Storage: No special permissions required as it's private to the app.

External Storage: Requires READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE


permissions, especially from Android 6.0 (API level 23) and above.

Runtime permissions are needed to dynamically request access during app use.

Requesting Runtime Permissions


How to Request Storage Permissions at Runtime

• Use checkSelfPermission() to check if the app already has the necessary permission.
• If not granted, use requestPermissions() to prompt the user.
• Example code snippet

if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_CODE)
}

Handle the user's response in onRequestPermissionsResult() to proceed with storage operations or gracefully
degrade functionality.

Handling Permission Denials and Best Practices


Handling Permission Denials and Best Practices

Always check for permissions before performing storage operations to prevent app crashes.

If the user denies permissions, explain the necessity and provide an option to revisit the decision.
Use shouldShowRequestPermissionRationale() to determine if you should show additional context before
asking again.

Example scenario: Prompt the user to enable permissions in settings if denied persistently.

if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE))
{
// Show rationale and direct the user to settings
}

Topic 6: Other Storage options


For more information

https://developer.android.com/training/data-storage
https://developer.android.com/training/data-storage/sqlite

Exploring Additional Storage Options


Beyond Internal and External Storage

Android provides several other storage options beyond just internal and external storage.

These options are useful for specific use cases that require temporary storage, data synchronization, or complex
data management.

Examples:

o Cache Storage: For temporarily storing data that can be easily recreated.
o Cloud Storage: For syncing data across devices or backing up important files.

Cache Storage
Understanding Cache Storage

Purpose: Cache storage is used for temporarily storing data that can be easily regenerated, such as image
thumbnails or temporary files.

Characteristics:

o Temporary: Data stored in cache is not meant to be persistent and can be cleared by the system to free up
space.
o No Permissions Needed: Cache storage does not require special permissions.

Use Case: Ideal for storing temporary files that enhance app performance, like caching images from the web.

Network/Cloud Storage
Using Cloud Storage in Android

Purpose: Cloud storage allows apps to store data on remote servers, providing benefits like data
synchronization across devices and remote backups.

Characteristics:

o Cross-Device Access: Data stored in the cloud can be accessed from any device with internet connectivity.
o Persistent: Data is stored remotely, ensuring that it is safe from local device issues.

Use Case: Best for apps that need to store user data across multiple devices, like a note-taking app that syncs
notes across all user devices.

Databases and Structured Data Storage


Managing Complex Data with Databases

Purpose: For apps that require managing structured data, Android provides support for SQLite databases and
other relational database options.
Characteristics:

o Structured: Ideal for storing data that needs relationships and queries, such as user accounts or inventory
systems.
o Local Storage: Data is stored on the device but can be synced with a server for remote access.

Use Case: Ideal for apps like contact managers or task management apps where data relationships are complex
and need to be queried efficiently.

You might also like