0% found this document useful (0 votes)
13 views128 pages

Andriod Programming

The document provides detailed information about Ankit D. Shrivastava, an Assistant Professor at K. K. S. University, focusing on Android programming for BCA students. It covers the history, features, advantages, and disadvantages of Android development, along with a timeline of Android versions and their key features. Additionally, it highlights programming languages used in Android development, particularly the preference for Kotlin over Java.

Uploaded by

mujjushaikh5653
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)
13 views128 pages

Andriod Programming

The document provides detailed information about Ankit D. Shrivastava, an Assistant Professor at K. K. S. University, focusing on Android programming for BCA students. It covers the history, features, advantages, and disadvantages of Android development, along with a timeline of Android versions and their key features. Additionally, it highlights programming languages used in Android development, particularly the preference for Kotlin over Java.

Uploaded by

mujjushaikh5653
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

Ankit

Shrivastava
BFC-ACS
Vashi
KKSU
22.01.2026

Page | 1
Sr.
Particulars Remarks
No.
01 Name of Teacher Ankit D. Shrivastava

02 Mobile Number 9930320188

03 E-mail ID Shriank16@[Link]

04 Designation Assistant Professor

05 University Name K. K. S. University

Bakliwal Foundation College of Arts,


06 College Name
Commerce & Science

07 Website [Link]

08 Department Name Computer

09 Course Name BCA

10 Course Duration 3 Years

11 Semester VI

12 Subject Name Android Programming

13 Sub-topic Name Unit 1, Unit2,Unit 3,Unit 4

14 Content Type PDF

15 Search Keywords Introduction to .Net Framework

Page | 2
UNIT - 1
Introduction to Android Development
Android operating system is the largest installed base among various mobile platforms across the
globe. Hundreds of millions of mobile devices are powered by Android in more than 190 countries
of the world. It conquered around 71% of the global market share by the end of 2021, and this trend
is growing bigger every other day. The company named Open Handset Alliance developed Android
for the first time that is based on the modified version of the Linux kernel and other open-source
software. Google sponsored the project at initial stages and in the year 2005, it acquired the whole
company. In September 2008, the first Android-powered device was launched in the market.
Android dominates the mobile OS industry because of the long list of features it provides. It’s user-
friendly, has huge community support, provides a greater extent of customization, and a large
number of companies build Android-compatible smartphones. As a result, the market observes a
sharp increase in the demand for developing Android mobile applications, and with that companies
need smart developers with the right skill set. At first, the purpose of Android was thought of as a
mobile operating system. However, with the advancement of code libraries and its popularity among
developers of the divergent domain, Android becomes an absolute set of software for all devices like
tablets, wearables, set-top boxes, smart TVs, notebooks, etc.

If you’re looking to dive deeper into Android development and learn how to build powerful apps
using Kotlin, consider enrolling in the Android Development with Kotlin course . This course
offers comprehensive training, from the basics to advanced techniques, equipping you with the skills
needed to excel in Android development.

Android Versions
Google first publicly announced Android in November 2007 but was released on 23 SEPTEMBER
2008 to be exact. The first device to bring Android into the market was the HTC Dream with the

Page | 3
version Android 1.0. Since then, Google released a lot of android versions such as Apple Pie,
Banana Bread, Cupcake, Donut, Éclair, Froyo, Gingerbread, Jellybeans, Kitkat, Lollipop,
marshmallow, Nougat, Oreo, etc. with extra functionalities and new features.

The following table shows the version details of android which is released by Google from 2007 to
date.
Code Name Version API level Release date
– Android 1.0 1 September 23, 2008

– Android 1.1 2 February 9, 2009

Cupcake Android 1.5 3 April 30, 2009

Donut Android 1.6 4 September 15, 2009


Eclair Android 2.0 – 2.1 5-7 October 26, 2009

Froyo Android 2.2 – 2.2.3 8 May 20, 2010

Gingerbread Android 2.3 – 2.3.4 9-10 December 6, 2010

Honeycomb Android 3.0.x – 3.2.x 11 – 13 February 22, 2011

Ice Cream Sandwich Android 4.0 – 4.0.4 14 – 15 October 18, 2011


Jelly Bean Android 4.1 – 4.1.2 16 – 18 July 9, 2012

Kitkat Android 4.4 – 4.4.4 19 July 9, 2012


Lollipop Android 5.0 – 5.1 21 – 22 October 17, 2014
Marshmallow Android 6.0 – 6.0.1 23 October 5, 2015

Page | 4
Nougat Android 7.0 – 7.1 24 – 25 August 22, 2016

Oreo Android 8.0 26 August 21, 2017

Pie Android 9.0 27 August 6, 2018

Android Q Android 10.0 29 September 3, 2019

Android 11 Android 11.0 30 September 8, 2020

Snow Cone Android 12.0 – 12.1 31-32 October 4, 2021

Tiramisu Android 13 33 August 15, 2022

Upside Down Cake Android 14 34 October 4, 2023

Vanilla Ice Cream Android 15 35 May 15, 2024

Programming Languages used in Developing Android Applications


1. Java
2. Kotlin
Developing the Android Application using Kotlin is preferred by Google, as Kotlin is made an
official language for Android Development, which is developed and maintained by JetBrains.
Previously before Java is considered the official language for Android Development. Kotlin is made
official for Android Development in Google I/O 2017.
Advantages of Android Development
 The Android is an open-source Operating system and hence possesses a vast community for
support.
 The design of the Android Application has guidelines from Google, which becomes easier
for developers to produce more intuitive user applications.
 Fragmentation gives more power to Android Applications. This means the application can
run two activities on a single screen.
 Releasing the Android application in the Google play store is easier when it is compared to
other platforms.
Disadvantages of Android Development
 Fragmentation provides a very intuitive approach to user experience but it has some
drawbacks, where the development team needs time to adjust to the various screen sizes of
mobile smartphones that are now available in the market and invoke the particular features in
the application.
 The Android devices might vary broadly. So the testing of the application becomes more
difficult.
 As the development and testing consume more time, the cost of the application may increase,
depending on the application’s complexity and features.

Page | 5
Features of Android
Android is a powerful open-source operating system that open-source provides immense features
and some of these are listed below.

 Android Open Source Project so we can customize the OS based on our requirements.
 Android supports different types of connectivity for GSM, CDMA, Wi-Fi, Bluetooth, etc. for
telephonic conversation or data transfer.
 Using wifi technology we can pair with other devices while playing games or using other
applications.
 It contains multiple APIs to support location-tracking services such as GPS.
 We can manage all data storage-related activities by using the file manager.
 It contains a wide range of media supports like AVI, MKV, FLV, MPEG4, etc. to play or
record a variety of audio/video.
 It also supports different image formats like JPEG, PNG, GIF, BMP, MP3, etc.
 It supports multimedia hardware control to perform playback or recording using a camera
and microphone.
 Android has an integrated open-source WebKit layout-based web browser to support User
Interfaces like HTML5, and CSS3.
 Android supports multi-tasking means we can run multiple applications at a time and can
switch between them.
 It provides support for virtual reality or 2D/3D Graphics.

Page | 6
History of Android
The story of Android dates back to 2003 when Andy Rubin, Rich Miner, Nick Sears, and
Chris White co-founded a start-up Android Inc. in Palo Alto, California. However, the company
was later faced with the insufficiency of funds which brought Google into the picture. Google could
sense the potential the product carried within and sealed a deal worth $50 Million to acquire Android
in 2005. All the four Co-founders soon moved to the Googleplex to continue to develop the OS
further under their new owners. The first public Android Beta Version 1.0 was finally published
on 5th November 2007.

Android Version 1 Series


– Android 1.0 (API 1) and 1.1 (API 2)
Android 1.0 (API 1) was launched on the 23rd Of September 2008. It was incorporated into
the HTC Dream smartphone (aka T-mobile G1 in the US). It thus became the first-ever Android
device. The features it offered included Google Maps, YouTube, an HTML browser, Gmail, camera,
Bluetooth, Wi-Fi, and many more. The unique feature at that time was the presence of an Android
Market (now Play Store) from where the users could download and update Android applications
additional to what was already pre-installed. A few months later, in February 2009, Google released
the Android 1.1 (API 2) update for HTC Dream. This time the aim was to make it more robust and
user-friendly. There were four major updates in this version:
 Saving of attachments in messages

Page | 7
 Availability of details and reviews for businesses on Google Maps
 Longer in-call screen timeout by default while the speakerphone was in use along with the
ability to toggle the dial-pad.
 Support was added for a marquee in the system layouts.
– Android 1.5 (API 3) aka Cupcake
This version came up in late April 2009 and was the first to have Google’s dessert-themed naming
scheme and be incorporated in the Samsung Galaxy phone series. It was introduced with a lot of
functionalities that we take for granted today. These updates included new features and
enhancements to the ones already present in the above versions, for example, some major updates
included auto-rotation, third-party keyboard support, support for widgets, video recording, enabling
copy-paste for browser, facility to upload videos on YouTube, check phone usage history, etc.

– Android 1.6 (API 4) aka Donut


Just after a couple of months in September 2009, Donut was released. One of its most significant
features was the inclusion of CDMA-based networks that made it possible for carriers across the
globe to support it. Earlier only GSM technologies were in use. Other critical improvements such as
support for devices having different screen sizes, quick search boxes and bookmarks on web
browsers, fuller integration of Gallery, Camera, and Camcorder with faster camera access, expansion
of the Gesture framework, text-to-speech, etc. were too introduced in this update.

Android Version 2 Series


– Android 2.0 (API 5), 2.0.1 (API 6), and 2.1 (API 7) aka Eclair
Almost after a year of the Version 1 release, Version 2.0 was launched in October 2009. Key
highlights of this update included the introduction of navigation in Google Maps with voice
guidance, support for adding multiple accounts in one device, display of live wallpapers, a lock
screen with drag and drop unlocking functionality, additions to camera services such as Flash and
digital zoom, the inclusion of smarter dictionary for virtual keyboards that learned through word
usages, support for further more screen sizes, enhanced ability to track multi-touch events, better
Calendar agenda, support for HTML 5 view and so on and so forth. Within three months of 2.0’s
release, 2.0.1 and 2.1 were released in Dec 2009 and Jan 2010, respectively. These releases majorly
dealt with minor amendments to the API and other bug fixes.

– Android 2.2 (API 8) aka Froyo


Froyo is actually a combination of the words, “frozen Yogurt”. This version was launched in May
2010. Some of its most significant features included Wi-Fi mobile hotspot support, push
notifications through Android Cloud to Device Messaging, enhancement of device security through
PIN/ Password protection, Adobe Flash support, USB tethering functionality, update in Android
Market application with the automatic update of apps features, support for Bluetooth enabled car,
etc. The other versions 2.2.1, 2.2.2, and 2.2.3 were all in total about bug fixes and other security
updates all released in 2011. The latest of them, i.e. 2.2.3 was published in Nov 2011.

– Android 2.3 (API 9) aka Gingerbread

Page | 8
Gingerbread, released even before the later versions of Froyo, brought drastic changes to the look
and feel of smartphones. The first phone to adopt this version was Nexus S, co-developed by Google
and Samsung. In this version, the user interface design was updated to bring in more simplicity and
speed. Support for extra-large screen sizes and resolutions was integrated. Support for NFC
function, improved keyboard, enhanced support for multi-touch events, multiple cameras on the
device including a front-facing camera, Enhanced copy/paste functionality were some other
noteworthy features. Version 2.3.1 and 2.3.2 were released in Dec 2010 and Jan 2011 respectively.
They majorly carried improvements and bug fixes for the Nexus S.

– Android Version 2.3.3 and further in the series Gingerbread (API 10).
Version 2.3.3 brought along some API improvements and bug fixes in Feb 2011. Further 2.3.4 in
April the same year introduced support for voice and video chat using Google Talk. In this version,
the default encryption for SSL was also changed from AES256-SHA to RC4-MD5. 2.3.5 and 2.3.6
were released dominantly with various kinds of bug fixes and improvements in July 2011 and Sept
2011 respectively. 2.3.7 got the Google wallet support for the Nexus S 4G in Sept 2011.

Android Version 3 Series


– Android 3.0 (API 11) Honeycomb
In Feb 2011, Android 3.0 Honeycomb was released to be installed on tablets and phones with larger
screens only and had functions that could not be managed on phones with smaller screens. The most
important function brought by this version was to eliminate the need for the physical button and
rather the introduction of virtual buttons for performing the start, back, and menu functions. This
version was first launched along with the Motorola Xoom Tablet. Other refined UI advancements
were made by adding a System Bar which resolved quicker access to notifications and status at the
bottom. The inclusion of an Action Bar gave access to contextual options, navigation, widgets, and
other types of content at the top of the screen. This version also enabled switching between
tasks/applications easier. Another significant feature included the ability to encrypt all the user
data.

– Android 3.1 (API 12) Honeycomb


This version released in May 2011 presented many other UI refinements. Its foremost feature was
support for joysticks, gamepads, external keyboards, and pointing devices. It also had better
connectivity for USB accessories.

– Android 3.2 series Honeycomb (API 13)


Version 3.2 released in July 2011, mainly improved the hardware support and increased the ability
of various applications to access files on the SD card. Some displays support functions were also
upgraded in this update to control the variation of display appearances on different Android devices
more precisely.
3.2.1 in Sept 2011 brought in various bug fixes and minor security, Wi-Fi, and stability
improvements. Some other updates were too made to Google Books, Adobe Flash, and Android
Market.
On Aug 30, 2011, 3.2.2 and 3.2.3 were released, and in Jan 2012, 3.2.5 was published. All of them
were majorly about bug fixes and other minor improvements for the Motorola Xoom and Motorola
Xoom 4G.
Page | 9
In Dec 2011, the 3.2.4 version introduced the Pay As you Go feature for 3G and 4G tablets. And the
last version of this series, 3.2.6, published in Feb 2012 fixed the data connectivity issues faced when
disabling the Airplane mode on the US 4G Motorola Xoom.

Android Version 4 Series


– Android 4.0 (API 14) Icecream Sandwich
Android 4.0 was released in October 2011. It was a combination of a lot of features of the
Honeycomb Version and the Gingerbread. For the first time ever, the Face Unlock feature for
smartphones was introduced with 4.0. Other prominent features included the possibility to
monitor the use of mobile data and Wi-Fi, sliding gestures to reject notifications, tabs of a browser
or even tasks, integration of screenshot capture using the Power and Volume button, real-time
speech to text dictation, using certain apps without necessarily unlocking, pre-fed text responses to
calls, and many more. Another important feature that greatly enhanced the accessibility of devices
for the visually challenged people was a new explore-by-touch mode through which users could
navigate through the screen with the help of audible feedback. This eliminated the need to actually
view the device’s screen. A lot of advanced camera capabilities were added in this version, including
the Panorama mode. Live effects during the recording of videos were also introduced. The new
technology of Wi-Fi peer-to-peer (P2P) that lets the users connect directly to nearby peer devices
over Wi-Fi, without the need for internet or tethering was also introduced with this version. Android
4.0.1 and 4.0.2 introduced in October and November 2011 brought minor bug fixes to certain
devices.

– Android 4.0.3 and 4.0.4 Ice Cream Sandwich (API 15)


4.0.3, released in December 2011 brought various bug fixes, optimizations, and enhancements to
certain functionalities including databases, Bluetooth, graphics, camera, Calendar provider. 4.0.4,
released in March 2012, too brought minor improvements such as better camera performance and
smoother screen rotation.

– Android 4.1 (API 16), 4.2 (API 17), and 4.3 (API 18) Jelly Bean
Android 4.1 was the first version of Jelly bean and the fastest and smoothest by that time too. This
version further enhanced the accessibility and extended assistance to international users by
introducing Bi-directional text i.e. left to right or right to left scripts and support for various other
international languages. From this version onwards, the notifications could be expanded, display a
greater variety of content, present options for multiple actions, etc. User-installable keyboard maps
were also introduced. Shortcuts and widgets can automatically be re-arranged or re-sized to allow
new items to fit on home screens. Android Beam, an NFC-based technology could let users
instantly share media, just by touching two NFC-enabled phones together.
Version 4.2 was launched in Nov 2013. This was a faster smoother and more responsive version.
This was the first version to introduce the feature of one tablet, – many users through which multiple
users could use the same device but still have a separate system environment for each user data.
Other prominent incorporations included Widget support (display any kind of content on the lock
screen, however it was removed again in 2014), Daydream feature which is an interactive
screensaver mode that starts when a user’s device is docked or charging, presentation functionality
that let user represent a window for their app’s content on a specific external display, Wi-Fi Display

Page |
10
that let users connect to an external display over Wi-Fi on the supported devices and full native
support for RTL.
Version 4.3 released in July 2013 built further on the performance improvements already included
in earlier versions of Jelly Bean. It introduced the platform support for Khronos OpenGL ES
3.0, which provided games and some other apps with the highest-performance 2D and 3D graphics
capabilities on supported devices. This release further extended the multi-user feature for tablets,
which made it even easier to manage users and their capabilities on a single device. Another
prominent feature of this version would let apps observe the stream of notifications with the user’s
permission and then display them in any way they choose to. They could also send these
notifications to nearby devices connected over Bluetooth.

– Android 4.4 (API 19) Kitkat


The launch of Android 4.4 KitKat took place in 2013 and had many distinct features such as the blue
accents found in Ice Cream Sandwich and Jelly Bean had turned whiter and many storage
applications displayed lighter color schemes. With the ‘Ok Google’ command, a user could access
Google at any time and could work on phones with a minimum RAM memory of 512MB. The
phone app could automatically prioritize user’s contacts based on the numbers most frequently
contacted. Google Hangouts was introduced in this version that could keep all the user’s SMS and
MMS messages together in the same app. Emoji was made also available on Google Keyboard.

– Android 4.4W (API 20) KitKat, with wearable extensions.


3 Versions of Android KitKat exclusive to Android Wear devices were released between June 2014
to October 2014. These were primarily designed for smartwatches and other wearables and
integrated with Google Assistant technology and mobile notifications features into
a smartwatch form factor.

Android Version 5 Series


– Android 5.0 (API 21) Lollipop
Android 5.0 was launched in Nov 2014 with the Nexus 6 device. It was the first to feature Google’s
‘Material Design’ Philosophy which brought tremendous improvements to the UI Design, for
example, the Vector drawables which could be scaled indefinitely without losing their definition
were introduced. Other significant features included the replacement of VM Dalvik with Android
Runtime that improved the app performance and responsiveness considerably as some of the
processing power for applications could now be provided before they were opened. Support for
Android TV was integrated that provided a complete TV platform for any app’s big-screen
experience. The navigation bar had been renewed making it more visible, accessible, and
configurable. A/V sync was improved noticeably. Quite some new concepts too were implemented
in this release such as the ‘Document-centric apps‘ that enabled users to take advantage of
concurrent documents and provided them with instant access to their content/ services, ‘Android in
the workplace’ that allowed apps in the launcher to display a Work badge over their icon which was
an indication that a certain app and its data are administered inside of the work profile,
and ‘dumpsys batterystats‘ command that would generate battery usage statistics and help the
users understand system-wide power use.

– Android 5.1 (API 21) Lollipop

Page |
11
This version of Android was launched in March 2015. Some notable features of the release included
official support for multiple SIM cards, the Device protection policy that kept the device locked in
case of theft/misplacement until the owner signs into their Google account, and the introduction of
High-definition voice calls, available between compatible 4G LTE devices.

Android Version 6.0 Marshmallow (API 23)


Android Marshmallow was launched in October 2015 and it did bring along remarkable features
such as support for biometric fingerprint unlocking and USB type C support, the introduction of
Doze mode which reduced CPU speed while the display remains turned off to enhance the battery
life, a search bar for easy access to applications and option to mark them as favorites, Android Pay,
the introduction of the Memory Manager, Contextual search from keywords within apps, the
possibility to set the volume for device, media, and alarms all separately, a refurbished vertically
scrolling app drawer that could be accessed alphabetically, provisions for target-specific sharing
between apps, MIDI support for musical instruments and a lot more. Google Nexus 6P and Nexus
5X were the first devices to have android Marshmallow preinstalled.

Android Version 7 Series


– Android 7.0 (API 24) Nougat
In August 2016, Google released Android 7.0 Nougat. It presented improved multitasking features
especially for devices with larger screens, for example, the split-screen mode was introduced along
with provision for fast switching between applications. Other significant features included the
integration of the Daydream virtual-reality platform and enhancement of the ‘Doze now‘ mode.
More characteristics such as rearranging the Quick Setting tiles for faster access, replying to
conversations through notifications themselves, catching up with all the notifications from a specific
app together through bundled notifications, limiting device data usage with Data Saver, and the
possibility to change the size of the text as well as icons on the display screen were incorporated.
Google Now was replaced with Google Assistant. The first phones to come with this version
were Google Pixel, Pixel XL, and LG V20.

– Android 7.1, 7.1.1 and 7.1.2 Nougat (API 25)


Android 7.1, released in October 2016 majorly brought changes and updates to the existing features
and the ones introduced in 7.0, however, one fascinating design idea portrayed in 7.1 was
the Circular app icon support.
In 7.1.1, launched in December 2016, a new set of emojis with different skin tones and haircuts to
existing ones were added. Moreover, it now became possible to send GIFs directly from the default
keyboard.
In April 2017, 7.1.2 was published that brought in battery usage alerts.

Android Version 8 Series


– Android 8.0 (API 26) Oreo
This version appeared in Aug 2017 and brought a series of noteworthy changes to the existing ones.
It turned out to be a more powerful and faster version as it had a 2x boot speed compared to
Nougat when tested on Pixel devices, according to a claim by Google. This version was smarter as
well which was evident through the introduction of functionalities such as Autofill, picture-in-
Page |
110
picture mode (for example, the video calling window in WhatsApp while working with some
other app), and the Notification dots through which user could quickly catch up with newer
information. This update brought enhancements to the security aspect too by launching Google Play
Protect that ensured the safety of the device and its data against misbehaving apps. Apart from these,
attention was also driven towards visual details, e.g. the blob style for emojis was replaced with
emojis that were consistent with other platforms, and Quick Settings and Settings were redesigned
considerably.

– Android 8.1.0 (API 27) Oreo


Android 8.1 released in December 2017, introduced a variety of new capabilities for users and
developers. The most significant one for users was the development of Go Edition that provided
configurations for Memory optimizations, Flexible targeting options (New hardware feature
constants that let the users target the distribution of their apps to normal or low-RAM devices.), and
Google Play Services. For Developers, a whole new bunch of APIs was added including the Neural
Networks API, Shared memory API, and WallpaperColors API.

Android Version 9 Pie (API 28)


Android 9 was introduced in August 2018. It brought tremendous improvements to the visual aspect
and made exceptional use of the power of artificial intelligence. The most noticeable ones included,
replacement of traditional navigation buttons with an elongated button in the center that functioned
as the new start button, swiping which up provided an overview of recently used applications, a
search bar, and five application suggestions. Improvements were brought to the battery life, ‘Shush‘
was introduced that automatically put the phone in ‘Do not Disturb‘ mode by placing the phone
face down, capabilities for adaptive Brightness and Battery were embedded, provision to avail
details of screentime to grab a better idea of how often and for what purposes the phone device was
used was introduced.

Android Version 10 (API 29)


With Android 10 in Sept 2019, Google announced a rebranding of the operating system, eliminating
the sweets-name based naming scheme that was being used for the earlier versions. With this
version, a new logo and a different color scheme were announced. Facilities such as Live Captions
for all media, smarter replies to text (automated text and actions suggestions), ‘Focus mode’ to
block out distractions by selecting certain apps to pause temporarily, replacement of navigation
buttons with the use of gestures, availability of the dark mode at the system level, provision for more
control over permissions for applications, the introduction of support for foldable smartphones with
flexible displays, and capabilities to see device location, set screen time limits and have better
parental control over children’s content were embedded.

Android Version 11 (API 30)


Android 11 was recently released on the 8th of September 2020. This version has come up with a
tagline ‘The OS that gets to what’s important‘ and it’s pretty much justified. Android 11 brings
along capabilities to control conversations across multiple messaging apps all in the same spot, it
allows the user to digitally select priorities for people they are conversing with and then show the
most important conversations at the top and on the lock screen. Another distinguishing feature is the
chat bubbles (similar to the Facebook messenger) through which users can pin conversations from
various messaging apps so they always appear on their screens. The built-in screen recording feature
has been introduced finally that avoids the installation of an extra app to record the screen.
Page |
111
Enhancements have been brought to the smart reply features and the voice access functionalities.
One more captivating feature is the Device control capability that allows controlling all the
connected devices from one place. Google play security has also been updated remarkably. 11
major versions have been launched by Android till date and with each version, the OS promises
to get better. Till the next release let’s speculate what newer capabilities could an OS unleash!

Android Version 12 (API 31)


Android 12 was released on October 4, 2021 with tagline: “A Personal Phone for You”. Android
12 brings a complete visual overhaul with the introduction of Material You, a design system focused
on personalizing the user interface. With dynamic colour themes, users can customize the look and
feel of their devices to reflect their style, with the system adapting to wallpapers and user
preferences. Here’s a summary of some key features and fun facts about Android 12:
 Material You: The new design language changes the aesthetic of the entire system based on
users’ wallpaper, automatically generating a colour palette that’s applied to widgets,
notifications, settings, and more.
 Improved Privacy Features: Android 12 introduced a Privacy Dashboard, allowing users to
see which apps are accessing sensitive information like the microphone, camera, or location.
Visual indicators (like a small dot) notify users when an app is actively using the camera or
microphone.
 Quick Settings Overhaul: The Quick Settings panel was redesigned for easier access to
important controls, including toggles for smart home devices, Google Pay, and internet
connection.
 Performance Enhancements: Android 12 optimized the CPU usage by up to 22%, leading
to smoother animations and better power efficiency. This was particularly beneficial for
gaming and multitasking.
 Haptic Feedback Customization: Game developers and app creators can now provide more
immersive experiences by customizing haptic feedback based on audio or touch interactions,
which is great for mobile gaming.
 Scrolling Screenshots: One of the most requested features, scrollable screenshots, allows
users to capture long pages without needing to stitch multiple images together.
 One-Handed Mode: Android 12 introduced a one-handed mode, shrinking the display to
make it easier to interact with the device when using one hand.
 Fun Fact: Android 12’s Easter Egg features playful colour circles that reflect the Material
You design system. When you long-press the clock in the settings menu, you’re greeted by a
clock that spins around and eventually unlocks the dynamic colours.
 Another Fun Fact: Android 12 is optimized to work with foldable devices, which is
significant as foldable smartphones gained popularity in 2021 and beyond. This shows
Android’s commitment to innovation and adapting to new hardware trends.
 Overall, Android 12 focused on personalization, privacy, and performance, offering users a
more tailored and secure mobile experience. With the growing trend of foldable phones and
evolving smart technology, Android 12 set the foundation for even more flexible and
interactive mobile platforms in the future!
Page | 12
Android Version 13 (API 33)
Android 13 was released on August 15, 2022. Android 13 continues the focus on personalization,
security, and user experience enhancements. Building upon the foundation of Material You from
Android 12, Android 13 introduces more user-centric features and visual tweaks for a seamless and
secure experience across devices. Here are the features of and changes in the Android 13
 Expanded Customization with Material You: Users can now apply Material You’s
dynamic colour themes to more apps, not just Google ones. It allows greater personalization
of the entire system, including third-party app icons that adapt to wallpaper colours, making
the phone feel uniquely yours.
 Enhanced Multilingual Support: Android 13 offers per-app language preferences, so users
can choose different languages for individual apps. This is particularly useful for
multilingual users who prefer certain apps in different languages.
 Improved Privacy and Security: The Photo Picker feature lets users share specific images
with apps without giving access to the entire photo library. Also, app notification permissions
require apps to ask before sending notifications, giving users more control over their app
experience.
 Bluetooth Low Energy (LE) Audio: This new audio standard introduced better energy
efficiency and lower latency for wireless audio devices. It also supports broadcasting audio
to multiple devices, like sharing music with friends seamlessly.
 Spatial Audio Support: For a more immersive audio experience, Android 13 added Spatial
Audio, which adjusts the sound direction based on head movement, ideal for music and
video playback with compatible headphones.
 Improved Tablet and Foldable Experience: Android 13 introduced features to optimize the
experience on larger screens like tablets and foldable devices. The updated taskbar and
improved split-screen mode enhance multitasking, making it easier to use several apps side
by side.
 Fun Fact: Android 13’s Easter Egg is a quirky extension of the one from Android 12! This
time, it adds colourful emoji bubbles, where users can tap to create emoji patterns. You can
even find rare emojis like animals, food, and symbols!
 Fun Fact: For the first time, Android 13 supports streaming messaging apps to
Chromebooks, allowing users to chat from their laptops without switching between devices.
This shows Google’s increasing focus on a connected ecosystem.
 Overall, Android 13 brought further personalization through Material You, stronger security
controls, and better support for large screens and audio features. It helped refine and improve
the Android experience across different device types, setting the stage for the future of multi-
device collaboration and connected ecosystems.

Android Version 14 (API 34)


Android 14 was released on October 4, 2023. Android 14 builds upon the foundations of
personalization and device connectivity established by earlier versions, enhancing performance,
accessibility, and multi-device functionality. With deeper customizations and smarter features,

Page | 13
Android 14 aims to offer a seamless and efficient user experience. Following are the features of the
Android 14:
 More Customizable Lock Screen: Android 14 introduces lock screen customizations,
allowing users to personalize their lock screen with different clock styles, fonts, and widget
placements, making the phone feel even more unique.
 Improved Battery Efficiency: Battery life enhancements continue in Android 14, with
improved power management, especially for apps running in the background. This helps
devices last longer on a single charge by reducing energy consumption for background tasks.
 Advanced Accessibility: Android 14 expands on accessibility features with enhanced screen
readers, better magnification options, and non-verbal communication tools, making it easier
for users with disabilities to navigate the system.
 Satellite Connectivity Support: For the first time, Android 14 adds support for satellite-
based communication, enabling emergency messaging in areas with no cellular coverage.
This is a significant move toward improving communication in remote locations.
 App Cloning: Android 14 officially allows app cloning, which lets users run two instances
of the same app with different accounts, such as using two WhatsApp accounts on the same
device. This is a great feature for people balancing personal and work life on one phone.
 Faster and More Secure Updates: Google Play System Updates have been further
enhanced, allowing quicker and more frequent updates for security patches and system
components without needing full OS upgrades.
 Health Connect Integration: Android 14 integrates Health Connect, a centralized hub for
all fitness and health data, making it easier to manage health-related apps and share data
between them seamlessly.
 Fun Fact: The Android 14 Easter Egg features a space-themed puzzle game where users
collect “space sweets” (a nod to Android’s sweet treat naming history), as Android 14 is also
internally known as “Upside Down Cake.”
 Fun Fact: Android 14 introduces emoji wallpaper generation! Users can create custom
wallpapers filled with their favourite emojis in various patterns and styles, adding a fun
touch to device personalization.

Android Architecture
Android architecture contains a different number of components to support any Android device’s
needs. Android software contains an open-source Linux Kernel having a collection of a number of
C/C++ libraries which are exposed through application framework services. Among all the
components Linux Kernel provides the main functionality of operating system functions to
smartphones and Dalvik Virtual Machine (DVM) provide a platform for running an Android
application.

Components of Android Architecture


The main components of Android architecture are the following:-
 Applications
Page | 14
 Application Framework
 Android Runtime
 Platform Libraries
 Linux Kernel
Pictorial representation of Android architecture with several main components and their sub-
components

Understanding Android’s architecture is essential for building efficient applications. For those
looking to master this structure and move from beginner to advanced skills in Kotlin, the Android
Mastery with Kotlin: Beginner to Advanced course offers a comprehensive guide

1. Applications
Applications is the top layer of android architecture. The pre-installed applications like home,
contacts, camera, gallery etc and third party applications downloaded from the play store like chat
applications, games etc. will be installed on this layer only. It runs within the Android run time with
the help of the classes and services provided by the application framework.

Page | 15
2. Application framework
Application Framework provides several important classes which are used to create an Android
application. It provides a generic abstraction for hardware access and also helps in managing the
user interface with application resources. Generally, it provides the services with the help of which
we can create a particular class and make that class helpful for the Applications creation. It includes
different types of services activity manager, notification manager, view system, package manager
etc. which are helpful for the development of our application according to the prerequisite.

3. Application runtime
Android Runtime environment is one of the most important part of Android. It contains components
like core libraries and the Dalvik virtual machine(DVM). Mainly, it provides the base for the
application framework and powers our application with the help of the core libraries. Like Java
Virtual Machine (JVM), Dalvik Virtual Machine (DVM) is a register-based virtual machine and
specially designed and optimized for android to ensure that a device can run multiple instances
efficiently. It depends on the layer Linux kernel for threading and low-level memory management.
The core libraries enable us to implement android applications using the standard JAVA or Kotlin
programming languages.

Note: Now, starting from Android 5.0 and above, we use ART (Android Runtime) to compile
bytecode into native code to leverage ahead-of-time compilation.

4. Platform libraries
The Platform Libraries includes various C/C++ core libraries and Java based libraries such as
Media, Graphics, Surface Manager, OpenGL etc. to provide a support for android development.
 Media library provides support to play and record an audio and video formats.
 Surface manager responsible for managing access to the display subsystem.

Page | 16
 SGL and OpenGL both cross-language, cross-platform application program interface (API)
are used for 2D and 3D computer graphics.
 SQLite provides database support and FreeType provides font support.
 Web-Kit This open source web browser engine provides all the functionality to display web
content and to simplify page loading.
 SSL (Secure Sockets Layer) is security technology to establish an encrypted link between a
web server and a web browser.

5. Linux Kernel
Linux Kernel is heart of the android architecture. It manages all the available drivers such as display
drivers, camera drivers, Bluetooth drivers, audio drivers, memory drivers, etc. which are required
during the runtime. The Linux Kernel will provide an abstraction layer between the device hardware
and the other components of android architecture. It is responsible for management of memory,
power, devices etc. The features of Linux kernel are:
 Security: The Linux kernel handles the security between the application and the system.
 Memory Management: It efficiently handles the memory management thereby providing
the freedom to develop our apps.
 Process Management: It manages the process well, allocates resources to processes
whenever they need them.
 Network Stack: It effectively handles the network communication.
 Driver Model: It ensures that the application works properly on the device and hardware
manufacturers responsible for building their drivers into the Linux build.

Other Commonly Used Architectures in Android


There are few commonly used Android Architectures used mentioned below:
Page | 17
1. MVC ( Model View Controller )
MVC or Model View Controller breaks the model into three main components Model that stores the
application data , View UI layer that holds the component visible on the screen and Controller that
establishes the relationship between Model and the View.

2. MVP ( Model View Presenter )


To avoid complexities like maintainability, readability, scalability, and refactoring of applications we
use MVP model. The basic working of this model relies of the points mentioned below:
 Communication between the View-Presenter and Presenter-Model happens with the help of
Interface (also called Contract).
 There is One to One relationship between Presenter and View , One Presenter Class only
manages One View at a time.
 Model and View doesn’t have any knowledge about each other.

3. MVVM ( Model View ViewModel ) :


MVVM or Model View ViewModel as the name suggest like MVC model it contains three
components too Model , View and ViewModel. Features of MVVM model are mentioned below:
 ViewModel does not hold any kind of reference to the View.
 Many to-1 relationships exist between View and ViewModel.
 No triggering methods to update the View.
And we can achieve this using 2 methods:
 Using DataBinding library of Google.
 Using Tools like RxJava for Data Binding.

Benefits of Architecture
Using Architecture solves many problems for us few of them are:
 Improves the Maintainability , quality and robustness of the application
 Scalability of the Application is increased using Architecuture as , users and developers bot
the engamenents on the application can be increased.
 Testing of Application gets easy because of it.
 Bugs can be identified and removed easily with the well defined process.

Android System Architecture


The Android software stack generally consists of a Linux kernel and a collection of C/C++ libraries
that are exposed through an application framework that provides services, and management of the
applications and run time.

Linux Kernel
Page | 18
Android was created on the open-source kernel of Linux. One main reason for choosing this kernel
was that it provided proven core features on which to develop the Android operating system. The
features of the Linux kernel are:
1. Security: The Linux kernel handles the security between the application and the system.
2. Memory Management: It efficiently handles memory management thereby providing the
freedom to develop our apps.
3. Process Management: It manages the process well and allocates resources to processes
whenever they need them.
4. Network Stack: It effectively handles network communication.
5. Driver Model: It ensures that the application works. Hardware manufacturers can build their
drivers into the Linux build.

Libraries:
Running on top of the kernel, the Android framework was developed with various features. It
consists of various C/C++ core libraries with numerous open-source tools. Some of these are:
1. The Android Runtime: The Android runtime consists of core libraries of Java and ART(the
Android RunTime). Older versions of Android (4.x and earlier) had Dalvik runtime.
2. Open GL(graphics library): This cross-language, cross-platform application program interface
(API) is used to produce 2D and 3D computer graphics.
3. WebKit: This open-source web browser engine provides all the functionality to display web
content and simplify page loading.
4. Media frameworks: These libraries allow you to play and record audio and video.
5. Secure Socket Layer (SSL): These libraries are there for Internet security.

Android Runtime
It is the third section of the architecture. It provides one of the key components which is called
Dalvik Virtual Machine. It acts like Java Virtual Machine which is designed especially for Android.
Android uses its own custom VM designed to ensure that multiple instances run efficiently on a
single device.
The Dalvik VM uses the device’s underlying Linux kernel to handle low-level functionality,
including security, threading, and memory management.

Application Framework
The Android team has built on a known set of proven libraries, built in the background, and all of it
is exposed through Android interfaces. These interfaces wrap up all the various libraries and make
them useful for the Developer. They don’t have to build any of the functionality provided by the
android. Some of these interfaces include:
1. Activity Manager: It manages the activity lifecycle and the activity stack.
2. Telephony Manager: It provides access to telephony services as related subscriber information,
such as phone numbers.
Page | 19
3. View System: It builds the user interface by handling the views and layouts.
4. Location manager: It finds the device’s geographic location.

Applications:
Android applications can be found at the topmost layer. At the application layer, we write our
application to be installed on this layer only. Examples of applications are Games, Messages,
Contacts, etc.

Android System Stack


The Android system stack is a layered architecture that organizes the components of the Android
operating system. It ensures efficient interaction between hardware and software components. The
stack is divided into the following layers:

1. Linux Kernel

 The core layer of Android, based on the Linux kernel.


 Provides essential system services like:
o Process Management: Handles multitasking and process lifecycle.
o Memory Management: Efficiently allocates system memory.
o Security: Enforces permissions and user access.
o Hardware Drivers: For devices like Wi-Fi, Bluetooth, cameras, and audio.
o Power Management: Optimizes battery usage.

2. Hardware Abstraction Layer (HAL)

 Sits between the Linux kernel and Android runtime/framework.


 Provides standard interfaces for hardware-specific implementations.
 Ensures developers interact with hardware using APIs without writing driver code.
 Examples:
o Camera HAL
o Sensor HAL
o Audio HAL

3. Android Runtime (ART)

 Replaces the earlier Dalvik Virtual Machine (DVM) for improved performance.
 Key Features:
o Ahead-of-Time (AOT) Compilation: Compiles app code into machine code during
installation, reducing runtime execution overhead.
o Garbage Collection (GC): Optimizes memory management.
o Includes a set of Core Java Libraries for app development.

4. Native Libraries

 Written in C/C++, they provide low-level system functionalities:


o SurfaceFlinger: Manages rendering and display compositing.
o OpenGL/ES: Renders 2D/3D graphics.
Page |
210
o Media Framework: Handles audio, video, and media file playback.
o WebKit: Manages web rendering.
o SQLite: Provides database support for app data storage.

5. Android Framework

 Provides high-level APIs for app development.


 Manages core services, including:
o Activity Manager: Oversees app lifecycle and navigation.
o Content Providers: Share data between applications.
o Notification Manager: Manages status bar notifications.
o Package Manager: Handles app installation and updates.
o Location Manager: Provides GPS and location-based services.

6. Application Layer

 The topmost layer where user-facing apps reside.


 Includes:
o Pre-installed apps (e.g., Phone, Contacts, Messages).
o Third-party apps downloaded via the Play Store.
 Apps interact with the system via the Android Framework.

Diagram of the Android System Stack

Here’s a textual representation of the stack diagram:

+ +
| Applications | <-- User-installed and pre-installed apps
+ +
| Android Framework | <-- APIs for UI, lifecycle, notifications
+ +
| Native Libraries | <-- Media, SQLite, SurfaceFlinger, OpenGL
| Android Runtime | <-- ART & Core Libraries
+ +
| Hardware Abstraction | <-- Hardware interaction interfaces
+ +
| Linux Kernel | <-- Drivers, memory, process, security
+ +

SDK Overview
The Software Development Kit (SDK) is a collection of tools, libraries, and APIs for Android
application development.

Android SDK is a collection of libraries and Software Development tools that are essential for
Developing Android Applications. Whenever Google releases a new version or update of Android
Software, a corresponding SDK also releases with it. In the updated or new version of SDK, some
more features are included which are not present in the previous version. Android SDK consists of
some tools which are very essential for the development of Android Application. These tools
provide a smooth flow of the development process from developing and debugging. Android SDK is
compatible with all operating systems such as Windows, Linux, macOS, etc.

Page |
211
Key Features:

 Development Tools: APIs for accessing Android-specific features like UI components,


sensors, and storage.
 Platform Compatibility: Develop apps compatible with multiple Android versions and
devices.
 Debugging and Testing: Tools to test apps in real-world scenarios without physical devices.

Components:

1. SDK Tools: Command-line utilities for building, debugging, and deploying apps (e.g., ADB,
Fastboot).
2. Platform Tools: APIs for different Android versions.
3. System Images: Emulator images for testing apps on virtual devices.

Platforms
1. Mobile Devices

Android’s Mobile Platform is the primary platform for smartphones and tablets. It’s the most
widely used platform, with billions of devices running on Android worldwide.

Key Features:

1. Touch Gestures:
o Touchscreen interfaces support multiple gestures like taps, swipes, and pinch-to-
zoom.
o Apps must adapt to user input for smooth interaction.
2. Adaptive Layouts:
o Supports flexible layouts that adapt to various screen sizes and resolutions.
o Android provides layout types like ConstraintLayout, LinearLayout, and
RelativeLayout to create responsive UIs.
3. Sensors & Hardware:
o Android devices include various sensors like Accelerometers, Gyroscopes, GPS,
Proximity Sensors, and Ambient Light Sensors, allowing for rich, context-aware
applications.
4. App Distribution:
o Most apps are distributed via Google Play Store, which is the official marketplace
for Android applications. Developers can monetize their apps via ads, in-app
purchases, and paid downloads.

Example Use Case:

 Mobile Games: Apps like Pokémon GO utilize GPS, accelerometer, and gyroscope sensors
to enhance gameplay.

2. Wear OS (Smartwatches)
Page | 22
Wear OS is a version of Android tailored for smartwatches and wearables, such as Fitbit, Samsung
Galaxy Watch, and Google Pixel Watch.

Key Features:

1. Circular User Interface:


o Apps must optimize for small, circular screens.
o The Wearable UI follows Google's Material Design guidelines for wearables.
2. Fitness and Health Tracking:
o Wear OS supports APIs for monitoring health metrics, including heart rate, steps,
calories burned, and activity tracking.
o Integration with Google Fit allows developers to access health data across apps.
3. Notifications and Voice Integration:
o Wear OS focuses on quick notifications and voice-based commands via Google
Assistant.
o Apps often support quick replies to messages or commands like "Set an alarm" using
voice recognition.
4. Battery Optimization:
o Battery life is a concern for wearables. Apps must be optimized for minimal battery
consumption.

Example Use Case:

 Fitness Tracker Apps like Google Fit or Strava that track users' exercise and daily activity.

3. Android TV

Android TV is the version of Android optimized for television screens. It enables users to access
streaming apps, games, and services on big-screen TVs.

Key Features:

1. Leanback Interface:
o The Leanback Library provides UI components designed for easy navigation on
large screens with remote controls.
o It simplifies app layouts for media-centric apps (e.g., video streaming, music).
2. Google Play Store Integration:
o Apps from the Google Play Store are optimized for the TV screen, ensuring a
smooth viewing experience.
o TV apps generally focus on video streaming, games, and utilities.
3. Controller Input:
o Instead of touch, input on Android TV is done using remote controls, gamepads, or
voice commands.
4. Google Assistant:
o Google Assistant allows users to interact with Android TV via voice commands for
tasks like searching for content or controlling the TV.

Example Use Case:

Page | 23
 Streaming Apps: Netflix, YouTube, and Disney+ on Android TV are examples where
users can watch content directly on the TV screen.

4. Android Auto

Android Auto is the version of Android designed for in-car infotainment systems. It offers users an
interface that integrates with their vehicle’s dashboard for hands-free operation.

Key Features:

1. Driver Safety:
o Android Auto focuses on reducing distractions while driving. The interface is simple
and includes large icons and voice commands.
o Google Assistant allows drivers to perform tasks like navigation and controlling
music without taking their hands off the wheel.
2. Navigation Integration:
o Provides turn-by-turn navigation through Google Maps or third-party apps like
Waze.
o Integrates real-time traffic data, routes, and alerts for a better navigation experience.
3. Media and Messaging:
o Supports media apps like Spotify, YouTube Music, and Pandora.
o Allows users to send and receive text messages via voice commands, enhancing
hands-free functionality.
4. Voice Control:
o Voice commands are heavily utilized, with features like “Call [Contact Name]” or
“Play [Song Name]”.

Example Use Case:

 Navigation Apps: Google Maps on Android Auto for real-time GPS guidance, lane
guidance, and traffic updates.

5. Android Things (IoT)

Android Things is a version of Android designed for Internet of Things (IoT) devices such as smart
appliances, security cameras, smart speakers, and more.

Key Features:

1. Embedded Systems:
o Android Things runs on embedded hardware and offers low-level access to sensors,
display devices, and other hardware.
2. IoT Connectivity:
o It supports Wi-Fi, Bluetooth, and other wireless protocols to connect IoT devices to
the cloud and other smart devices.
3. Google Assistant Integration:

Page | 24
o Android Things integrates with Google Assistant, enabling voice commands for
devices (e.g., “Turn off the lights”).
4. Security:
o Android Things includes built-in security measures to protect IoT devices from
vulnerabilities and unauthorized access.

Example Use Case:

 Smart Home Devices: A smart thermostat like Nest that can adjust temperature settings
based on voice commands or app control.

Diagram of Android Platforms:


+ +
| Android Mobile | --> For smartphones and tablets.
+ +
|
+ +
| Wear OS | --> For smartwatches and wearables.
+ +
|
+ +
| Android TV | --> For TV and large screen displays.
+ +
|
+ +
| Android Auto | --> For in-car systems and infotainment.
+ +
|
+ +
| Android Things (IoT) | --> For IoT devices like smart appliances.
+ +

Conclusion:

Each Android platform is designed with specific use cases in mind, and developers must tailor their
apps for the unique features and constraints of each platform. Whether it's optimizing for the small
screen of a smartwatch or creating intuitive controls for in-car use, Android offers versatile
platforms that support a wide array of devices, allowing developers to reach diverse audiences.

Tools
1. Java Development Kit (JDK)

The JDK is essential for Android development as it provides the environment to compile and
execute Java code, which is used for developing Android applications.

Key Components:

Page | 25
1. Compiler (javac): Converts Java source code (.java files) into bytecode (.class files),
which is executed by the Android runtime.
Example:

bash
Copy code
javac [Link]

2. Runtime Environment (JRE): Provides the libraries and tools to execute Java programs.
Android Studio relies on the JDK to compile Java/Kotlin code into DEX (Dalvik Executable)
files.
3. Development Tools:
o javadoc: Generates documentation from Java code comments.
o jarsigner: Signs .jar or .apk files to ensure code integrity.

Importance in Android:

 Required to compile Java-based Android applications.


 Ensures compatibility with Android's Java libraries and runtime.

2. Android Studio

Android Studio is the official Integrated Development Environment (IDE) for Android
development, created by Google.

Features:

1. Code Editor:
o Syntax highlighting, code completion, and error detection for Java, Kotlin, and XML.
2. UI Design Tools:
o Drag-and-drop Layout Editor for building responsive UIs.
o Supports modern layouts like ConstraintLayout for adaptive screen designs.
3. Debugger:
o Step-by-step debugging tools to locate and fix runtime errors.
4. Performance Profiler:
o Monitors CPU, memory, and network usage to optimize app performance.
5. Gradle Integration:
o Automates project builds, manages dependencies, and generates APKs/AABs for
deployment.

Advantages:

 Tailored for Android with built-in support for SDK tools.


 Frequent updates to align with the latest Android versions and features.

3. SDK (Software Development Kit)

Page | 26
The Android SDK is a collection of tools, libraries, and APIs required to build, test, and debug
Android apps.

Components:

1. SDK Tools:
o Command-line utilities like ADB (Android Debug Bridge) and Fastboot for device
communication and debugging.
2. Build Tools:
o Tools like aapt (Android Asset Packaging Tool) to compile resources and generate
APKs.
3. Platform Tools:
o APIs and libraries for different Android versions.
4. Extras:
o Google Play services and additional libraries for app compatibility.

Workflow:

 Install using Android Studio’s SDK Manager.


 Use SDK tools to compile and test apps in a simulated or physical environment.

4. ADT (Android Development Tools)

The ADT Plugin was an extension for Eclipse IDE to support Android app development (now
deprecated).

Features:

1. UI Designer: Drag-and-drop tools to design layouts visually.


2. Emulator Integration: Seamless interaction with Android Virtual Devices (AVDs).
3. Build System: Tools to compile, debug, and package APKs directly within Eclipse.

Importance:

 ADT was widely used before Android Studio.


 Provided a unified platform for coding, designing, and testing apps.

Drawbacks:

 Limited compared to modern tools.


 Deprecated in favor of Android Studio.

5. AVD (Android Virtual Device)

An AVD is a configuration for creating a virtual Android device emulator.

Features:
Page | 27
1. Device Profiles:
o Customizable screen size, resolution, and hardware specifications.
2. Android Versions:
o Emulate any Android version to test app compatibility.
3. Hardware Simulation:
o Test hardware features like GPS, camera, and sensors.

Importance:

 Eliminates the need for physical devices during development.


 Allows testing on different device configurations to ensure compatibility.

Example Use Case:

 Simulate location data to test a navigation app.

6. Android Emulator

The Android Emulator executes AVD configurations to simulate an Android device on a PC.

Features:

1. Hardware Features:
o Simulate calls, SMS, and battery levels.
2. Gesture Controls:
o Supports multi-touch gestures like zoom and swipe using a mouse.
3. Performance Testing:
o Test apps under different conditions (e.g., low memory, slow networks).

Benefits:

 Saves time and resources by avoiding reliance on physical devices.


 Enables real-time testing and debugging.

Limitations:

 Can be slower than testing on physical devices, especially for resource-intensive apps.

Version 1.6
Android Version 1.6 (Donut) was released in September 2009 and is considered one of the early
versions of Android. It introduced several important features that laid the groundwork for future
Android releases. Here’s a detailed explanation of Android 1.6 Donut:

Page | 28
Overview of Android 1.6 (Donut)

Android 1.6, codenamed Donut, was released in September 2009. It was a major update after
Android 1.5 Cupcake and came with several improvements to the operating system, including
enhanced features for the camera, gallery, search, and performance.

Key Features and Enhancements in Android 1.6 (Donut)

1. Improved Search Functionality:


o Android 1.6 enhanced the search functionality by introducing a global search bar at
the top of the screen, allowing users to search for content within apps, contacts, web,
and even within the device.
o The search box provided quicker access to apps, contacts, and even text within apps.
2. Gallery and Camera Enhancements:
o The Gallery app was revamped to support zooming in and out of photos with multi-
touch gestures.
o Camera was upgraded with the ability to zoom in and out during photo capture.
o The video recording feature was introduced for the first time in Android, allowing
users to record video directly from the camera app.
3. Updated Android Market:
o Android 1.6 brought changes to the Android Market, making it easier to browse and
search for apps. The update provided developers with access to additional categories
and better organization in the Market.
4. CDMA Support:
o Android 1.6 Donut introduced support for CDMA networks (Code Division
Multiple Access), which allowed Android to be used on more carriers beyond GSM
networks, such as Verizon in the U.S.
5. Improved Speed and Performance:
o Android 1.6 provided optimizations to the underlying system, improving
performance and providing smoother animations.
o It included a faster UI and better application performance, which was crucial for user
experience on older hardware.
6. Text-to-Speech Engine:
o Android 1.6 introduced a Text-to-Speech engine that enabled apps to read out text.
This was particularly useful for accessibility purposes and future use cases like
navigation.
7. Support for More Screen Resolutions:
o Android 1.6 supported more screen resolutions, including WVGA (800x480) and
QVGA (240x320), which improved the user experience across a wider variety of
devices.
8. Battery and Power Management:
o Enhanced power management, improving the battery life of Android devices.
o The system also optimized background processing, reducing unnecessary battery
drain.
9. New API Level:
o Android 1.6 introduced API Level 4, which allowed developers to access additional
system functionality and tools.
10. Voice Search:

Page | 29
o Voice search was integrated for the first time in Android 1.6. It enabled users to
search for content using voice commands, providing an alternative to traditional
typing.

Android 1.6 Donut - API Changes

 API Level 4: The introduction of API Level 4 opened up new functionalities for developers.
o Camera APIs for capturing videos and photos.
o Gesture Detection: Support for gestures like pinch-to-zoom.
o Enhanced Media Capabilities: Media APIs to support audio and video streaming.
o Improved Location APIs: Improved location services to offer more accurate
location-based apps.

Device Support and Compatibility

Android 1.6 Donut extended support for various screen resolutions and hardware types, paving
the way for future devices with higher-resolution displays and more powerful hardware. Some of the
early Android smartphones such as HTC Hero and Motorola Droid ran Android 1.6.

User Interface Enhancements

 Faster and More Responsive UI: Android 1.6 featured a smoother interface, with more
responsive transitions between screens and a more polished user experience.
 Updated Widgets: The widgets were more interactive and provided additional functionality
like direct interaction with the home screen.

Conclusion

Android 1.6 (Donut) was an important release that improved upon many of the basic features
introduced in Android 1.5 (Cupcake). It enhanced functionality for the camera, media, and search,
laid the foundation for better support of different screen sizes and resolutions, and expanded
Android's compatibility with more networks (e.g., CDMA).

Although Android 1.6 is outdated today, its introduction of features like video recording, voice
search, and enhanced media support marked significant steps forward for the platform.

Creating your first Android Application


Creating your first Android application involves several steps. Below is a detailed guide for
beginners to get started with Android development using Android Studio, the official IDE for
Android development.

Page |
310
Prerequisites

1. Install Android Studio:


o Download and install Android Studio from the official website.
o Ensure you have the latest version of the Java Development Kit (JDK) installed.
2. Set up Android Studio:
o Configure the SDK, Emulator, and required tools during installation.
3. Basic Knowledge:
o Familiarity with Java/Kotlin programming languages.
o Understanding of XML for designing layouts.

Step-by-Step Guide

Step 1: Create a New Project

1. Open Android Studio and click on "New Project".


2. Choose a project template:
o For a basic app, select Empty Activity and click Next.
3. Configure your project:
o Name: Enter a name for your app (e.g., MyFirstApp).
o Package Name: Choose a unique identifier (e.g., [Link]).
o Save Location: Choose a directory for your project files.
o Language: Select Java or Kotlin.
o Minimum API Level: Choose the lowest Android version your app will support.
4. Click Finish, and Android Studio will set up the project.

Step 2: Understand the Project Structure

Your project will have the following structure:

1. Manifest File ([Link]):


o Contains app metadata like app permissions, activities, and app name.
2. Java/Kotlin Files (/java):
o Code logic for your application.
3. Resources (/res):
o Layout (/layout): XML files for app UI.
o Drawable (/drawable): Images and visual resources.
o Values (/values): Strings, styles, and colors.
4. Gradle Files:
o Used for building the app and managing dependencies.

Step 3: Design the UI

1. Open activity_main.xml in the res/layout folder.


2. Use the Layout Editor to drag and drop UI components like buttons, text views, etc.
Page |
311
o Example Layout XML:

<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="18sp" />

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

Step 4: Write Code for Functionality

1. Open [Link] or [Link] in the /java folder.


2. Add logic to respond to button clicks.
o Example in Java:

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

TextView textView = findViewById([Link]);


Button button = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View v) {
[Link]("Button Clicked!");
}
});
}
}

Step 5: Run the Application

Page | 32
1. Set up an Emulator:
o Go to Tools > AVD Manager.
o Create a virtual device with your desired specifications.
o Launch the emulator.
2. Run the App:
o Click the Run button (green play icon) in Android Studio.
o Choose the connected emulator or a physical device.
o Android Studio will compile the app and install it on the selected device.

Step 6: Test and Debug

1. Test the app by interacting with the UI.


2. Use the Logcat tool to view logs and debug issues.

Diagram: Android App Development Workflow


[Create Project] --> [Design UI (XML)] --> [Write Logic (Java/Kotlin)]
| | |
[Run App] <-- [Debugging Tools (Logcat)] <-- [AVD/Physical Device]

Step 7: Build and Share

1. Build APK:
o Go to Build > Build Bundle(s)/APK(s) > Build APK(s).
o The APK file can be shared and installed on other devices.
2. Deploy to Play Store:
o Sign the APK and upload it to the Google Play Console for distribution.

Conclusion

Congratulations! You've created your first Android app. With this foundational knowledge, you can
expand into more complex features like using databases, integrating APIs, and building multi-screen
applications. Let me know if you need more help!

Page | 33
Page | 34
UNIT - 2
Android User Interface
The Android User Interface (UI) is the way users interact with Android applications. It includes the layout of
screens, components like buttons and text boxes, and the overall look and feel of the app. Android provides
a robust framework and tools for designing and implementing user interfaces.

Components of Android User Interface

1. View:
o
A View is the basic building block of the UI, representing a rectangular area of the
screen.
o Examples: TextView, Button, ImageView, etc.
2. ViewGroup:
o A ViewGroup is a container that holds multiple views or other ViewGroups.
o Examples: LinearLayout, RelativeLayout, ConstraintLayout, etc.

Android UI Layouts

Android layouts define the structure and placement of UI elements on the screen.

1. LinearLayout:
o Arranges elements in a single row (horizontal) or column (vertical).
o Example:

<LinearLayout
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!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>

2. RelativeLayout:
o Places elements relative to each other or the parent layout.
o Example:

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"

Page | 35
android:layout_height="wrap_content"
android:text="Button 1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button1"
android:text="Button 2" />
</RelativeLayout>

3. ConstraintLayout:
o Provides a more flexible and efficient way to arrange elements by creating
constraints.
o Example:

<ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="Centered Button" />
</ConstraintLayout>

4. FrameLayout:
o Displays a single view or stacks views on top of each other.
5. GridLayout:
o Arranges elements in a grid format.

UI Widgets

Widgets are the interactive elements of the Android UI. Below are commonly used widgets:

1. TextView:
o Displays text to the user.
o Example:

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="18sp" />

2. EditText:
o Allows users to input text.
o Example:

<EditText
android:layout_width="match_parent"

Page | 36
android:layout_height="wrap_content"
android:hint="Enter your name" />

3. Button:
o Responds to user clicks.
o Example:

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />

4. ImageView:
o Displays images.
o Example:

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/sample_image" />

5. Checkbox:
o Allows users to select multiple options.
o Example:

<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check me" />

6. RadioButton:
o Lets users select one option from a group.
o Example:

<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2" />
</RadioGroup>

User Interaction

1. Event Listeners:
o Handles user interactions, like button clicks or text input.
o Example of a Button click listener in Java:

Button button = findViewById([Link]);


[Link](new [Link]() {

Page | 37
@Override
public void onClick(View v) {
// Perform action on click
}
});

2. Toast Messages:
o Displays brief messages.
o Example:

[Link](getApplicationContext(), "Button Clicked!",


Toast.LENGTH_SHORT).show();

3. Dialogs:
o Displays alerts or additional options to the user.
o Example:

new [Link](this)
.setTitle("Alert")
.setMessage("Are you sure?")
.setPositiveButton("Yes", null)
.setNegativeButton("No", null)
.show();

Designing UI Using XML

Android separates the design and logic by defining the UI in XML files under the res/layout folder.
This separation allows developers to focus on the visual design independently of the app's
functionality.

Previewing the UI

Android Studio includes a Design Editor where you can:

 Drag and drop UI components.


 Preview layouts on different screen sizes and resolutions.

UI Customization

1. Themes and Styles:


o Themes define the overall look of the app (e.g., dark mode).
o Styles customize individual widgets.
2. Responsive Design:
o Android supports multiple layouts for different screen sizes using resource qualifiers
like layout-large or layout-small.
3. Animations:
o Add animations using the Animator API or XML-based transitions.

Page | 38
Conclusion

The Android User Interface is a powerful framework that combines flexibility, responsiveness, and
interactivity. By leveraging layouts, widgets, and event listeners, developers can create visually
appealing and user-friendly applications. As you advance, you can explore complex UI patterns,
animations, and custom views to enhance the user experience.

Understanding the Components of an Android Screen


An Android screen comprises several components that work together to provide an intuitive and
interactive user interface. These components can be categorized into visual elements (what the user
sees) and logical components (how the system processes actions). Below is a detailed breakdown of
the components:

1. Visual Components (UI Elements)

a. App Bar (Toolbar or Action Bar)

 Located at the top of the screen.


 Provides navigation, branding, and action-related features.
 Common features include:
o App title/logo.
o Navigation buttons (e.g., back or hamburger menu).
o Action icons (e.g., search, settings).
 Example in XML:

<[Link]
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:title="My App" />

b. Content Area

 The central part of the screen where most user interaction occurs.
 Includes views like:
o TextView: Displays text.
o ImageView: Displays images.
o Buttons: Perform actions.
o RecyclerView: Displays lists or grids.
 Example Layout:

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

Page | 39
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to My App" />

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

c. Navigation Bar

 Typically located at the bottom of the screen.


 Used for primary navigation within the app.
 Types of navigation:
o Bottom Navigation Bar: Tabs for switching between main sections.
o Navigation Drawer: A sliding menu accessed via the hamburger icon.
 Example of Bottom Navigation:

<[Link]
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:menu="@menu/navigation_menu" />

d. Status Bar

 Displays system-level information like:


o Network connectivity.
o Battery status.
o Notifications.
 Customizable using themes and system UI controls.

2. Logical Components (Functionality and Interaction)

a. Activities

 Represents a single screen in an app.


 Acts as the entry point for user interaction with the app.
 Example: A login page or a dashboard.

b. Fragments

 A modular section of the UI that can be reused within activities.


 Allows dynamic UI changes without switching activities.
 Example: A tabbed interface.

Page |
410
c. Intents

 Handles navigation between activities or external apps.


 Types:
o Explicit Intent: Opens a specific activity.
o Implicit Intent: Requests an action from other apps.
 Example:

Intent intent = new Intent(this, [Link]);


startActivity(intent);

3. Supporting Components

a. Layouts

 Define the structure and arrangement of UI elements.


 Types of layouts:
o LinearLayout: Aligns elements horizontally or vertically.
o ConstraintLayout: Provides flexible positioning with constraints.
o FrameLayout: Stacks elements.

b. Widgets

 Interactive UI elements.
o Example: Buttons, Checkboxes, Text Inputs, etc.

c. Menus

 Provide options and actions for the user.


 Types:
o Options Menu: Accessed via the toolbar.
o Context Menu: Accessed by long-pressing an element.
o Popup Menu: Displays temporary options.

4. Event Handling and User Interaction

a. Event Listeners

 Respond to user actions like clicks, swipes, or text input.


 Example of a Button Click Listener:

Button button = findViewById([Link]);


[Link](new [Link]() {
@Override
public void onClick(View v) {
[Link](getApplicationContext(), "Button Clicked!",
Toast.LENGTH_SHORT).show();
}
});

b. Gesture Detection
Page |
411
 Detects gestures like tap, swipe, or pinch.
 Example: Swipe detection for navigating between pages.

5. Customization and Themes

a. Themes

 Define the overall look and feel of the app.


 Customizable attributes:
o Colors.
o Fonts.
o Icons.
 Example in [Link]:

<style name="AppTheme" parent="[Link]">


<item name="colorPrimary">#3F51B5</item>
<item name="colorPrimaryDark">#303F9F</item>
<item name="colorAccent">#FF4081</item>
</style>

b. Animations

 Enhance user experience with transitions and effects.


 Example of fade animation in XML:

<alpha
xmlns:android="[Link]
android:duration="500"
android:fromAlpha="0.0"
android:toAlpha="1.0" />

Diagram: Android Screen Components

| Status Bar |

| App Bar |

| |
| Content Area |
| (Text, Buttons, Images) |
| |

| Navigation Bar |

Conclusion

Understanding the components of an Android screen is crucial for designing user-friendly


applications. By effectively using visual and logical components, developers can create responsive,
dynamic, and interactive apps tailored to user needs.

Page | 42
Views and ViewGroups in Android
In Android, Views and ViewGroups are the fundamental building blocks of the user interface. They
define how UI components are displayed and how users interact with them.

What is a View?

A View represents a single rectangular area on the screen and is responsible for drawing and
handling user interactions. It is the base class for all UI components like buttons, text fields, images,
and more.

The View class is the base class or we can say that it is the superclass for all the GUI components in
android. For example, the EditText class is used to accept the input from users in android apps,
which is a subclass of View, and another example of the TextView class which is used to display
text labels in Android apps is also a subclass of View.

Or the other definition,

View refer to the [Link] class, which is the base class of all UI classes.
[Link] class is the root of the UI class hierarchy. So from an object point of view, all UI
objects are View objects. Following are some of the common View subclasses that will be used in
android applications.

 TextView
 EditText
 ImageView
 RadioButton
 Button
 ImageButton
 CheckBox
 DatePicker
 Spinner
 ProgressBar and etc.

These are some of the view subclass available in android.

Commonly Used Views

1. TextView:
o Displays text to the user.
o Example:

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="18sp" />
Page | 43
2. EditText:
o Accepts user input as text.
o Example:

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name" />

3. Button:
o Performs an action when clicked.
o Example:

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

4. ImageView:
o Displays an image.
o Example:

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/sample_image" />

5. CheckBox:
o Allows the user to select multiple options.
o Example:

<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I agree to the terms and conditions" />

What is a ViewGroup?

A ViewGroup is a container that holds other Views (or ViewGroups). It defines how child views
are arranged on the screen. It is the base class for layouts like LinearLayout, RelativeLayout, and
ConstraintLayout.

The ViewGroup class is a subclass of the View class. And also it will act as a base class for layouts
and layouts parameters. The ViewGroup will provide an invisible container to hold other Views or
ViewGroups and to define the layout properties. For example, Linear Layout is the ViewGroup that
contains UI controls like Button, TextView, etc., and other layouts also. ViewGroup Refer to
the [Link] class, which is the base class of some special UI classes that can
contain other View objects as children. Since ViewGroup objects are also View objects, multiple
ViewGroup objects and View objects can be organized into an object tree to build a complex UI
structure. Following are the commonly used ViewGroup subclasses used in android applications.
Page | 44
 FrameLayout
 WebView
 ListView
 GridView
 LinearLayout
 RelativeLayout
 TableLayout and many more.

The ViewGroup subclasses listed above group View instances together and takes care of their
layout. For instance, the LinearLayout will render the components after each other either
horizontally or vertically.

Commonly Used ViewGroups

1. LinearLayout:
o Arranges child views in a single row (horizontal) or column (vertical).
o Example:

<LinearLayout
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="Welcome!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>

2. RelativeLayout:
o Arranges child views relative to each other or the parent container.
o Example:

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView

Page | 45
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:text="Click Me" />
</RelativeLayout>

3. ConstraintLayout:
o Provides a flexible way to arrange views by defining constraints relative to other
views or the parent.
o Example:

<ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:text="Click Me" />
</ConstraintLayout>

4. FrameLayout:
o Designed to display a single view or stack views on top of each other.
o Example:

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/background" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Overlay Text"
android:gravity="center" />
</FrameLayout>

5. RecyclerView:
o Displays large sets of data efficiently as a scrollable list or grid.
o Commonly used for lists with dynamic content.

Hierarchy of Views and ViewGroups

 Views and ViewGroups form a tree-like structure.


 Example hierarchy for a simple app:

Page | 46
ConstraintLayout (ViewGroup)
├── TextView (View)
├── Button (View)
└── ImageView (View)

Key Differences Between Views and ViewGroups

Aspect View ViewGroup


Definition Represents a single UI element. Acts as a container for other Views or
ViewGroups.
Purpose Handles UI display and user Defines the layout and arrangement of its
interactions. children.
Examples TextView, Button, EditText, LinearLayout, RelativeLayout, FrameLayout.
ImageView.
Positioning Can be placed within a ViewGroup. Defines rules for positioning its children.

Event Handling

 Views can handle user interactions like clicks, swipes, and gestures.
 Example of handling a click event for a Button:

Button button = findViewById([Link]);


[Link](new [Link]() {
@Override
public void onClick(View v) {
[Link](getApplicationContext(), "Button Clicked!",
Toast.LENGTH_SHORT).show();
}
});

Diagram: Example Hierarchy of Views and ViewGroups


ConstraintLayout (ViewGroup)
├── LinearLayout (ViewGroup)
│ ├── TextView (View)
│ ├── Button (View)
│ └── EditText (View)
└── ImageView (View)

Page | 47
Conclusion

Views and ViewGroups are essential for designing Android applications. By understanding their
roles and how to use them effectively, developers can create intuitive and responsive user interfaces.

Difference Table

View ViewGroup

View is a simple rectangle box that ViewGroup is the invisible container. It holds
responds to the user’s actions. View and ViewGroup

ViewGroup is a collection of Views(TextView,


View is the SuperClass of All component
EditText, ListView, etc..), somewhat like a
like TextView, EditText, ListView, etc
container.

A View object is a component of the user A ViewGroup object is a layout, that is, a
interface (UI) like a button or a text box, container of other ViewGroup objects (layouts)
and it’s also called a widget. and View objects (widgets)

Examples are EditText, Button, CheckBox, For example, LinearLayout is the ViewGroup that
etc. contains Button(View), and other Layouts also.

ViewGroup refers to the [Link]


View refers to the [Link] class
class

[Link] which is the base class


ViewGroup is the base class for Layouts.
of all UI classes.

Page | 48
LinearLayout, AbsoluteLayout, TableLayout, RelativeLayout,
FrameLayout, ScrollLayout, and ScrollView in Detail
In Android, layouts are used to arrange UI components in a structured and visually appealing way.
Here’s an in-depth explanation of each layout with examples and key attributes:

1. LinearLayout

 Description: Arranges child views in a single direction, either horizontally or vertically.


 Key Attributes:
o orientation: Defines the direction (horizontal or vertical).
o layout_weight: Allocates space proportionally among child views.
o gravity: Aligns child views within the parent.
 Use Case: Stacking elements in a linear sequence.
 Example:

<LinearLayout
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="Welcome!" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>

2. AbsoluteLayout (Deprecated)

 Description: Places child views at absolute positions using X and Y coordinates.


 Key Attributes:
o layout_x and layout_y: Specifies the exact position of child views.
 Use Case: When precise positioning is needed (not recommended for modern apps).
 Example:

<AbsoluteLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_x="50dp"
android:layout_y="100dp"
android:text="Button 1" />

<Button

Page | 49
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_x="200dp"
android:layout_y="200dp"
android:text="Button 2" />
</AbsoluteLayout>

3. TableLayout

 Description: Arranges child views in rows and columns, similar to a table.


 Key Attributes:
o stretchColumns: Allows specified columns to expand to fill unused space.
o shrinkColumns: Allows columns to shrink to fit content.
 Use Case: Building forms or structured grids.
 Example:

<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>

<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age:" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>

4. RelativeLayout

 Description: Positions child views relative to each other or the parent container.
 Key Attributes:
o layout_above, layout_below, layout_toLeftOf, layout_toRightOf: Position
views relative to others.
o layout_alignParentTop, layout_alignParentBottom: Align views with the
parent edges.
 Use Case: Complex UI arrangements with dynamic positioning.
 Example:

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
Page |
510
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:text="Click Me" />
</RelativeLayout>

5. FrameLayout

 Description: Designed to hold a single child view or stack multiple views.


 Key Attributes:
o layout_gravity: Defines how child views are positioned within the container.
 Use Case: Overlaying elements, such as adding text over an image.
 Example:

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/sample_image" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Overlay Text"
android:textColor="#FFFFFF" />
</FrameLayout>

6. ScrollLayout (Deprecated)

 Description: An older scrolling container replaced by ScrollView and


HorizontalScrollView.
 Key Attributes: Similar to ScrollView.
 Use Case: Basic scrolling (replaced by ScrollView for better performance and flexibility).

7. ScrollView

 Description: Enables vertical scrolling for content that exceeds the screen height.
 Key Attributes:
o fillViewport: Expands child views to fill the available space.
 Use Case: Long content, like a list or a form.
Page |
511
 Example:

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">

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

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

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

</LinearLayout>
</ScrollView>

8. HorizontalScrollView

 Description: Enables horizontal scrolling of its content.


 Key Attributes:
o Similar to ScrollView, but scrolls horizontally.
 Use Case: When content extends horizontally beyond the screen width.
 Example:

<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">

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

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

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

</LinearLayout>
</HorizontalScrollView>
Page | 52
Comparison of Layouts

Layout Description Use Case


LinearLayout Arranges views in a row or column. Simple stacked elements.
Positions views by X and Y coordinates
AbsoluteLayout Avoid using for modern apps.
(deprecated).
Forms or grid-like
TableLayout Organizes views in rows and columns.
arrangements.
Positions views relative to others or
RelativeLayout Flexible and dynamic layouts.
parent.
Overlaying elements like text
FrameLayout Stacks views on top of each other.
on images.
ScrollLayout Enables scrolling (deprecated). Replaced by ScrollView.
Content exceeding screen
ScrollView Adds vertical scrolling to content.
height.
HorizontalScrollView Adds horizontal scrolling. Content wider than the screen.

Diagram: Layout Hierarchy


Parent ViewGroup (e.g., ScrollView)
└── Child ViewGroup (e.g., LinearLayout)
├── TextView
├── Button
└── EditText

Conclusion

Choosing the right layout is crucial for designing user-friendly and performant Android applications.
While some layouts like AbsoluteLayout and ScrollLayout are deprecated, alternatives like
RelativeLayout, ScrollView, and LinearLayout offer modern solutions for building responsive
and adaptive interfaces.

Adapting to Display Orientation in Android


Android applications are used on devices that can switch between two primary orientations:
Portrait and Landscape. Adapting your app’s layout to different orientations ensures a smooth and
user-friendly experience. Below is an in-depth look at how to handle display orientation changes
effectively.

1. Display Orientations

 Portrait Orientation: The height of the screen is greater than the width.
Page | 53
 Landscape Orientation: The width of the screen is greater than the height.

2. Challenges with Orientation Changes

When the orientation changes, the activity is destroyed and recreated by default. This can cause:

 Loss of user data (e.g., input in forms).


 Layout issues due to lack of optimized resources.
 Performance overhead during activity recreation.

3. Adapting to Orientation Changes

To handle orientation changes effectively, Android provides several tools and techniques:

A. Using Separate Layout Resources

 Android allows developers to define different layouts for different orientations by creating
resource directories.
 Steps:
1. Place a layout for portrait mode in the res/layout/ folder.
2. Place a layout for landscape mode in the res/layout-land/ folder.
 Example:
o res/layout/activity_main.xml (Portrait):

<LinearLayout
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="Portrait Mode" />
</LinearLayout>

o res/layout-land/activity_main.xml (Landscape):

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Landscape Mode" />
</LinearLayout>

B. Handling Configuration Changes Programmatically

Page | 54
 To prevent activity recreation during orientation change, declare the configChanges
attribute in the manifest.
 Manifest Declaration:

<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize">
</activity>

 In Code: Override the onConfigurationChanged method in your activity:

override fun onConfigurationChanged(newConfig: Configuration) {


[Link](newConfig)

if ([Link] == Configuration.ORIENTATION_LANDSCAPE) {
[Link](this, "Landscape mode", Toast.LENGTH_SHORT).show()
} else if ([Link] ==
Configuration.ORIENTATION_PORTRAIT) {
[Link](this, "Portrait mode", Toast.LENGTH_SHORT).show()
}
}

C. Retaining Data Using ViewModel

 Use the ViewModel class to retain data across orientation changes without recreating the
activity.
 Example:

class MyViewModel : ViewModel() {


var userData: String = ""
}

o In the activity:

val viewModel: MyViewModel by viewModels()

D. Saving and Restoring State

 Save the activity state before orientation changes and restore it after.
 Example:

override fun onSaveInstanceState(outState: Bundle) {


[Link](outState)
[Link]("KEY", "Some Data")
}

override fun onCreate(savedInstanceState: Bundle?) {


[Link](savedInstanceState)
val restoredData = savedInstanceState?.getString("KEY")
}

E. Using ConstraintLayout for Flexible Layouts

Page | 55
 ConstraintLayout is highly adaptable and eliminates the need for separate layouts.
 Use constraints to define relationships between views so they adjust automatically to
orientation changes.

4. Testing Orientation Adaptation

 Steps to Test:
1. Rotate the emulator or physical device to observe layout behavior.
2. Use the Layout Inspector in Android Studio to preview layouts in both orientations.

5. Diagram: Orientation Change Workflow

| User Rotates Device |


| Activity Destroyed (onDestroy) |


| Activity Recreated (onCreate) |

6. Best Practices

 Avoid hardcoding dimensions; use match_parent, wrap_content, and dp.


 Use flexible layouts like ConstraintLayout.
 Retain critical data using ViewModel or onSaveInstanceState.
 Provide optimized layouts for both orientations if necessary.

Conclusion

Adapting to display orientation is essential for a seamless user experience. By using tools like
resource qualifiers, handling configuration changes, and employing flexible layouts, developers can
create responsive and dynamic Android applications.

Anchoring Views
Anchoring views is a fundamental concept in Android UI development, ensuring that views
maintain a consistent position relative to their parent container or other views, regardless of screen
size or orientation.

1. Introduction

Page | 56
 Definition: Anchoring means positioning views with respect to the edges of the screen, other
views, or within a container.
 Purpose: Helps in creating flexible and responsive layouts that adapt seamlessly to different
screen sizes and orientations.

2. Key Components

Anchoring is typically achieved using layout attributes and specific layout managers such as
RelativeLayout and ConstraintLayout.

Attributes for Anchoring:

1. Relative to Parent:
o layout_alignParentStart, layout_alignParentEnd: Aligns the view to the
parent's start or end.
o layout_alignParentTop, layout_alignParentBottom: Aligns the view to the
parent's top or bottom.
o layout_centerHorizontal, layout_centerVertical: Centers the view
horizontally or vertically in the parent.
2. Relative to Sibling Views:
o layout_toStartOf, layout_toEndOf: Places a view to the start or end of another
view.
o layout_above, layout_below: Places a view above or below another view.
o layout_alignBaseline: Aligns the baseline of a view with another view.

3. Examples and Use Cases

Example 1: Anchoring to Parent

This ensures a button is always displayed at the bottom-right corner of the screen.

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="Anchored Button" />
</RelativeLayout>

Example 2: Anchoring to Sibling Views

This places one button below another and centers it horizontally.

<RelativeLayout
android:layout_width="match_parent"

Page | 57
android:layout_height="match_parent">

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Button 1" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button1"
android:layout_centerHorizontal="true"
android:text="Button 2" />
</RelativeLayout>

Example 3: ConstraintLayout (Recommended)

This layout is more versatile and allows precise anchoring.

<[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="Anchored TextView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/textView"
app:layout_constraintStart_toStartOf="parent"
android:text="Button Below TextView" />
</[Link]>

4. Importance

1. Responsive Design:
o Ensures views adapt to different screen sizes and orientations.
2. Flexibility:
o Simplifies complex UI designs by maintaining relative positioning.
3. Consistency:
o Avoids overlap and disorganization in UI layouts.

5. Common Challenges

 Incorrect Anchoring: Misaligned views if incorrect attributes are used.


 Overlapping Views: Occurs in improper sibling relationships.

Page | 58
 Performance: Overuse of nested layouts can reduce rendering performance.

6. Diagram

A visual representation of a RelativeLayout showing anchored views:

| Header | (layout_alignParentTop)

| TextView | (layout_centerHorizontal)

| Button | (layout_alignParentBottom)

7. Advanced Concepts

1. Adaptive UI:
o Use ConstraintLayout for dynamic constraints based on screen size.
2. Relative Anchoring:
o Combine multiple attributes like layout_toEndOf and layout_below for complex
designs.
3. RTL (Right-to-Left) Support:
o Use layout_alignParentStart instead of layout_alignParentLeft for
compatibility with RTL languages.

8. Conclusion

Anchoring views is essential for creating dynamic and adaptive layouts. Proper understanding and
implementation of anchoring attributes ensure your app is responsive, visually appealing, and user-
friendly across all devices and orientations.

Resizing and Repositioning


Resizing and repositioning are crucial techniques in Android development for creating flexible,
adaptive, and user-friendly layouts. These approaches ensure that UI components adjust dynamically
to varying screen sizes, resolutions, and orientations.

1. Introduction

 Resizing: Adjusting the size of UI elements to fit the available space.


 Repositioning: Moving UI elements to appropriate locations within a layout in response to
screen changes or constraints.

Page | 59
2. Importance

 User Experience: Maintains visual consistency and usability across devices.


 Device Compatibility: Supports a wide range of screen sizes and resolutions.
 Accessibility: Ensures UI elements remain accessible without manual scrolling or zooming.

3. Techniques for Resizing

1. Dynamic Dimensions:
o Use match_parent or wrap_content instead of fixed pixel values.

<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Dynamic Button" />

o Benefits:
 Prevents clipping or unnecessary whitespace.
 Ensures elements expand or shrink as needed.
2. Weighted Layouts (LinearLayout):
o Assign weights to distribute space proportionally.

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

<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1" />

<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button 2" />
</LinearLayout>

3. Scalable Resources:
o Use dp for dimensions and sp for text sizes for consistent scaling.
o Define scalable resources in res/values/[Link]:

<dimen name="button_margin">16dp</dimen>

4. ConstraintLayout:
o Adjust dimensions dynamically using constraints like match_constraint.

<[Link]
android:layout_width="match_parent"
android:layout_height="wrap_content">

<ImageView
Page |
610
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:src="@drawable/sample_image" />
</[Link]>

4. Techniques for Repositioning

1. Relative Positioning:
o Use attributes like layout_above, layout_below, layout_toStartOf, and
layout_toEndOf in RelativeLayout.

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/label"
android:text="Repositioned Button" />
</RelativeLayout>

2. Anchoring in ConstraintLayout:
o Position elements relative to each other or the parent container.

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="Top Left Button" />

3. Responsive Design:
o Use percent-based dimensions with PercentRelativeLayout or custom solutions.
4. Grid Layouts:
o Position elements systematically within a grid:

<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="2">

<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:text="Button 1" />

Page |
611
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:text="Button 2" />
</GridLayout>

5. Adapting to Screen Size and Orientation

1. Resource Qualifiers:
o Create separate layout files for different screen sizes:
 res/layout/ for default layouts.
 res/layout-large/ for large screens.
 res/layout-land/ for landscape orientation.
2. Orientation-Aware Design:
o Dynamically reposition elements using onConfigurationChanged:

override fun onConfigurationChanged(newConfig: Configuration) {


[Link](newConfig)
if ([Link] ==
Configuration.ORIENTATION_LANDSCAPE) {
// Adjust UI for landscape
} else {
// Adjust UI for portrait
}
}

6. Best Practices

 Use ConstraintLayout as the primary layout for flexibility.


 Avoid hardcoding pixel values; instead, rely on scalable units like dp and sp.
 Test layouts on multiple screen sizes using Android Emulator or real devices.
 Use Android Studio’s Layout Inspector and Preview tools for debugging.

7. Diagram

Resizing and Repositioning in ConstraintLayout

+ +
| Parent Layout |
| + + |
| | Top TextView | |
| + + |
| ↓ |
| + + + + |
| | Button 1 | | Button 2 | |
| + + + + |
| |
+ +

Page | 62
8. Conclusion

Resizing and repositioning ensure that your Android application’s user interface is responsive,
accessible, and visually appealing across various devices and orientations. By leveraging the right
layouts and attributes, developers can create scalable and adaptive designs that cater to diverse user
experiences.

Managing Changes to Screen Orientation


Managing changes to screen orientation is a key aspect of Android development. Screen orientation
changes, such as switching between portrait and landscape, can have a significant impact on the
layout and functionality of an app. Handling these changes properly ensures a smooth user
experience and prevents potential issues like loss of data or app crashes.

1. Introduction

When the user rotates their device, Android re-creates the activity by default to adjust the UI for the
new orientation. This can lead to inefficiency if not handled correctly, as the app may lose important
information (like user input or app state). Proper management of orientation changes involves
preserving UI states, handling resource changes, and ensuring that the app performs efficiently
during these transitions.

2. Default Behavior on Orientation Change

By default, when the device’s orientation changes:

 Android destroys and recreates the Activity: The current instance of the activity is
destroyed and a new instance is created.
 OnCreate() is called again: The activity's lifecycle method onCreate() is invoked,
requiring the app to set up the UI again.

3. Managing Orientation Changes

a. Saving and Restoring State

To preserve the UI state during an orientation change, developers can use the following techniques:

1. onSaveInstanceState()
o This method is called before the activity is destroyed (i.e., when the orientation
changes). It allows the developer to save temporary data (such as text input or scroll
position) to a Bundle.
o Example:

Page | 63
@Override
public void onSaveInstanceState(Bundle outState) {
[Link](outState);
[Link]("key", "Some value to preserve");
}

2. onRestoreInstanceState()
o This method is called after the activity is recreated. It allows the developer to restore
the saved data from the Bundle.
o Example:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
[Link](savedInstanceState);
String value = [Link]("key");
}

b. Using android:configChanges to Handle Configuration Changes

If the activity doesn't need to be recreated during an orientation change, you can use the
android:configChanges attribute in the [Link] file. This tells the system to
handle the configuration change itself without restarting the activity.

 Example:

<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden">
</activity>

 This will stop the activity from being destroyed and recreated on orientation change, and will
call onConfigurationChanged() instead.

c. onConfigurationChanged()

 onConfigurationChanged() is a callback method that is called when the device


configuration changes (including orientation changes). This method is useful when you do
not want to recreate the activity and want to handle the changes manually.
 Example:

@Override
public void onConfigurationChanged(Configuration newConfig) {
[Link](newConfig);
if ([Link] == Configuration.ORIENTATION_LANDSCAPE) {
// Handle landscape orientation changes
} else if ([Link] ==
Configuration.ORIENTATION_PORTRAIT) {
// Handle portrait orientation changes
}
}

4. Using Fragments for Handling Orientation Changes

Page | 64
Fragments are a powerful tool for managing UI components and can help in preserving UI state
across orientation changes.

 Retaining Fragment State: You can use the setRetainInstance(true) method to keep a
fragment's state across orientation changes, without recreating the fragment.
o Example:

if (savedInstanceState == null) {
Fragment fragment = new MyFragment();
[Link](true);
getSupportFragmentManager().beginTransaction()
.replace([Link].fragment_container, fragment)
.commit();
}

5. Managing Layouts for Different Orientations

Layouts should be optimized for both portrait and landscape orientations. Android provides a system
for handling layout resources for different configurations:

1. res/layout/: Default layout for the device.


2. res/layout-land/: Layout for landscape orientation.
3. res/layout-port/: Layout for portrait orientation.
4. res/values/[Link]: Texts and strings can also be customized for different orientations.

 Example:
o Portrait Layout (res/layout/activity_main.xml):

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- UI components for portrait -->
</LinearLayout>

o Landscape Layout (res/layout-land/activity_main.xml):

<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- UI components optimized for landscape -->
</LinearLayout>

6. Best Practices for Managing Orientation Changes

1. Use onSaveInstanceState and onRestoreInstanceState for preserving activity data.


2. Use configChanges carefully: If you do not want the activity to be recreated, use
android:configChanges in the [Link], but be mindful that you must
handle all changes manually (like screen size, locale, keyboard).
3. Avoid Storing Large Data in Instance State: Large data (such as bitmaps or complex data
structures) should not be saved in the instance state as it can lead to inefficiency.
Page | 65
4. Utilize Fragments for Reusable UI: Use fragments to manage UI components that need to
be preserved or adjusted for both orientations.
5. Create Separate Layouts for Different Orientations: Design different layouts for portrait
and landscape orientations using resource directories like res/layout-land/.

7. Diagram: Orientation Change Lifecycle

Here is a simple flow of the activity lifecycle during an orientation change:

+ +
| Initial State |
| Activity Created |
+ +
|
v
+ +
| Orientation Change |
| Activity Destroyed |
| onSaveInstanceState() |
+ +
|
v
+ +
| New Activity Created |
| onCreate() |
| onRestoreInstanceState()|
+ +
|
v
+ +
| Updated UI |
+ +

8. Conclusion

Managing changes to screen orientation is a critical part of Android development, ensuring that apps
remain functional and visually consistent across all screen orientations. By carefully saving and
restoring state, using configChanges wisely, and employing fragments and appropriate layouts,
developers can create responsive, user-friendly applications that perform well across a range of
devices and orientations.

Persisting State Information during Changes in Configuration


In Android, changes in configuration, such as screen rotations, orientation changes, language
settings, or keyboard visibility, can affect the activity lifecycle. If not managed properly, such
changes may lead to loss of state information or result in inefficient reloading of data.

Persisting state information during configuration changes is essential to enhance the user experience
by preventing the app from losing valuable data such as user inputs, scroll positions, and temporary
states during configuration changes.

Page | 66
1. Introduction

Configuration changes in Android typically lead to activity recreation. By default, when a


configuration change (like orientation change) occurs, the current activity is destroyed and recreated,
causing the loss of data and UI state.

To avoid this, Android provides mechanisms to persist the state information and restore it after the
configuration change. This allows for smoother transitions and better app performance.

2. Key Concepts

 Configuration Changes: These include screen size changes, orientation changes, locale
changes, font size, or keyboard visibility changes.
 Persisting State: Refers to saving and restoring the necessary state of an app (e.g., user
input, UI components) during configuration changes.
 Activity Lifecycle: Understanding the activity lifecycle is crucial for handling state
persistence. Key methods involved in managing state persistence during configuration
changes include onSaveInstanceState(), onRestoreInstanceState(), and
onConfigurationChanged().

3. Mechanisms for Persisting State

a. onSaveInstanceState() and onRestoreInstanceState()

1. onSaveInstanceState():
o This method is called before an activity is destroyed, allowing you to save the current
state (e.g., form inputs, scroll positions, or any temporary data) into a Bundle.
o Example:

@Override
public void onSaveInstanceState(Bundle outState) {
[Link](outState);
[Link]("userInput", [Link]().toString());
}

2. onRestoreInstanceState():
o This method is called when the activity is recreated (after a configuration change)
and allows you to restore the saved state from the Bundle.
o Example:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
[Link](savedInstanceState);
String userInput = [Link]("userInput");
[Link](userInput);
}

Page | 67
Usage: This approach works well for saving small, temporary data that does not involve complex
objects or large resources.

b. Using ViewModels for State Persistence (Recommended)

ViewModel is a lifecycle-aware component that stores and manages UI-related data. It is part of the
Android Architecture Components and is designed specifically for persisting UI-related data during
configuration changes. A ViewModel is retained during configuration changes, meaning the data
within it is preserved even when the activity is recreated.

 Example:

public class MyViewModel extends ViewModel {


private MutableLiveData<String> userInput = new MutableLiveData<>();

public MutableLiveData<String> getUserInput() {


return userInput;
}

public void setUserInput(String input) {


[Link](input);
}
}

 Using ViewModel in Activity:

public class MainActivity extends AppCompatActivity {


private MyViewModel myViewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

myViewModel = new ViewModelProvider(this).get([Link]);


final EditText editText = findViewById([Link]);

[Link]().observe(this, new Observer<String>() {


@Override
public void onChanged(String s) {
[Link](s);
}
});

[Link](new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
[Link]([Link]());
}
// Other required methods omitted
});
}
}

Advantages:

Page | 68
 ViewModels survive configuration changes without the need for manual state saving and
restoring.
 They provide a clean separation of UI and data handling, improving the architecture of the
app.

c. SharedPreferences for Persisting State

For small, persistent data (such as user settings, preferences, or simple form inputs),
SharedPreferences is often used. It allows for easy storage of key-value pairs, which can be
retrieved and used after the activity is recreated.

 Example:

// Saving data
SharedPreferences sharedPreferences =
getSharedPreferences("MyPreferences", MODE_PRIVATE);
[Link] editor = [Link]();
[Link]("userName", [Link]().toString());
[Link]();

// Retrieving data
SharedPreferences sharedPreferences =
getSharedPreferences("MyPreferences", MODE_PRIVATE);
String userName = [Link]("userName", "");
[Link](userName);

Use Cases:

 Store small preferences, user settings, or other simple data.


 Suitable for data that doesn’t need to be tied to UI elements or doesn’t require complex
structures.

d. Database Persistence (for Larger Data)

For more complex or large datasets (e.g., user entries, product information, etc.), Room Database or
SQLite can be used. These solutions allow for robust data storage that persists even when activities
are destroyed and recreated due to configuration changes.

 Room Database Example:

@Entity(tableName = "user_table")
public class User {
@PrimaryKey
private int id;
private String name;

// Getters and setters


}

@Dao
public interface UserDao {

Page | 69
@Insert
void insert(User user);
@Query("SELECT * FROM user_table")
List<User> getAllUsers();
}

@Database(entities = {[Link]}, version = 1)


public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}

 Usage:
o Store and manage large or complex data, ensuring that it is not lost when the
configuration changes.

4. Handling Configuration Changes with onConfigurationChanged()

If you prefer not to recreate the activity during a configuration change (such as an orientation
change), you can handle these changes manually by overriding the onConfigurationChanged()
method.

 Manifest Configuration:

<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|screenSize">
</activity>

 Handling Changes:

@Override
public void onConfigurationChanged(Configuration newConfig) {
[Link](newConfig);
if ([Link] == Configuration.ORIENTATION_LANDSCAPE) {
// Handle landscape mode
} else if ([Link] ==
Configuration.ORIENTATION_PORTRAIT) {
// Handle portrait mode
}
}

Considerations:

 Only use onConfigurationChanged() for cases where activity recreation is not desirable,
as it can lead to more complex code management.

5. Best Practices for Persisting State Information

1. Use ViewModel for UI-Related Data: ViewModel is the recommended approach for
preserving UI-related data like user input, selections, or current screen position during
configuration changes.
Page |
710
2. Use onSaveInstanceState() for Temporary Data: Save simple, short-lived data (such as
input text or scroll positions) in the onSaveInstanceState() method.
3. Use SharedPreferences for Small Settings: For settings or small user data, store it in
SharedPreferences for easy retrieval.
4. Use Room Database or SQLite for Persistent Data: For large or complex data that needs
to be persisted across app launches, use a database like Room or SQLite.
5. Be Mindful of Performance: Avoid saving large objects (like images) in
onSaveInstanceState() as it can negatively impact performance.

6. Conclusion

Persisting state information during configuration changes is crucial for maintaining a smooth and
reliable user experience in Android applications. By using mechanisms like
onSaveInstanceState(), ViewModel, SharedPreferences, and databases, developers can ensure
that their app maintains state across orientation changes and other configuration changes, while
avoiding unnecessary resource usage or data loss.

Detecting Orientation Changes in Android


Detecting orientation changes is a common requirement in Android development, as it allows
developers to adjust the user interface (UI) and functionality based on the device’s orientation
(portrait or landscape). The process involves identifying when a device's orientation changes and
responding accordingly to maintain a smooth user experience.

1. Introduction

Android provides built-in mechanisms to detect orientation changes and handle them. When a user
rotates the device, the configuration changes (such as screen orientation) trigger the system to
recreate the current activity by default. Developers can manage these changes by detecting
orientation transitions and ensuring the app adapts to the new configuration without losing the data
or causing layout issues.

2. Default Behavior During Orientation Changes

By default, when the orientation changes (from portrait to landscape or vice versa), Android
destroys and recreates the current activity to load resources tailored for the new orientation. This
may involve:

 Recalling the activity lifecycle, including onCreate(), onStart(), and onResume().


 Destroying and recreating the UI elements based on the resources defined in the
corresponding layout files (like res/layout for portrait or res/layout-land for
landscape).

Page |
711
While this behavior ensures the layout is updated for the new orientation, it may cause the loss of
temporary data or user inputs unless developers manage this state properly.

3. Methods to Detect Orientation Changes

a. Using the Configuration Object

Android provides the Configuration class to detect changes in device configuration, including
orientation changes. This can be done in the onConfigurationChanged() method of an activity,
which gets called when the configuration changes, including when the orientation changes.

 Example:

@Override
public void onConfigurationChanged(Configuration newConfig) {
[Link](newConfig);
if ([Link] == Configuration.ORIENTATION_LANDSCAPE) {
// Handle landscape mode
Log.d("Orientation", "Landscape mode");
} else if ([Link] == Configuration.ORIENTATION_PORTRAIT) {
// Handle portrait mode
Log.d("Orientation", "Portrait mode");
}
}

In this approach, instead of destroying and recreating the activity, the app adjusts to the orientation
change within the onConfigurationChanged() method.

 Manifest Configuration: To ensure that the activity does not restart when the orientation
changes, developers need to declare the activity in the AndroidManifest file with the
configChanges attribute.

<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|screenSize">
</activity>

This tells Android not to recreate the activity and instead call onConfigurationChanged() to
manage the change manually.

b. Using onSaveInstanceState() and onRestoreInstanceState()

Another way to handle orientation changes is by saving and restoring the activity’s state during the
transition. This can help you retain important data, such as user inputs, when the activity is
destroyed and recreated.

1. Saving the state (onSaveInstanceState()):


o This method is invoked before the activity is destroyed and allows you to store
temporary data in a Bundle that can be restored later.

Page | 72
o Example:

@Override
public void onSaveInstanceState(Bundle outState) {
[Link](outState);
[Link]("inputText", [Link]().toString());
}

2. Restoring the state (onRestoreInstanceState()):


o This method is called after the activity is recreated. The saved state is restored from
the Bundle.
o Example:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
[Link](savedInstanceState);
String inputText = [Link]("inputText");
[Link](inputText);
}

c. Managing Layouts for Different Orientations

One of the simplest ways to detect and handle orientation changes is by using different layouts for
portrait and landscape modes. Android allows developers to define separate resources for different
configurations:

1. Default Layout (res/layout): The default layout used when the app is in portrait mode.
2. Landscape Layout (res/layout-land): The layout used when the device is in landscape
mode.

When the device is rotated, Android automatically loads the appropriate layout based on the current
configuration. This approach makes it easy to provide distinct UI designs tailored for different
orientations.

 Example:
o Portrait Layout (res/layout/activity_main.xml):

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Portrait-specific UI components -->
</LinearLayout>

o Landscape Layout (res/layout-land/activity_main.xml):

<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Landscape-specific UI components -->
</LinearLayout>

Page | 73
d. Manually Detecting Orientation Changes Using Sensors

For more advanced control, developers can also use the device’s sensors (accelerometer and
magnetic field sensor) to detect orientation changes manually. This can be useful when the app
needs to react to orientation changes without triggering the activity lifecycle methods.

 Example:

SensorManager sensorManager = (SensorManager)


getSystemService(SENSOR_SERVICE);
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if ([Link]() == Sensor.TYPE_ACCELEROMETER) {
float x = [Link][0];
float y = [Link][1];
if ([Link](x) > [Link](y)) {
// Landscape detected
} else {
// Portrait detected
}
}
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
};

[Link](sensorEventListener,
[Link](Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);

While this method offers fine-grained control over detecting orientation, it requires a better
understanding of sensor data and can be less efficient than using Android's built-in configuration
detection mechanisms.

4. Best Practices for Handling Orientation Changes

1. Use Orientation-Aware Layouts: Define separate layouts for portrait and landscape
orientations using the res/layout and res/layout-land resource directories. This is a
straightforward and effective way to provide different user interfaces for each orientation.
2. Preserve State: Use onSaveInstanceState() and onRestoreInstanceState() to
preserve temporary data (e.g., text inputs, scroll positions) when the activity is recreated.
This is important for providing a seamless user experience during orientation changes.
3. Avoid Recreating the Activity: If the app doesn’t need to be recreated during orientation
changes, use the configChanges attribute in the AndroidManifest to prevent activity
recreation and handle changes manually using onConfigurationChanged().
4. Use ViewModels for Persistent UI Data: For more complex data that needs to persist
across configuration changes, consider using Android’s ViewModel component, which is
lifecycle-aware and retains data through orientation changes without needing to save it
manually.

Page | 74
5. Test Across Devices: Ensure that the app behaves correctly across various screen sizes and
orientations. Android devices vary widely in form factors, so it’s important to test orientation
changes on different screen sizes and configurations.

5. Conclusion

Detecting and handling orientation changes is a crucial part of Android development. By


understanding and using the right mechanisms like onConfigurationChanged(),
onSaveInstanceState(), and layout management, developers can ensure that their apps maintain
smooth user experiences during orientation transitions. Whether it’s saving temporary data, adapting
layouts, or preventing unnecessary activity recreation, detecting orientation changes effectively
improves the app's usability across different devices and orientations.

Adding Action Items to the Action Bar in Android


The Action Bar (or App Bar) is an essential UI component in Android applications, providing key
actions, navigation options, and app branding. It usually sits at the top of the screen and can contain
elements such as titles, icons, and menu items. One of the main features of the Action Bar is the
ability to add action items, which are interactive elements such as buttons or icons that users can
click to trigger various app functionalities.

This section will explain how to add action items to the Action Bar, how to handle user interaction
with these items, and best practices for implementing action items in Android apps.

1. Introduction to Action Items

Action items are typically added to the Action Bar in the form of:

 Icons: These are graphical elements that represent actions, like search, settings, or favorite.
 Text Items: These are textual representations of actions, usually displayed in a menu
dropdown.
 Overflow Menu: If the Action Bar cannot fit all the items on screen (especially for smaller
screens), extra items are placed in an overflow menu (represented by three vertical dots or a
similar icon).

Adding action items provides users with easy access to key features of the application without
cluttering the screen.

2. Steps to Add Action Items to the Action Bar

To add action items, you will need to define them in your activity or fragment, and then specify how
they should behave when the user interacts with them.

a. Modifying the res/menu XML File

Page | 75
The first step is to define your action items in a menu resource file. This file is typically located in
the res/menu directory. Here, you define the items (icons or text) you want to add to the Action Bar.

Example: Creating a simple menu with action items (res/menu/menu_main.xml):

<menu xmlns:android="[Link]
<!-- Action Item 1: Search Icon -->
<item
android:id="@+id/action_search"
android:title="Search"
android:icon="@drawable/ic_search"
android:orderInCategory="100"
android:showAsAction="ifRoom"/>

<!-- Action Item 2: Settings Icon -->


<item
android:id="@+id/action_settings"
android:title="Settings"
android:icon="@drawable/ic_settings"
android:orderInCategory="200"
android:showAsAction="ifRoom"/>

<!-- Overflow Menu Item -->


<item
android:id="@+id/action_help"
android:title="Help"
android:showAsAction="never"/>
</menu>

 Attributes:
o android:id: The unique ID for the item.
o android:title: The text to be displayed when the item is selected.
o android:icon: The icon representing the item.
o android:orderInCategory: The order of the item within the menu.
o android:showAsAction: This attribute defines when the item should appear in the
Action Bar (e.g., ifRoom, always, never).

showAsAction Values:

 ifRoom: Show the item in the Action Bar if there is room.


 always: Always show the item in the Action Bar.
 never: Never show the item in the Action Bar (instead, it appears in the overflow menu).

b. Inflating the Menu in Your Activity

Once the menu XML file is created, the next step is to inflate the menu in your activity or fragment
using the onCreateOptionsMenu() method. This method is called when the activity is created and
is responsible for adding the defined menu items to the Action Bar.

Example:

@Override
public boolean onCreateOptionsMenu(Menu menu) {

Page | 76
// Inflate the menu from the XML resource
getMenuInflater().inflate([Link].menu_main, menu);
return true;
}

In this code, the menu XML file (menu_main.xml) is inflated into the menu object, which adds the
action items to the Action Bar.

c. Handling Item Selection in onOptionsItemSelected()

Once the action items are added to the Action Bar, you need to handle user interactions with these
items. This is done by overriding the onOptionsItemSelected() method in your activity or
fragment.

Example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch ([Link]()) {
case [Link].action_search:
// Handle search action
openSearch();
return true;
case [Link].action_settings:
// Handle settings action
openSettings();
return true;
case [Link].action_help:
// Handle help action from overflow menu
openHelp();
return true;
default:
return [Link](item);
}
}

 getItemId(): Identifies the selected action item using its unique ID ([Link].action_search,
[Link].action_settings, etc.).
 openSearch(), openSettings(), and openHelp() represent methods where specific
functionality is executed based on the selected action item.

d. Displaying Action Items in the Overflow Menu

If there are too many items to fit on the Action Bar, some of them are placed in the overflow menu
(the "three dots" icon). You can control which items appear in the overflow menu by setting the
android:showAsAction="never" attribute in the menu XML, as shown in the previous example
with the action_help item.

3. Example of an Action Bar with Action Items


Page | 77
Below is a complete example of an Activity that adds action items to the Action Bar and handles
user selections:

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu from XML
getMenuInflater().inflate([Link].menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch ([Link]()) {
case [Link].action_search:
// Perform search operation
openSearch();
return true;
case [Link].action_settings:
// Open settings activity
openSettings();
return true;
case [Link].action_help:
// Show help information
openHelp();
return true;
default:
return [Link](item);
}
}

// Methods to handle each action item


private void openSearch() {
[Link](this, "Search clicked", Toast.LENGTH_SHORT).show();
}

private void openSettings() {


[Link](this, "Settings clicked", Toast.LENGTH_SHORT).show();
}

private void openHelp() {


[Link](this, "Help clicked", Toast.LENGTH_SHORT).show();
}
}

4. Best Practices for Action Bar Items

1. Limit Action Items: Avoid overwhelming the user with too many items in the Action Bar.
Prioritize the most important actions and place less critical ones in the overflow menu.
2. Use Icons for Clarity: Icons help users quickly understand the function of an action item.
Use clear, universally recognized icons to represent common actions like search, settings,
and navigation.

Page | 78
3. Keep Action Items Contextual: Only show action items that are relevant to the current
activity or fragment. Avoid showing too many irrelevant items that may confuse the user.
4. Ensure Accessibility: Ensure that the action items are accessible by providing descriptive
text for screen readers (via android:contentDescription), making your app more
inclusive for users with disabilities.

5. Conclusion

Adding action items to the Action Bar enhances the user experience by providing quick access to
key actions and features of your app. By using menu XML files, inflating them in the activity, and
handling user interactions, developers can create a smooth, responsive navigation system that adapts
to different screen sizes and orientations. Following best practices, such as limiting the number of
action items and using clear icons, will help you design an effective and user-friendly app.

Customizing the Action Items and Application Icon in Android


Customizing the Action Bar items and the application icon is crucial for improving the visual
appeal, branding, and usability of your Android application. This section covers how to modify the
Action Bar's action items and how to change the application's icon, ensuring that the app aligns with
the desired user experience and branding guidelines.

1. Customizing Action Items

The Action Bar (or App Bar) allows developers to customize the items displayed, including buttons,
text, and icons. Customization enables you to match the app's design with your branding or provide
a unique look and feel.

a. Changing the Appearance of Action Items

You can customize the look of action items by applying styles, icons, and even text. Here are some
common ways to do this:

1. Icons and Text for Action Items

You can define the appearance of action items (icons or text) using the menu XML files. You
can choose to display either icons, text, or both in the Action Bar based on your
requirements.

Example (menu XML):

<menu xmlns:android="[Link]
<!-- Action Item with an icon -->
<item
android:id="@+id/action_search"
android:title="Search"
android:icon="@drawable/ic_search"
android:orderInCategory="100"
android:showAsAction="ifRoom|withText"/>
Page | 79
<!-- Action Item with text only -->
<item
android:id="@+id/action_info"
android:title="Info"
android:showAsAction="never"/>
</menu>

o android:showAsAction:
 ifRoom: Displays the item as an icon if there's enough room in the Action
Bar.
 always: Forces the item to always appear in the Action Bar.
 never: Puts the item in the overflow menu (appears only when clicking the
overflow icon).
2. Customizing the Action Item with Styles

You can apply custom styles to action items. For example, changing the color of icons and
text can be done by modifying the style resources in res/values/[Link].

Example ([Link]):

<style name="CustomActionBar" parent="[Link]">


<item name="android:background">@color/colorPrimary</item>
<item name="android:titleTextStyle">@style/ActionBarTitle</item>
</style>

<style name="ActionBarTitle">
<item name="android:textColor">@android:color/white</item>
</style>

o Here, CustomActionBar style customizes the Action Bar’s background and title
color.

You can then apply this style in your activity or theme by modifying the
[Link] or [Link].

Example (in the AndroidManifest):

<application
android:theme="@style/CustomActionBar">
...
</application>

b. Adding Custom Action Items Dynamically

In addition to defining action items in XML files, you can add action items programmatically in
your activity using the Menu object. This is useful when you want to add or remove items
dynamically based on user actions or app state.

Example:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate([Link].menu_main, menu);
Page |
810
// Dynamically add a new action item
MenuItem dynamicItem = [Link]([Link], [Link].action_dynamic, [Link],
"Dynamic Item");
[Link]([Link].ic_dynamic);
[Link](MenuItem.SHOW_AS_ACTION_IF_ROOM);

return true;
}

In this example, we dynamically add a new menu item to the Action Bar.

c. Handling Custom Action Item Clicks

Once custom action items are added, you need to handle clicks on them. This is done by overriding
the onOptionsItemSelected() method.

Example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch ([Link]()) {
case [Link].action_search:
// Perform search operation
openSearch();
return true;
case [Link].action_dynamic:
// Perform custom operation
openDynamicAction();
return true;
default:
return [Link](item);
}
}

2. Customizing the Application Icon

The application icon is one of the most critical elements of an Android app, as it represents the app
on the home screen, app launcher, and task manager. Customizing the app icon helps with branding
and improves the app's visibility and identity.

a. Creating a Custom Icon

A good application icon should be simple, recognizable, and scalable. It should reflect your app’s
branding and purpose. The icon should be created in different sizes to support various screen
densities.

 Icon Sizes:
o hdpi: 72x72 pixels
o mdpi: 48x48 pixels
o xhdpi: 96x96 pixels
o xxhdpi: 144x144 pixels

Page |
811
o xxxhdpi: 192x192 pixels

You can create the icon using graphic design tools such as Adobe Illustrator, Photoshop, or online
tools like Android Asset Studio.

b. Adding the Application Icon

Once you’ve created your icon, place the icon files in the appropriate res/drawable directories for
different screen densities. Android automatically picks the correct icon size based on the device’s
screen resolution.

1. Place icons in the following directories:


o res/mipmap-mdpi/ic_launcher.png
o res/mipmap-hdpi/ic_launcher.png
o res/mipmap-xhdpi/ic_launcher.png
o res/mipmap-xxhdpi/ic_launcher.png
o res/mipmap-xxxhdpi/ic_launcher.png
2. Modify the [Link] file to point to your custom icon:

<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name">
...
</application>

The @mipmap/ic_launcher resource refers to the icon that will be used for the app on all devices.

c. Using Adaptive Icons (Android 8.0 and Above)

From Android 8.0 (API level 26) and onwards, Android introduced adaptive icons, which provide a
consistent look for all apps across different devices. Adaptive icons are composed of two layers:

1. Background Layer: A fixed image that serves as the background of the icon.
2. Foreground Layer: A layer that contains the main icon image or logo.

To create adaptive icons:

1. Create Two Layers: One for the background (a simple shape or color) and one for the
foreground (the app logo).
2. Use XML to Define Icon: In res/mipmap-anydpi/ic_launcher.xml, define your adaptive
icon using the adaptive-icon element.

Example (ic_launcher.xml):

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


<adaptive-icon xmlns:android="[Link]
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

 ic_launcher_background: The background image (e.g., a solid color or shape).


 ic_launcher_foreground: The logo or icon that will appear on top of the background.

This ensures that your app icon appears consistent across different devices and screen shapes.
Page | 82
3. Best Practices for Customizing Action Items and Icons

1. Keep Action Items Simple and Consistent: Avoid overcrowding the Action Bar with too
many items. Use icons for common actions like search, settings, or favorites, and use text
sparingly.
2. Use High-Quality Icons: Ensure your icons are clear and easy to understand. Avoid using
complex icons; instead, use simple, recognizable symbols.
3. Follow Android’s Design Guidelines: Adhere to the Android Material Design guidelines
when designing icons and action items. This ensures a consistent and familiar experience for
users.
4. Consider Different Screen Sizes: Provide multiple icon sizes for different screen densities
to ensure that your app looks sharp on all devices.
5. Test Across Devices: Make sure your custom action items and icons look good across
various screen sizes, resolutions, and Android versions.

4. Conclusion

Customizing the action items in the Action Bar and the application icon is a powerful way to
enhance the user experience and reinforce your app’s branding. By following Android’s best
practices for customizing UI elements, you can ensure your app stands out while providing a
seamless and intuitive experience for users. Whether it’s changing the appearance of action items or
creating adaptive icons, these customizations help make your app visually appealing and functional
on a variety of devices.

Adapting to Display Orientation


Introduction:

 Mobile devices can rotate between portrait and landscape modes.


 Proper adaptation ensures a consistent user experience without losing functionality or data.

Key Concepts:

1. Default Behavior:
o Android destroys and recreates the activity when the orientation changes, causing
potential data loss.
2. Resource Qualifiers:
o Layouts can be tailored for orientations using resource folders:
 res/layout/ for portrait.
 res/layout-land/ for landscape.
3. Handling Orientation Changes:
o Override onConfigurationChanged to handle changes programmatically.
o Use layouts like ConstraintLayout or FlexboxLayout for flexible designs.
4. Preventing Recreation:
o Prevent activity recreation using android:configChanges in the
[Link].

Page | 83
Code Example:

<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize">
</activity>

Advantages:

 Improves responsiveness and user experience.


 Reduces layout distortions.

Diagram:

Lifecycle flow during orientation change:

| User rotates the screen |


| Activity Destroyed (onDestroy) |
| Activity Recreated (onCreate) |

Anchoring Views
Introduction:

 Anchoring ensures views remain in place relative to their parent or other views during
orientation or layout changes.

Key Concepts:

1. Attributes for Anchoring:


o layout_alignParentStart or layout_alignParentEnd for edges.
o layout_centerHorizontal or layout_centerVertical for centering.
o RelativeLayout and ConstraintLayout are ideal for anchoring views.
2. Practical Use:
o Use when designing buttons, headers, and footers to ensure they adapt gracefully.

Code Example:

<RelativeLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="Anchored Button" />
</RelativeLayout>

Advantages:

Page | 84
 Keeps critical UI elements aligned.
 Enhances usability on different screen sizes.

Resizing and Repositioning


Introduction:

 Ensures UI components scale and adapt for screens of varying sizes and orientations.

Key Concepts:

1. Flexible Dimensions:
o Use match_parent and wrap_content for non-fixed dimensions.
o Define scalable resources ([Link]) for consistency.
2. Dynamic Repositioning:
o Use ConstraintLayout to specify constraints like margins, padding, and relative
positioning.
3. Screen Size Specific Layouts:
o Use folders like res/layout-small, res/layout-large.

Code Example:

<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

Advantages:

 Provides a responsive UI.


 Eliminates the need for hardcoding dimensions.

Managing Changes to Screen Orientation


Introduction:

 Managing orientation changes ensures smooth transitions without disrupting user


interactions.

Key Concepts:

1. Challenges:
o Activity recreation by default can cause performance issues or data loss.
2. Solutions:
o Use android:configChanges to prevent recreation.
Page | 85
o Save and restore data using onSaveInstanceState.
3. Programmatic Management:
o Detect and handle orientation changes dynamically using onConfigurationChanged.

Code Example:

<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize" />
kotlin
Copy code
override fun onConfigurationChanged(newConfig: Configuration) {
[Link](newConfig)
if ([Link] == Configuration.ORIENTATION_LANDSCAPE) {
// Handle landscape
}
}

Advantages:

 Ensures seamless data handling.


 Optimizes performance.

Persisting State Information During Changes in Configuration


Introduction:

 Critical for maintaining user progress and data during orientation changes.

Key Concepts:

1. Challenges:
o Temporary data, like form input or app states, is lost when the activity is recreated.
2. Solutions:
o Save data in onSaveInstanceState and retrieve it in onCreate.
o Use ViewModel for longer data persistence.

Code Example:

override fun onSaveInstanceState(outState: Bundle) {


[Link]("username", username)
[Link](outState)
}

override fun onCreate(savedInstanceState: Bundle?) {


[Link](savedInstanceState)
val username = savedInstanceState?.getString("username")
}

Advantages:

 Prevents data loss.

Page | 86
 Improves user experience.

Detecting Orientation Changes


Introduction:

 Enables apps to adapt dynamically based on orientation.

Key Concepts:

1. Using Configuration Class:


o Check the current orientation programmatically:

if ([Link] ==
Configuration.ORIENTATION_LANDSCAPE) {
// Landscape mode
}

2. Advanced Detection:
o Use the SensorManager API for precise detection in custom scenarios (e.g., gaming
apps).

Advantages:

 Supports dynamic UI updates.


 Enables advanced orientation-based features.

Adding Action Items to the Action Bar


Introduction:

 Action items enhance functionality by providing quick access to frequently used tasks.

Key Concepts:

1. Defining Action Items:


o Create action items in the res/menu folder.
o Use onCreateOptionsMenu to inflate the menu into the Action Bar.
2. Customization:
o Set custom icons and titles.

Code Example:

<menu xmlns:android="[Link]
<item
android:id="@+id/action_settings"
android:icon="@drawable/ic_settings"
android:title="Settings"

Page | 87
android:showAsAction="always" />
</menu>

………
override fun onCreateOptionsMenu(menu: Menu): Boolean {
[Link]([Link].menu_main, menu)
return true
}

Advantages:

 Enhances usability.
 Offers a consistent UI pattern.

Customizing the Action Items and Application Icon


Introduction:
 Customization improves branding and user engagement.

Key Concepts:

1. Custom Action Items:


o Replace default icons with application-specific graphics.
o Use custom layouts for complex icons.
2. Custom App Icon:
o Change the default app icon in the [Link].

Code Example:

Application Icon:

<application
android:icon="@drawable/custom_icon">
</application>

Custom Action Item Layout:

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/custom_action_icon" />

Advantages:
 Enhances branding.
 Creates a visually distinct app interface.

Conclusion

Each subtopic is critical for developing responsive, user-friendly, and professional Android
applications. By mastering these techniques, developers can create applications that are robust,
adaptable, and visually appealing.

Page | 88
UNIT - 3
Designing Your User Interface with Views in Android
In Android, the user interface (UI) is composed of Views and ViewGroups, where Views represent
individual UI components (such as buttons, text fields, images), and ViewGroups act as containers
that hold and organize these Views. Proper design and layout of these Views is crucial for delivering
an effective user experience (UX) that is both functional and aesthetically pleasing.

1. What are Views in Android?

A View is the base class for all UI components in Android, such as buttons, text boxes, and images.
Each View occupies a rectangular area on the screen and is responsible for handling user
interactions and drawing itself.

Common View Types in Android:

 TextView: Displays text to the user.


 Button: A clickable button that can trigger actions when pressed.
 ImageView: Displays images.
 EditText: Allows the user to input text.
 CheckBox: A UI element representing a binary choice (checked or unchecked).
 RadioButton: Allows the user to select a single option from a group.
 ProgressBar: Displays the progress of a task.
 Switch: A UI element for switching between two states (on/off).

2. ViewHierarchy in Android

The ViewHierarchy is the structure of Views that defines how UI components are arranged within
an app. Views are organized in a parent-child hierarchy, where ViewGroups act as containers and
child Views are placed inside them. The layout of these Views is controlled by various types of
Layout Managers such as LinearLayout, RelativeLayout, and others.

Example of a View Hierarchy:

LinearLayout (parent ViewGroup)


|
|-- TextView (child View)
|
|-- Button (child View)
|
|-- ImageView (child View)

Using Basic Views in Android


In Android, basic Views represent the building blocks of a user interface. These Views can display
text, images, handle user interactions like button presses, collect input, and even show progress or
selections. Below is a detailed overview of commonly used basic Views in Android:

1. TextView
Page | 89
TextView is the most commonly used widget for displaying text on the screen. It is a versatile
widget that supports text formatting, alignment, and much more.

Attributes:

 android:text: Defines the text to be displayed.


 android:textSize: Sets the size of the text in scalable pixels (sp).
 android:textColor: Specifies the color of the text.
 android:gravity: Aligns text within the TextView. Values can be left, center, right,
top, or bottom.
 android:maxLines: Limits the number of lines of text.

Usage Example:

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Android!"
android:textSize="20sp"
android:textColor="#FF6347"
android:gravity="center"/>

Advanced Functionality:

 Multiline Text: You can enable wrapping and ellipsis when the text overflows the boundary
of the TextView.

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a very long text that will wrap or ellipsis."
android:maxLines="2"
android:ellipsize="end"/>

2. Button

Button is a clickable widget that triggers an event, such as submitting a form or opening a new
activity.

Attributes:

 android:text: Defines the label of the button.


 android:onClick: Assigns a method in the Activity that will be called when the button is
clicked.

Usage Example:

<Button
android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

Page |
910
android:text="Submit"
android:onClick="submitForm"/>

Handling Button Click:

In your Activity, you can define the submitForm method to handle the button click:

public void submitForm(View view) {


[Link](this, "Form Submitted!", Toast.LENGTH_SHORT).show();
}

3. ImageButton

ImageButton is a button that displays an image. It can be used for actions that don't require text,
such as play, pause, or settings icons.

Attributes:

 android:src: The image to be displayed on the button.


 android:contentDescription: Provides a description for the image for accessibility
purposes.

Usage Example:

<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_play"
android:contentDescription="Play Button"/>

4. EditText

EditText is a text box where the user can input text. It's typically used in forms, search boxes, or
settings fields.

Attributes:

 android:hint: Displays a hint when the input field is empty.


 android:inputType: Specifies the type of input, such as text, number, or password.
 android:maxLength: Limits the number of characters the user can enter.

Usage Example:

<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your username"
android:inputType="textEmailAddress"
android:maxLength="30"/>

Page |
911
Advanced Functionality:

 For a password field, you can use the inputType attribute to mask the input text:

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your password"
android:inputType="textPassword"/>

5. CheckBox

A CheckBox is a binary option, either checked or unchecked. It's commonly used for forms and
settings options where users need to make a yes/no choice.

Attributes:

 android:text: Label displayed next to the checkbox.


 android:checked: Sets the initial state of the checkbox.

Usage Example:

<CheckBox
android:id="@+id/checkBoxTerms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I agree to the terms and conditions"
android:checked="false"/>

Handling CheckBox State:

CheckBox checkBox = findViewById([Link]);


[Link]((buttonView, isChecked) -> {
if (isChecked) {
// Do something if checked
} else {
// Do something if unchecked
}
});

6. ToggleButton

A ToggleButton is used for switching between two states: "On" and "Off." It can be used to
represent binary settings such as "Enable" or "Disable."

Attributes:

 android:textOn: The text to display when the button is "On."


 android:textOff: The text to display when the button is "Off."

Usage Example:

Page | 92
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="ON"
android:textOff="OFF"/>

Handling ToggleButton State:

ToggleButton toggleButton = findViewById([Link]);


[Link]((buttonView, isChecked) -> {
if (isChecked) {
// Do something when ON
} else {
// Do something when OFF
}
});

7. RadioButton

A RadioButton is used within a RadioGroup for mutually exclusive options. It is a part of a group
where only one option can be selected at a time.

Attributes:

 android:text: The label for the radio button.

Usage Example:

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<RadioButton
android:id="@+id/radioOption1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1"/>

<RadioButton
android:id="@+id/radioOption2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2"/>
</RadioGroup>

Handling RadioButton Selection:

RadioGroup radioGroup = findViewById([Link]);


[Link]((group, checkedId) -> {
switch (checkedId) {
case [Link].radioOption1:
// Option 1 selected
break;
case [Link].radioOption2:
// Option 2 selected

Page | 93
break;
}
});

8. RadioGroup

A RadioGroup is a container that holds multiple RadioButton elements. It ensures that only one
radio button is selected at a time.

Usage:

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<RadioButton
android:id="@+id/radio_option_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1" />

<RadioButton
android:id="@+id/radio_option_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2" />
</RadioGroup>

9. ProgressBar

A ProgressBar indicates the progress of an ongoing task. It can be determinate (with a fixed
progress value) or indeterminate (without any specific progress value).

Attributes:

 android:indeterminate: If true, the progress bar shows a spinning wheel (indeterminate


state).
 android:max: Defines the maximum progress value for a determinate ProgressBar.
 android:progress: Defines the current progress value.

Usage Example:

<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"/>

Handling ProgressBar:

For a determinate ProgressBar, you can update the progress:


Page | 94
ProgressBar progressBar = findViewById([Link]);
[Link](100);
[Link](50); // Set progress to 50%

10. AutoCompleteTextView

The AutoCompleteTextView is a special type of EditText that shows suggestions as the user types.

Attributes:

 android:completionThreshold: The number of characters the user must type before the
suggestions are shown.
 android:adapter: A source of suggestions, typically an ArrayAdapter.

Usage Example:

<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter city"
android:completionThreshold="2"/>

Handling AutoCompleteTextView:

AutoCompleteTextView autoCompleteTextView =
findViewById([Link]);
String[] cities = {"New York", "Los Angeles", "Chicago"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
[Link].simple_dropdown_item_1line, cities);
[Link](adapter);

11. TimePicker

The TimePicker widget allows users to select a time, including hours and minutes.

Attributes:

 android:timePickerMode: Can be set to spinner (for scrolling through values) or clock


(for a visual clock display).

Usage Example:

<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"/>

Handling TimePicker:

TimePicker timePicker = findViewById([Link]);


int hour = [Link]();
Page | 95
int minute = [Link]();

12. DatePicker

The DatePicker widget allows users to select a date (day, month, and year).

Attributes:

 android:calendarViewShown: If set to true, a calendar view is displayed to the user.

Usage Example:

<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

Handling DatePicker:

DatePicker datePicker = findViewById([Link]);


int day = [Link]();
int month = [Link]();
int year = [Link]();

Conclusion

Android provides a rich set of Views, each of which serves a different purpose in designing an
interactive and functional UI. Understanding the attributes, handling user interactions, and
leveraging advanced features allows developers to create dynamic and responsive Android
applications.

Using ListViews to Display Long Lists


ListView is a view that displays a list of items in a vertically scrollable format. It's ideal for
displaying long lists of data. Each item in the list is typically represented by a row that can contain
any number of views (like text, images, etc.).

Key Features:

 Efficient Handling of Large Datasets: ListView is optimized for handling long lists. It
only creates the views that are visible on the screen, saving memory and improving
performance.
 Adapter: A ListView requires an adapter (such as ArrayAdapter or CustomAdapter) to
provide the data to be displayed in the list.
 Item Click Events: ListView supports item click events, allowing you to perform actions
when an item is selected.

Usage Example:

Page | 96
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

In your Activity or Fragment:

ListView listView = findViewById([Link]);


String[] items = {"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
[Link].simple_list_item_1, items);
[Link](adapter);

[Link]((parent, view, position, id) -> {


[Link](this, "Item clicked: " + items[position],
Toast.LENGTH_SHORT).show();
});

ListView View
A ListView is used to display a scrollable list of items. Each item in the list is created dynamically
based on the data provided by an adapter.

Key Attributes:

 android:divider: Defines the divider between list items.


 android:dividerHeight: Sets the height of the divider.
 android:choiceMode: Defines how items are selected (e.g., single, multiple).
 android:footerDividersEnabled: Controls whether the footer dividers are visible.

Usage Example (continued):

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#DDDDDD"
android:dividerHeight="1dp"
android:footerDividersEnabled="true"/>

Using the Spinner View


A Spinner is a dropdown menu used for selecting one item from a list. It’s similar to a ComboBox in
other frameworks.

Key Features:

 Drop-down List: Displays a list of items that the user can scroll through.
 Adapter: A Spinner also needs an adapter to provide the data.
 Item Selection: The spinner allows you to capture the selected item.

Usage Example:
Page | 97
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

In your Activity:

Spinner spinner = findViewById([Link]);


String[] options = {"Option 1", "Option 2", "Option 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
[Link].simple_spinner_item, options);
[Link]([Link].simple_spinner_dropdown_item);
[Link](adapter);

[Link](new [Link]() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView,
int position, long id) {
[Link](getApplicationContext(), "Selected: " +
options[position], Toast.LENGTH_SHORT).show();
}

@Override
public void onNothingSelected(AdapterView<?> parentView) {
// Do nothing
}
});

Understanding Specialized Fragments


Fragments are reusable UI components that allow you to build flexible and modular UIs. They
represent a portion of the user interface within an Activity and can be combined to create dynamic
and interactive layouts.

Types of Specialized Fragments:

 ListFragment: A fragment designed to display a list of items.


 DialogFragment: A fragment that displays a dialog window.
 PreferenceFragment: A fragment used for managing preferences in the Settings activity.

Using a ListFragment
A ListFragment is a specialized type of fragment that simplifies displaying a list of items. It
combines the functionality of ListView and Fragment, allowing you to show a list within a
fragment.

Key Features:

 Automatic Integration with ListView: ListFragment automatically integrates with a


ListView, so you don't need to manually define a ListView in the layout.
 Adapter: Like ListView, ListFragment uses an adapter to supply data to the list.

Page | 98
Usage Example:

<!-- No ListView in the layout, as it's handled by ListFragment -->

In your Activity:

public class MyListFragment extends ListFragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] items = {"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
[Link].simple_list_item_1, items);
setListAdapter(adapter);
return [Link](inflater, container, savedInstanceState);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
[Link](getActivity(), "Item clicked: " + position,
Toast.LENGTH_SHORT).show();
}
}

Using a DialogFragment
A DialogFragment is a fragment that displays a modal dialog. It provides a flexible way of showing
dialogs without disrupting the activity's layout.

Key Features:

 Popup Dialogs: It can display pop-up dialogs, with custom layouts or predefined ones.
 Communication with Activity: You can pass data to and from the DialogFragment to the
hosting Activity.

Usage Example:

public static class MyDialogFragment extends DialogFragment {


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
[Link] builder = new [Link](getActivity());
[Link]("This is a DialogFragment")
.setPositiveButton("OK", (dialog, id) -> {
// Handle OK button click
})
.setNegativeButton("Cancel", (dialog, id) -> {
// Handle Cancel button click
});
return [Link]();
}
}

To show the dialog from the activity:

DialogFragment dialog = new MyDialogFragment();


[Link](getSupportFragmentManager(), "MyDialog");
Page | 99
Using a PreferenceFragment
A PreferenceFragment is a specialized fragment that simplifies displaying and managing
preferences in an application, typically used in a settings screen.

Key Features:

 Preference Management: It uses SharedPreferences to store the settings.


 Default Preferences: Can be configured in XML files.

Usage Example:

<!-- [Link] -->


<PreferenceScreen
xmlns:android="[Link]
<CheckBoxPreference
android:key="example_key"
android:title="Enable Feature"
android:defaultValue="false"/>
</PreferenceScreen>

In the PreferenceActivity:

public class SettingsActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
getFragmentManager().beginTransaction()
.replace([Link], new SettingsFragment())
.commit();
}

public static class SettingsFragment extends PreferenceFragment {


@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
addPreferencesFromResource([Link]);
}
}
}

Conclusion

Each of the views and fragments mentioned serves a unique purpose in Android development:

 ListView and Spinner: For displaying lists and selection options.


 Fragments: For modular UI components that enhance reusability and flexibility.
o ListFragment: For lists within fragments.
o DialogFragment: For modal dialogs within fragments.
o PreferenceFragment: For managing settings and preferences in an application.

By using these components effectively, you can create dynamic, flexible, and interactive UIs that
provide a better user experience.
Page | 101
Displaying Pictures and Menus in Android
In Android development, displaying images and menus effectively is essential for creating dynamic,
user-friendly apps. Here's a detailed breakdown of how to use the various components for displaying
images and working with menus.

1. Gallery and ImageView Views

ImageView:

The ImageView is a widget used to display images in Android. It allows you to display images from
different sources, such as local resources, URLs, or files.

Key Attributes:

 android:src: Sets the image resource.


 android:scaleType: Defines how the image should fit within the ImageView. Possible
values include center, fitXY, centerCrop, etc.
 android:adjustViewBounds: Adjusts the bounds of the image to fit inside the ImageView.

Usage Example:

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/sample_image"
android:scaleType="centerCrop"/>

In the Activity:

ImageView imageView = findViewById([Link]);


[Link]([Link].another_image);

Gallery:

The Gallery view allows users to scroll through a collection of images or other items horizontally.

Key Features:

 The Gallery can be used with an adapter (e.g., ArrayAdapter, BaseAdapter) to populate
the items.
 Horizontal Scrolling: Provides an easy way to display a horizontally scrollable list of items.

Usage Example:

<Gallery
android:id="@+id/gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

Page | 101
In the Activity:

Gallery gallery = findViewById([Link]);


Integer[] images = {[Link].image1, [Link].image2, [Link].image3};
ImageAdapter adapter = new ImageAdapter(this, images);
[Link](adapter);

2. ImageSwitcher

ImageSwitcher is a specialized ViewSwitcher used for switching between images, often used in
situations where images are dynamically updated (e.g., a slideshow or a gallery).

Key Features:

 Allows for animated transitions between images.


 Requires an adapter and a view factory to manage image transitions.
 Useful for situations where you want to show images with smooth transitions.

Usage Example:

<ImageSwitcher
android:id="@+id/imageSwitcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inAnimation="@android:anim/fade_in"
android:outAnimation="@android:anim/fade_out"/>

In the Activity:

ImageSwitcher imageSwitcher = findViewById([Link]);


[Link](() -> new ImageView(getApplicationContext()));

String[] imageUrls = {"url1", "url2", "url3"};


int currentImageIndex = 0;
[Link]([Link].image1);

// Switch image on button click


Button nextButton = findViewById([Link]);
[Link](v -> {
currentImageIndex = (currentImageIndex + 1) % [Link];
[Link]([Link].image2); // Load next image
});

3. GridView

GridView is a type of view that allows you to display items in a 2D grid format. It is ideal for
displaying images or other items in rows and columns.

Key Features:

 Efficient Layout: Similar to ListView, GridView uses an adapter to handle the layout
efficiently.
 Flexibility: Can be customized with different types of views (e.g., images, text).
Page | 103
 Item Click: Supports item click events.

Usage Example:

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:columnWidth="100dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"/>

In the Activity:

GridView gridView = findViewById([Link]);


Integer[] images = {[Link].image1, [Link].image2, [Link].image3,
[Link].image4};
ImageAdapter adapter = new ImageAdapter(this, images);
[Link](adapter);

[Link]((parent, view, position, id) -> {


[Link](this, "Item " + position + " clicked",
Toast.LENGTH_SHORT).show();
});

4. Using Menus with Views

Menus are a critical part of any Android app, allowing users to interact with the application in a
structured way. Android provides two types of menus: Options Menu and Context Menu.

Creating Helper Methods for Menus:

To handle the creation of menus, you need to override two methods:

 onCreateOptionsMenu(): Creates the options menu.


 onOptionsItemSelected(): Handles item selection from the options menu.

Options Menu:

The Options Menu is the primary menu for an Activity. It’s typically invoked by pressing the menu
button (or through the action bar in modern Android apps).

Usage Example (Options Menu):

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate([Link].main_menu, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch ([Link]()) {
case [Link].option1:
Page | 103
[Link](this, "Option 1 selected",
Toast.LENGTH_SHORT).show();
return true;
case [Link].option2:
[Link](this, "Option 2 selected",
Toast.LENGTH_SHORT).show();
return true;
default:
return [Link](item);
}
}

Menu XML (res/menu/main_menu.xml):

<menu xmlns:android="[Link]
<item
android:id="@+id/option1"
android:title="Option 1" />
<item
android:id="@+id/option2"
android:title="Option 2" />
</menu>

Context Menu:

A Context Menu is a floating menu that appears when the user long presses on an item in the view.
It’s ideal for giving users additional options related to a specific item.

Usage Example (Context Menu):

@Override
public boolean onContextItemSelected(MenuItem item) {
[Link] info =
([Link]) [Link]();
switch ([Link]()) {
case [Link].delete_option:
[Link](this, "Deleted item at position " + [Link],
Toast.LENGTH_SHORT).show();
return true;
case [Link].edit_option:
[Link](this, "Edited item at position " + [Link],
Toast.LENGTH_SHORT).show();
return true;
default:
return [Link](item);
}
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
[Link] menuInfo) {
[Link](menu, v, menuInfo);
getMenuInflater().inflate([Link].context_menu, menu);
}

Context Menu XML (res/menu/context_menu.xml):

<menu xmlns:android="[Link]
<item

Page | 105
android:id="@+id/edit_option"
android:title="Edit" />
<item
android:id="@+id/delete_option"
android:title="Delete" />
</menu>

Conclusion

These components provide you with powerful tools to create interactive and visually appealing apps:

1. ImageView and Gallery: Used for displaying images in various formats.


2. ImageSwitcher: Facilitates smooth transitions between images, ideal for dynamic displays.
3. GridView: A versatile grid layout for displaying items like images or text in multiple
columns.
4. Menus: Allow users to interact with the app by selecting from options or context menus.
Options menus typically appear in the action bar, while context menus appear on long press
of an item.

These components enhance the user experience by offering interactive, visually rich interfaces and
intuitive menus for easier navigation within the app.

Page | 105
Page | 107
UNIT - 4
Introduction to SQLite
SQLite is a lightweight, embedded, serverless relational database engine that is widely used in
Android applications for local data storage. It is a self-contained, zero-configuration database engine
that provides a fully functional relational database management system (RDBMS). Unlike
traditional database systems, SQLite doesn't require a separate server process to operate, making it
ideal for use in mobile and desktop applications where a serverless solution is desired.

SQLite stores its data in a single, portable file, making it efficient and easy to use. Its simplicity and
small footprint make it a popular choice for applications that need to store structured data on a local
device.

Key Features of SQLite:

1. Serverless:
o SQLite is an embedded database, meaning it does not require a server to run. It runs
directly within the application and operates on a single database file.
2. Lightweight:
o The database engine is small and efficient, with minimal resource usage. It is
typically only a few hundred kilobytes in size.
3. Self-contained:
o SQLite doesn't rely on external dependencies or services. The entire database engine
is included in the application, and it only requires the SQLite file to function.
4. Zero Configuration:
o SQLite requires no setup or configuration. There is no need for a separate database
server or complex setup steps, which simplifies the development process.
5. ACID Compliant:
o SQLite is ACID (Atomicity, Consistency, Isolation, Durability) compliant, ensuring
data integrity even in the event of system crashes or power failures.
6. Portable:
o The database is stored as a single file, making it easy to move or back up data. This
feature is especially useful in mobile applications, where data portability is important.
7. Supports SQL:
o SQLite uses a dialect of SQL (Structured Query Language), which means developers
can interact with the database using familiar SQL commands like SELECT, INSERT,
UPDATE, and DELETE.

How SQLite Works in Android

In Android applications, SQLite is commonly used for local data storage, allowing the app to store
data on the device in a persistent manner. This is particularly useful for apps that need to store user
data (such as contacts, notes, or preferences) or work offline.

Page | 107
SQLite in Android is integrated via the SQLiteDatabase class and managed through the
SQLiteOpenHelper class, which helps in managing database creation, version management, and
data migrations.

Basic Components of SQLite in Android:

1. SQLiteDatabase Class:
o This class provides an interface to interact with the SQLite database. You can use this
class to execute SQL queries, such as SELECT, INSERT, UPDATE, and DELETE.
2. SQLiteOpenHelper Class:
o The SQLiteOpenHelper class is used to manage database creation and version
management. It provides methods for creating, upgrading, and opening the database.
It also helps with database schema changes and migrations.
3. ContentValues Class:
o ContentValues is used to store key-value pairs, which can then be inserted or
updated in the database. The keys correspond to column names, and the values are
the data to be stored in those columns.
4. Cursor Class:
o The Cursor class is used to represent a result set from a database query. It points to a
specific row and provides methods for reading data from each column.

How to Use SQLite in Android

1. Create a SQLiteOpenHelper Class:


o The SQLiteOpenHelper class is extended to handle database creation and version
management. This class defines the database schema and contains methods like
onCreate() (for creating the database) and onUpgrade() (for upgrading the database
schema).
2. Inserting, Reading, Updating, and Deleting Data:
o Data is inserted using the insert() method, read using the query() or rawQuery()
methods, updated with the update() method, and deleted with the delete() method.
These methods interact with the database through SQL commands.
3. Querying Data:
o To read data, you use SQL queries and retrieve results using a Cursor. You can
iterate over the Cursor to access individual rows of the result set.
4. Closing the Database:
o After performing database operations, it’s important to close the database and cursor
to release resources.

Advantages of Using SQLite in Android:

1. Efficiency:
o SQLite is highly efficient for small and medium-sized applications that need to store
structured data locally.

Page | 109
2. No Server Requirement:
o Unlike other databases, SQLite does not require a separate database server, making it
easier to set up and use.
3. Portable Data:
o Since SQLite stores its database in a single file, it is easy to back up or transfer the
data across different devices or platforms.
4. ACID Compliant:
o SQLite guarantees data integrity, ensuring that transactions are processed reliably,
even in the case of unexpected shutdowns or failures.
5. Ease of Use:
o SQLite supports a standard SQL interface, making it easy for developers to interact
with the database using familiar SQL queries.

Use Cases for SQLite in Android Applications:

 Offline Data Storage: Storing data locally when the app is used offline (e.g., in news apps,
offline games, or weather apps).
 User Preferences: Storing settings and preferences for user accounts, like themes, language
settings, and app configurations.
 Persistent Data: Storing application data such as messages, notes, contacts, or shopping lists
in a structured way.
 Small Databases: Ideal for small databases with a low number of rows, where a full
database server solution would be overkill.

SQLite Syntax

SQLite uses standard SQL syntax for database operations, including:

 Creating a table:

CREATE TABLE contacts (


id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
phone TEXT
);

 Inserting data:

INSERT INTO contacts (name, phone) VALUES ('John Doe', '1234567890');

 Querying data:

SELECT * FROM contacts WHERE name = 'John Doe';

 Updating data:

UPDATE contacts SET phone = '0987654321' WHERE id = 1;

Page | 109
 Deleting data:

DELETE FROM contacts WHERE id = 1;

Conclusion

SQLite is an integral part of Android development, providing a simple and effective way to store
and manage local data. It allows for powerful data management while maintaining a small memory
footprint and avoiding the need for a separate database server. By using SQLite, developers can
ensure their apps are capable of handling structured data efficiently, making it a key tool for offline
data storage in mobile applications.

SQLiteOpenHelper and SQLiteDatabase in Android


In Android, SQLiteOpenHelper and SQLiteDatabase are two essential components used to interact
with SQLite databases. They work together to help developers manage database creation, access,
and updates. Below is a detailed explanation of both classes:

1. SQLiteOpenHelper

The SQLiteOpenHelper class is used to manage database creation, version management, and
schema updates in Android applications. It abstracts away much of the complexity involved in
working with SQLite databases, providing an easy-to-use interface for database operations.

Key Features of SQLiteOpenHelper:

 Database Creation: SQLiteOpenHelper creates a new database if it doesn't already exist,


using the onCreate() method.
 Version Management: It helps manage database versions. When the version of the database
schema changes, the onUpgrade() method is called.
 Database Management: It simplifies tasks like opening and closing the database.

Constructor:

 SQLiteOpenHelper(Context context, String name, [Link]


factory, int version):
o context: The application context.
o name: The name of the database.
o factory: A cursor factory used to create custom Cursor objects (usually null).
o version: The version of the database schema.

Methods:

 onCreate(SQLiteDatabase db):
o This method is called when the database is created for the first time. You typically
define the SQL queries to create your tables in this method.

Page | 110
 onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion):
o This method is called when the database version is upgraded. You can define how the
schema should be modified (e.g., add new columns or tables) in this method.
 onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion):
o This method is used when downgrading the database version, although it is rarely
needed.
 getWritableDatabase():
o Returns a writable database object, allowing you to perform write operations (insert,
update, delete).
 getReadableDatabase():
o Returns a readable database object, used for read-only operations.

Example of SQLiteOpenHelper Class:

public class MyDatabaseHelper extends SQLiteOpenHelper {

// Database Information
private static final String DATABASE_NAME = "contactsDB";
private static final int DATABASE_VERSION = 1;

// Table Information
private static final String TABLE_CONTACTS = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_PHONE = "phone";

// SQL to create the table


private static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_CONTACTS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_PHONE + " TEXT);";

public MyDatabaseHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
// Create the table if it doesn't exist
[Link](CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Handle database version upgrade
[Link]("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
}

In this example, the MyDatabaseHelper class extends SQLiteOpenHelper and creates a simple
contacts table to store the name and phone number of contacts.

Page | 111
2. SQLiteDatabase

The SQLiteDatabase class provides the interface to interact with the SQLite database. It allows you
to perform CRUD (Create, Read, Update, Delete) operations on the database.

Key Features of SQLiteDatabase:

 CRUD Operations: You can insert, query, update, and delete data.
 Transactions: SQLiteDatabase supports transactions, which ensure that a series of database
operations are executed atomically.
 SQL Queries: You can execute raw SQL queries through methods like rawQuery(),
execSQL(), etc.
 Locking: SQLite automatically handles concurrency and locking.

Methods:

 insert(String table, String nullColumnHack, ContentValues values):


o Inserts a new row into the specified table.
o table: The name of the table.
o nullColumnHack: A column name that can be used when the ContentValues is
empty.
o values: The key-value pairs to be inserted.
 query(String table, String[] columns, String selection, String[] selectionArgs, String
groupBy, String having, String orderBy):
o Queries the database and returns a Cursor object containing the results.
o table: The table name.
o columns: The columns to retrieve.
o selection: The WHERE clause (optional).
o selectionArgs: The arguments for the WHERE clause (optional).
 update(String table, ContentValues values, String whereClause, String[] whereArgs):
o Updates records in the specified table based on the whereClause.
 delete(String table, String whereClause, String[] whereArgs):
o Deletes records from the table based on the whereClause.
 execSQL(String sql):
o Executes a single SQL statement that doesn't return any data, such as INSERT,
UPDATE, or CREATE TABLE.
 beginTransaction(), setTransactionSuccessful(), endTransaction():
o Used to group database operations into a single transaction to ensure atomicity.

Example of SQLiteDatabase Operations:

public class ContactDatabase {

private SQLiteDatabase database;


private MyDatabaseHelper dbHelper;

public ContactDatabase(Context context) {


dbHelper = new MyDatabaseHelper(context);
}

Page | 112
// Insert a new contact
public void insertContact(String name, String phone) {
SQLiteDatabase db = [Link]();
ContentValues values = new ContentValues();
[Link]("name", name);
[Link]("phone", phone);
[Link]("contacts", null, values);
[Link]();
}

// Query all contacts


public List<String> getAllContacts() {
SQLiteDatabase db = [Link]();
Cursor cursor = [Link]("contacts", new String[]{"name", "phone"},
null, null, null, null, null);
List<String> contacts = new ArrayList<>();
if (cursor != null) {
while ([Link]()) {
String name = [Link]([Link]("name"));
String phone = [Link]([Link]("phone"));
[Link](name + ": " + phone);
}
[Link]();
}
[Link]();
return contacts;
}
}

In this example, the insertContact method inserts a new contact into the database, while the
getAllContacts method retrieves all contacts from the contacts table.

Difference Between SQLiteOpenHelper and SQLiteDatabase:

Feature SQLiteOpenHelper SQLiteDatabase


Manages database creation, version Provides methods to interact with the database
Purpose
management, and upgrades. (CRUD operations).
Used for executing SQL queries and
Used for creating, upgrading, and
Usage performing database operations (insert, query,
managing the database schema.
update, delete).
onCreate(), onUpgrade(), insert(), query(), update(), delete(),
Methods
onDowngrade(), etc. execSQL(), etc.
Handles the lifecycle of the database Handles actual data manipulation (create, read,
Lifecycle
(open/close). update, delete).

Conclusion

 SQLiteOpenHelper is primarily used to manage the database schema and handle the
creation, upgrading, and opening of the database.
 SQLiteDatabase is used to perform the actual CRUD operations on the database, including
querying and updating records.

Together, these two classes provide an efficient way to work with SQLite databases in Android,
abstracting much of the complexity involved in interacting with a database.
Page | 113
Creating, Opening, and Closing a Database in Android using SQLite
In Android, working with an SQLite database involves creating the database, opening it for
read/write operations, and closing it when the operations are completed. The SQLiteOpenHelper
and SQLiteDatabase classes play a crucial role in this process.

Here’s a detailed explanation of each of these steps:

1. Creating a Database

To create a database, you use the SQLiteOpenHelper class. This class helps manage database
creation and version management. The onCreate() method of SQLiteOpenHelper is called when
the database is created for the first time.

Steps to Create a Database:

1. Extend SQLiteOpenHelper: You must extend the SQLiteOpenHelper class and override
the onCreate() method where the database schema (tables) is defined.
2. Create Tables: In the onCreate() method, you define the SQL queries to create the
necessary tables.
3. Call getWritableDatabase() or getReadableDatabase(): When the
getWritableDatabase() or getReadableDatabase() method is called, it will trigger the
creation of the database if it does not exist.

Example:

public class MyDatabaseHelper extends SQLiteOpenHelper {

// Database Information
private static final String DATABASE_NAME = "contactsDB";
private static final int DATABASE_VERSION = 1;

// Table Information
private static final String TABLE_CONTACTS = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_PHONE = "phone";

// SQL to create the table


private static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_CONTACTS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_PHONE + " TEXT);";

public MyDatabaseHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
// Create the table if it doesn't exist
[Link](CREATE_TABLE);

Page | 114
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Handle database upgrade if needed
[Link]("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
}

In the above code:

 DATABASE_NAME defines the name of the database.


 DATABASE_VERSION defines the version number of the database. If you change the schema,
you should increment this version.
 onCreate() method creates the contacts table when the database is created.

2. Opening a Database

When you want to interact with the database (for reading and writing data), you need to open it
using the getWritableDatabase() or getReadableDatabase() methods from the
SQLiteOpenHelper class.

Methods to Open a Database:

 getWritableDatabase(): This method opens the database in read/write mode, allowing you
to insert, update, or delete data.
 getReadableDatabase(): This method opens the database in read-only mode, meaning you
can only query the data.

These methods are usually invoked within the application to interact with the database.

Example:

public class ContactDatabase {

private SQLiteDatabase database;


private MyDatabaseHelper dbHelper;

public ContactDatabase(Context context) {


dbHelper = new MyDatabaseHelper(context);
}

// Opening the database


public void openDatabase() {
database = [Link](); // Opens the database in
read/write mode
}

// Close the database


public void closeDatabase() {
if (database != null && [Link]()) {
[Link](); // Closes the database when you're done
}

Page | 115
}
}

In the above example:

 The openDatabase() method calls getWritableDatabase() to open the database for


writing.
 The closeDatabase() method checks if the database is open and then closes it using the
close() method.

3. Closing a Database

It’s important to close the database after your operations are complete to release resources and avoid
memory leaks. The close() method of SQLiteDatabase is used to close the database.

Why Closing the Database is Important:

 Closing the database releases the resources and memory used by the database.
 It also ensures that any pending transactions are committed or rolled back, which prevents
potential issues with data corruption.

How to Close the Database:

 You simply call the close() method on the SQLiteDatabase object when you're done with
it.

Example (continued from the previous example):

// In the same class, after performing database operations:


public void closeDatabase() {
if (database != null && [Link]()) {
[Link](); // Close the database when done
}
}

4. Example: Full Lifecycle (Create, Open, and Close)

Here's a complete example showing the process of creating, opening, interacting with, and closing
an SQLite database in an Android application.

public class ContactDatabase {

private SQLiteDatabase database;


private MyDatabaseHelper dbHelper;

public ContactDatabase(Context context) {


dbHelper = new MyDatabaseHelper(context);
}

// Opening the database


public void openDatabase() {

Page | 116
database = [Link](); // Opens database in
read/write mode
}

// Insert a contact
public void insertContact(String name, String phone) {
ContentValues values = new ContentValues();
[Link]("name", name);
[Link]("phone", phone);
[Link]("contacts", null, values); // Insert the contact into
the table
}

// Query all contacts


public List<String> getAllContacts() {
List<String> contacts = new ArrayList<>();
Cursor cursor = [Link]("contacts", new String[]{"name",
"phone"}, null, null, null, null, null);

if (cursor != null) {
while ([Link]()) {
String name = [Link]([Link]("name"));
String phone = [Link]([Link]("phone"));
[Link](name + ": " + phone);
}
[Link]();
}
return contacts;
}

// Close the database


public void closeDatabase() {
if (database != null && [Link]()) {
[Link](); // Close the database when done
}
}
}

In the above code:

 openDatabase() is used to open the database for write operations.


 insertContact() inserts a new contact into the contacts table.
 getAllContacts() queries the database to retrieve all contacts.
 closeDatabase() closes the database after the operations are completed.

Summary of Database Lifecycle in Android:

Operation Method Used Purpose


Create [Link]() Creates the database and tables.
Database
Open getWritableDatabase(), Opens the database for read/write
Database getReadableDatabase() or read-only operations.
Inserts new rows of data into the
Insert Data insert(), insertOrThrow()
database.
Page | 117
Queries the database for specific
Query Data query(), rawQuery()
records.
Close close()
Closes the database to free
Database resources.

By following these steps, you can efficiently manage the lifecycle of an SQLite database in your
Android app, ensuring that you can perform necessary operations while maintaining good resource
management.

Working with Cursors in Android


In Android, a Cursor is a pointer that is used to retrieve data from a SQLite database. It holds the
result set of a query and allows access to the data retrieved from the database in a structured way. A
Cursor is used primarily for reading data from a database after performing a query operation using
methods such as query() or rawQuery().

Understanding Cursor

A Cursor provides an interface for accessing the rows and columns returned by a database query. It
allows you to:

 Navigate through the result set (moving from one row to another).
 Retrieve data from individual rows.
 Perform operations like checking if the cursor has data, getting the position of the cursor, etc.

A Cursor object provides methods to access data from the database, such as:

 getColumnIndex(): Retrieves the index of a column by its name.


 getString(), getInt(), getFloat(), etc.: Retrieve data from the columns of the current row.
 moveToNext(): Moves the cursor to the next row.
 moveToFirst(): Moves the cursor to the first row.
 isAfterLast(): Checks if the cursor is past the last row.
 close(): Closes the cursor when done with it to release resources.

Steps for Using a Cursor in SQLite:

1. Performing a Query: First, you need to perform a query using methods like query() or
rawQuery() to fetch data from the database. This will return a Cursor object containing the
result set.
2. Navigating through the Cursor: The Cursor starts pointing before the first row, so you
need to use methods like moveToFirst(), moveToNext(), or moveToLast() to move the
cursor to the desired row.
3. Retrieving Data: You can use methods like getString(), getInt(), getDouble(), etc., to
retrieve the data from the current row.
4. Closing the Cursor: After you finish using the Cursor, it's important to call the close()
method to release resources.

Page | 118
Commonly Used Methods in Cursor:

Method Description
moveToFirst() Moves the cursor to the first row of the result set.
moveToNext() Moves the cursor to the next row in the result set.
moveToLast() Moves the cursor to the last row in the result set.

getString(int columnIndex)
Retrieves the data from the specified column index as a
String.

Retrieves the data from the specified column index as an


getInt(int columnIndex)
int.

getFloat(int columnIndex)
Retrieves the data from the specified column index as a
float.

getDouble(int columnIndex)
Retrieves the data from the specified column index as a
double.

getColumnIndex(String Returns the index of the column with the specified


columnName) name.

isAfterLast()
Returns true if the cursor is past the last row in the
result set.
isBeforeFirst() Returns true if the cursor is before the first row.
close() Closes the cursor to free up the resources.

Example: Using Cursor to Retrieve Data

Here’s an example of how to query a database and retrieve data using a Cursor.

SQLiteOpenHelper Class

public class MyDatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "contactsDB";


private static final int DATABASE_VERSION = 1;

private static final String TABLE_CONTACTS = "contacts";


private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_PHONE = "phone";

private static final String CREATE_TABLE =


"CREATE TABLE " + TABLE_CONTACTS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_PHONE + " TEXT);";

Page | 119
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
[Link](CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
[Link]("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
}

Using Cursor to Query Data

public class ContactDatabase {

private SQLiteDatabase database;


private MyDatabaseHelper dbHelper;

public ContactDatabase(Context context) {


dbHelper = new MyDatabaseHelper(context);
}

// Opening the database


public void openDatabase() {
database = [Link](); // Opens database in
read/write mode
}

// Query to get all contacts


public List<String> getAllContacts() {
List<String> contacts = new ArrayList<>();
// Define the columns to query
String[] columns = {"id", "name", "phone"};

// Perform query and return a cursor


Cursor cursor = [Link]("contacts", columns, null, null, null,
null, null);

if (cursor != null) {
// Move the cursor to the first row
if ([Link]()) {
// Loop through all rows in the cursor
do {
int id = [Link]([Link]("id"));
String name =
[Link]([Link]("name"));
String phone =
[Link]([Link]("phone"));
[Link](id + ": " + name + " - " + phone);
} while ([Link]()); // Move to the next row
}
[Link](); // Close the cursor when done
}
return contacts;
}

// Close the database


Page | 120
public void closeDatabase() {
if (database != null && [Link]()) {
[Link](); // Close the database when done
}
}
}

Explanation of the Code:

 Opening the Database: The openDatabase() method opens the database in write mode.
 Querying Data: The getAllContacts() method queries the contacts table, retrieving all
columns (id, name, phone). The query results are returned as a Cursor.
 Navigating the Cursor: The moveToFirst() method moves the cursor to the first row.
Then, the moveToNext() method is used to loop through all the rows in the result set. For
each row, data is retrieved using the appropriate get method (e.g., getString(), getInt()).
 Closing the Cursor: After iterating through all the rows, the cursor is closed to free up the
resources.

Handling Cursors Properly

1. Always Close the Cursor: Always close the cursor after you're done using it. Failing to
close the cursor will lead to memory leaks and resource wastage. The close() method
should be called as soon as the cursor is no longer needed.
2. Check if the Cursor is Not Empty: Always check whether the cursor has data (e.g., using
moveToFirst() or getCount()) before trying to read from it to avoid
CursorIndexOutOfBoundsException.
3. Use try-catch-finally for Proper Resource Management: It's a good practice to use a
try-catch-finally block to ensure that the cursor is closed properly, even if an exception
occurs.

Example with Try-Catch-Finally:

public List<String> getAllContacts() {


List<String> contacts = new ArrayList<>();
Cursor cursor = null;

try {
// Perform the query
cursor = [Link]("contacts", new String[]{"id", "name", "phone"},
null, null, null, null, null);

if (cursor != null && [Link]()) {


do {
int id = [Link]([Link]("id"));
String name = [Link]([Link]("name"));
String phone = [Link]([Link]("phone"));
[Link](id + ": " + name + " - " + phone);
} while ([Link]());
}
} catch (Exception e) {
[Link]();
} finally {
if (cursor != null) {
[Link](); // Always close the cursor in the finally block
Page | 121
}
}
return contacts;
}

This method ensures that the cursor is always closed, even if an error occurs.

Conclusion

 Cursors are fundamental for interacting with the data returned by SQLite queries in
Android.
 They provide a convenient way to navigate through query results and retrieve data row by
row.
 Always remember to close the Cursor after using it to avoid memory leaks and other issues.
 Use appropriate methods to retrieve data (getString(), getInt(), etc.) and ensure proper
resource management by closing the cursor in a finally block.

Insert, Update, and Delete Operations in SQLite


In SQLite, data manipulation is primarily done using SQL commands: INSERT, UPDATE, and DELETE.
These operations allow you to add, modify, or remove records from the database tables.

Let's dive into each operation with examples and how they are executed in Android using the
SQLiteDatabase class.

1. Insert Operation (Inserting Data into Database)

The INSERT operation is used to add new rows of data into a table. In Android, this operation is
performed using the insert() method of the SQLiteDatabase class.

Syntax:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

Android Example:

public long insertContact(String name, String phone) {


SQLiteDatabase db = [Link](); // Get writable database

ContentValues values = new ContentValues();


[Link]("name", name); // Add the values to be inserted
[Link]("phone", phone); // Add the phone number

long result = [Link]("contacts", null, values); // Insert data into the


"contacts" table
[Link]();
return result;
}

 Explanation:

Page | 122
o ContentValues: This is used to store column names and their respective values.
o [Link](): The insert() method inserts the values into the specified table. If
successful, it returns the ID of the inserted row.

Handling Insert Errors:

 You should handle errors like duplicate entries, especially if there are unique constraints on
any columns.

2. Update Operation (Modifying Existing Data)

The UPDATE operation is used to modify the existing data in the table. It allows updating one or more
columns of a specific row.

Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Android Example:

public int updateContact(long id, String name, String phone) {


SQLiteDatabase db = [Link](); // Get writable database

ContentValues values = new ContentValues();


[Link]("name", name); // Add new name
[Link]("phone", phone); // Add new phone number

// Update the "contacts" table for the row with the given ID
int rowsAffected = [Link]("contacts", values, "id = ?", new
String[]{[Link](id)});
[Link]();
return rowsAffected; // Returns the number of rows affected by the update
}

 Explanation:
o [Link](): This method updates the rows in the database. You specify which
rows to update using a WHERE clause. If the condition is met, the corresponding rows
are updated with the new values.
o new String[]{[Link](id)}: The WHERE clause is parameterized using id,
which prevents SQL injection attacks.

Handling Update Errors:

 Ensure that the WHERE clause is correctly defined to update the intended rows.
 If no rows match the condition, the method returns 0 (i.e., no rows were affected).

Page | 123
3. Delete Operation (Removing Data from the Database)

The DELETE operation is used to remove rows from a table. You can delete one or multiple rows
based on a specified condition.

Syntax:

DELETE FROM table_name WHERE condition;

Android Example:

public int deleteContact(long id) {


SQLiteDatabase db = [Link](); // Get writable database
// Delete the row with the specific ID from the "contacts" table
int rowsDeleted = [Link]("contacts", "id = ?", new
String[]{[Link](id)});
[Link]();
return rowsDeleted; // Returns the number of rows deleted
}

 Explanation:
o [Link](): The delete() method deletes rows from the table based on the
condition specified in the WHERE clause. The condition here is id = ?, which
identifies the row(s) to delete.
o new String[]{[Link](id)}: The row(s) to be deleted are identified using
the id value.

Handling Delete Errors:

 If no rows match the condition, the method returns 0, indicating no rows were deleted.
 Be careful when using the DELETE operation, especially without a WHERE clause, as it may
delete all rows from the table.

4. Building and Executing Queries

You can also execute raw SQL queries using the execSQL() method in SQLite. This method is
useful for performing operations such as creating tables, altering tables, or executing complex
queries.

Syntax for Executing Queries:

[Link]("SQL_QUERY");

Android Example:

public void createTable() {


SQLiteDatabase db = [Link](); // Get writable database
String createTableQuery = "CREATE TABLE IF NOT EXISTS contacts (id INTEGER
PRIMARY KEY AUTOINCREMENT, name TEXT, phone TEXT);";
[Link](createTableQuery); // Execute raw SQL to create a table
[Link]();
}
Page | 124
Explanation:

 The execSQL() method is used for raw SQL commands that do not return a result (such as
CREATE, DROP, ALTER, etc.).
 In this example, we use execSQL() to create a table if it doesn't already exist.

Example of Full CRUD Operations (Insert, Update, Delete, and Query)

Here is a complete example of how these operations work together in Android:

public class ContactDatabase {

private SQLiteDatabase db;


private MyDatabaseHelper dbHelper;

public ContactDatabase(Context context) {


dbHelper = new MyDatabaseHelper(context);
}

// Opening the database


public void openDatabase() {
db = [Link](); // Open database in writable mode
}

// Insert Contact
public long insertContact(String name, String phone) {
ContentValues values = new ContentValues();
[Link]("name", name);
[Link]("phone", phone);
return [Link]("contacts", null, values); // Insert into contacts
table
}

// Update Contact
public int updateContact(long id, String name, String phone) {
ContentValues values = new ContentValues();
[Link]("name", name);
[Link]("phone", phone);
return [Link]("contacts", values, "id = ?", new
String[]{[Link](id)});
}

// Delete Contact
public int deleteContact(long id) {
return [Link]("contacts", "id = ?", new
String[]{[Link](id)});
}

// Get All Contacts


public Cursor getAllContacts() {
return [Link]("contacts", new String[]{"id", "name", "phone"}, null,
null, null, null, null);
}

// Close database
public void closeDatabase() {
if (db != null && [Link]()) {
[Link](); // Close database
Page | 125
}
}
}

Usage Example:

// Creating an instance of ContactDatabase


ContactDatabase contactDatabase = new ContactDatabase(context);

// Open the database


[Link]();

// Inserting a contact
long contactId = [Link]("John Doe", "1234567890");

// Updating a contact
int updatedRows = [Link](contactId, "John Doe",
"0987654321");

// Deleting a contact
int deletedRows = [Link](contactId);

// Fetching all contacts


Cursor cursor = [Link]();
if ([Link]()) {
do {
String name = [Link]([Link]("name"));
String phone = [Link]([Link]("phone"));
Log.d("Contact", "Name: " + name + ", Phone: " + phone);
} while ([Link]());
}
[Link]();

// Close the database


[Link]();

Best Practices for Using SQLite in Android:

 Use ContentValues: Always use ContentValues for inserting and updating data as it
allows you to insert values in a key-value format, making your code cleaner and more
secure.
 Avoid SQL Injection: Use parameterized queries instead of concatenating strings for SQL
queries to avoid SQL injection vulnerabilities.
 Handle Cursors Properly: Always close the Cursor when it’s no longer needed to prevent
memory leaks.
 Use Transactions: For multiple insert, update, or delete operations, use transactions
(beginTransaction(), setTransactionSuccessful(), and endTransaction()) to ensure
atomicity and improve performance.

Conclusion

The INSERT, UPDATE, and DELETE operations are the core of any database-driven application. By
using SQLite’s methods such as insert(), update(), and delete(), combined with the use of
ContentValues and Cursor, Android applications can efficiently manage data. Always ensure
proper handling of the database connection and closing resources to avoid memory leaks.
Page | 126

You might also like