You are on page 1of 206

Syllabus ...

1.1 Introduction to Android, Open Handset Alliance, Android Ecosystem.


1.2 Need of Android, Features of Android.
1.3 Tools and Software required for Developing an Android Application.
1.4 Android Architecture.

2.1 Operating System, Java JDK, Android SDK.


22 Android Development Tools (ADT).
2.3 Android Virtual Devices (AVDs).
2.4 Emulators
2.5 Dalvik Virtual Machine, Difference between JVM and DVM.
Steps to Install and Configure Android Studio and SDK.

Control Flow, Directory Structure.


3.2 Components of a Screen, Fundamental UI Design.
3.3 Linear Layout, AbsoluteLayout, FrameLayout, TableLayout, RelativeLayout.
= are fle
a woGl Bier! view

41 TextView, EditText, Button, ImageButton, ToggleButton, RadioButton and RadioGroup, CheckBox,


ProgressBar.
4.2 ListView, GridView, ImageView, ScrollView, Custom Toast Alert.
43 Time and Date Picker.

5.1 Intent, Intent_Filter.


5.2 Activity Lifecycle, Broadcast Lifecycle.
5.3 Content Provider, Fragments.
5.4 Service: Features of Service, Android Platform Service, Defining New Service, Service Lifecycle,
Permission, Example of Service.
5.5 Android System Architecture, Multimedia Framework, Play Audio and Video, Text to Speech, Sensors,
Async Tasks.
5.6 Audio Capture, Camera
5.7 Bluetooth, Animation
5.8 SQLite Database, Necessity of SQLite, Creation and Connection of the Database, Extracting Value from
Cursors, Transactions.

6.1 SMS Telephony.


6.2 Location Based Services: Creating the Project, Getting the Maps API Key, Displaying the Map,
Displaying the Zoom Control, Navigating to a Specific Location, Adding Markers, Getting Location,
Geocoding and Reverse Geocoding, Getting Location Data, Monitoring Location.
6.3 Android Security Model, Declaring and Using Permissions, Using Custom Permission.
6.4 Application Deployment: Creating Small Application, Signing of Application, Deploying App on Googlle
Play Store, Become a Publisher, Developer Console.

+, +,
oo

ad +
2,
Contents ...
1. Android
and its Tools 1.1-1.24
1.0 Introduction 1.1
1.1. Introduction to Android 1.1
1.1.1. What is Android? 1.2
1.1.2 Open Handset Alliance (OHA) 1.2
1.1.3. Android Ecosystem 1.3
1.2 Need of Android 1.3
1.2.1. Android Versions 1.4
1.2.3 Features of Android 1.11
1.3. Tools and Software required for Developing an Android Application 1.13
1.4. Android Architecture 1.16
* Practice Questions 1.24
2. Installation and Configuration of Android 2.1 - 2.16
2.0 — Introduction 2.1
2.1 Operating system 2.1
2.1.1 Java JDK 2.1
2.1.2 Android SDK 2.1
2.2 Android Development Tools 2.2
2.3. Android Virtual Device (AVD) 2.5
2.4 Emulators 2.6
2.5 Dalvik Virtual Machine (DVM) 2.6
2.5.1 Difference between Java Virtual Machine (JVM) and Dalvik Virtual Machine (DVM) 2.8
2.6 Steps to install and configure Android Studio and SDK 2.9
2.6.1 System Requirements 2.9
2.6.2 Downloading the Android Studio Package 2.9
2.6.3 Installing Android Studio 2.9
2.6.3.1 Installation on Windows 2.9
2.6.3.2 Installation on MAC OS 2.10
2.6.3.3 Installation on Linux 2.10
2.6.4 Android Studio Setup Wizard 2.11
2.6.5 Installing additional Android SDK Packages 2.12
2.6.6 Making the Android SDK Tools Command Line Accessible 2.13
2.6.6.1 Windows 7 2.14
2.6.6.2 Windows 8 2.14
2.6.6.3 Windows 10 2.15
2.6.6.4 Linux 2.15
2.6.6.5 MAC OS 2.15
2.6.7 Updating Android Studio and the SDK 2.15
* Practice Questions 2.15
3. Ul Components and Layouts 3.1 - 3.26
3.0 Introduction 3.1
3.1. Control Flow 3.2
3.2 Directory Structure 3.4
3.3. Components of a Screen 3.7
3.4 Fundamentals of UI Design 3.9
3.5 Ul! Layouts 3.9
3.5.1 LinearLayout 3.10
3.5.2 AbsoluteLayout 3.13
3.5.3 FrameLayout 3.15
3.5.4 TableLayout 3.19
3.5.5 RelativeLayout 3.23
Practice Questions

4.0 Introduction
41 TextView
4.2 EditText
43 Button 4.10
44 ImageButton 4.13
4.5 ToggleButton 4.17
4.6 RadioButton and RadioGroup 4.21
47 CheckBox 4.26
4.8 ProgressBar 4.30
49 ListView 4.35
4.10 GridView 4.40
4.11 ImageView 4.41
4.12 ScrollView 4.43
413 Custom Toast Alert 4.50
4.14 TimePicker 4.52
4.15 DatePicker 4.56
Practice Questions

5.0 Introduction
5.1 Intent
5.1.1 Explicit Intents
5.1.2 Implicit Intents
5.1.3 Intent_Filter
5.2 Activity Life Cycle 5.10
5.2.1 Broadcast Life Cycle 5.11
5.3 Content Provider 5.12
5.4 Fragments 5.13
5.5 Service 5.17
5.5.1 Features of Service 5.17
5.5.2 Android Platform Service 5.17
5.5.3 Defining New Services 5.17
5.5.4 Service Life Cycle 5.17
5.5.5 Permission 5.19
5.5.6 Example of Service 5.19
5.6 Android System Architecture 5.22
5.7 Multimedia Framework 5.24
5.8 Play Audio and Video 5.25
5.8.1 Play Audio 5.25
5.9 Text to Speech 5.31
5.10 Sensor 5.34
5.10.1 Sensor Framework 5.35
5.11 AsyncTask 5.36
5.12 Audio Capture 5.39
5.13 Camera 5.42
5.14 BlueTooth 5.55
5.15 Animation 5.62
5.16 SQLite Database 5.69
5.16.1 What is SQLite Database? 5.69
5.16.2 Why SQLite/Necessity of SQLite 5.70
5.16.3 Creation and Connetion of Database 5.70
5.16.4 Extracting Values from a Cursors 5.73
5.16.5 Transactions 5.75
* Practice Questions 5.76

6.0 — Introduction 6.1


6.1. SMS Telephony 6.2
6.2 Location Based Services (LBSs) 6.5
6.2.1 Creating the Project 6.5
6.2.2 Getting the Maps API Key 6.6
6.2.3 Displaying the Maps 6.7
6.2.4 Displaying the Zoom Control 6.10
6.2.5 Navigating to a Specific Location 6.12
6.2.6 Adding Markers 6.13
6.2.7 Getting the Location 6.15
6.2.8 Geocoding and Reverse Geocoding 6.16
6.2.9 Getting Location Data 6.18
6.2.10 Monitoring a Location 6.22
6.3 Android security model 6.22
6.3.1 Declaring and Using Permissions 6.24
6.3.2 Using Custom Permission 6.28
6.4 Application Deployment 6.30
6.4.1 Preparing App for Release 6.31
6.4.2 Signing of Application 6.32
6.4.3 Deploying App on Google Play Store (Small Application} 6.34
* Practice Questions 6.41

fe af of
a

1...
Android and its Tools a
Chapter Outcomes...
(=) Explain the given basic terms related to Android system.
@) Explain with sketches Android architecture for the given application.
@] Identify tools and software required for developing the given Android application with justification.
@ Explain significance of the given component in Android architecture.

Learning Objectives...
To understand Basic Concepts in Mobile Application Development and Android
BEE

To learn Android with its Need, Features etc.


To study Android Architecture
To learn Tools in Android and Development of Android Application

sa) INTRODUCTION
4 mobile application, most commonly referred to as an app, is a type of application software
designed to run on a mobile device, such as a smart phone or tablet computer.
Mobile app developmentis the process by which a mobile applications is developed for mobile
devices like Personal Digital Assistants (PDAs), tablet computer or mobile smart phones.
Android is a mobile operating system developed by Google, based on a modified version of the Linux
kernel and other open source software and designed primarily for touchscreen mobile devices such
as smart phones and tablets.
Today, Android is arguably the world’s most popular platform for mobile devices. Android brings
Google and the whole internet to users of smart phones, tablets and other mobile devices. In the
process, it is changing how we communicate with one another.
For application developers, Android is an open platform that provides exciting opportunities for
developing virtually any app imaginable. With a user base that continues growing every day,
Android also has a built-in open marketplace for distributing new apps.
Android applications can be packaged easily and sold out either through a store such as Google Play,
Windows Phone Store, SlideME, Opera Mobile Store, Mobango, F-droid and the Amazon Appstore.

‘ea INTRODUCTION TO ANDROID


Operating System (OS) has developed a lot in last 15 years. It started from black and white phones to
smart phones or mini computers.
Nowadays, most popular used mobile Operating System (OS) is Android. Android is an open source
and Linux-based operating system for mobile devices such as smart phones and tablet computers.
Android was founded in Palo Alto of California, U.S. by Andy Rubin, Rich Miner, Nick Sears and Chris
White during 2003. After it was acquired by Google in 2005.
[1.1]
Mobile Application Development 1.2 Android and its Tools

7e68 What is Android?


Android is a mobile operating system developed by Google, based on the Linux kernel and designed
primarily for touch screen mobile devices such as smart phones and tablets.
The Android is a powerful Operating System (OS) and it supports large number of applications (apps)
in smart phones. These applications are more comfortable and advanced for the users.
The hardware that supports android software is based on ARM architecture platform. The android is
an open source operating system means that it is free and any one can use it.
The Android has got millions of apps available that can help us
managing our life one or other way and it is available low cost ab
in market at that reasons android is very popular.
The android development supports with the full Java
programming language. Even other packages that are API and il
JSE are not supported. The first version 1.0 of android
development kit (SDK) was released in 2008 and latest updated
version is Android 10. Fig. 1.1: Android Logo
Android was unveiled during 2007 along with the founding of the Open Handset Alliance (OHA).
A mobile app is a program designed to run on smart phones, tablet computers and other mobile
devices.
Developing mobile applications for Android platform will give us access to a large and expanding
market in a wide variety of devices.

Open Handset Alliance (OHA)


In August 2005, Google acquired Android Inc., and took over its development work to enter into the
mobile space. Since, then it is in the subsidiary of Google Inc.
In November 2007 Google formed Open Handset Alliance (OHA) in order to develop an open source
software platform for use in mobile devices. The OHA is the group that is in charge of the Android
smart phones operating system.
The OHA is the business alliance that consists of 47 companies (like Google, HTC, LG Electronics,
Motorola, T-Mobile, Samsung Electronics and so on) for developing open standard platform for
mobile devices.
The primary objective of these companies is to developed open standards for mobile devices. The
members of OHA include handset manufactures, chip makers, commercialization companies,
software companies and mobile operators/users.
The goal of the Open Handset
Alliance (OHA) is to create Handset
Manufactures
mobility without borders or
walls where mobile devices and
mobile applications all work
Mobile
together to achieve a single goal Operators
ie, providing users with the
Open Handset
service and applications that Alliance
they want and need. (OHA)

Software Commercializaton
Companies Companies

Fig. 1.2: Android Open Handset Alliance (OHA)


Mobile Application Development 13 Android and its Tools

Android Ecosystem
To learn about Android operating system and develop Android applications, it is very important for
to understand the entire ecosystem of Android and the stakeholders of Android ecosystem.
The stakeholders are the consumers that own Android devices. But there are others as well explained
below:
1. Google develops android.
2. OEMs (Original Equipment Manufacturers) manufacture the hardware, and as well the custom
application components.
3. Application Development Companies are the major contributors to the ecosystem and employ
developers, and also contract out the product development to services companies.
4. Freelance Android Developers have the skill-set to contribute to the ecosystem for android
development, they are who create their own applications and publish them on Google Play Store.
Freelancers can also generate money by developing applications for product companies.

Google
oP
oc @ yy
' a
2.
Consumers
OEMs

App Dev Houses Freelancers

Fig. 1.3: Android Ecosystem

iia ©6=NEED OF ANDROID


Android is a new generation mobile OS which runs on Linux kernel. There are some following points
which describe why we use Android OS:
1, Desktop: The Android phone adds widgets to the desktop. The purpose for the widget, for
example, the Facebook widget allows us to update our facebook desktop. The people widget
allows us to make possible different actions for different contacts right from our desktop. The
message widget allows us to immediately see our e-mail from the desktop.
Connectivity: On one page/desktop we could be able to have four connecting device tool button
like, Turn ON/OFF Bluetooth, Turn ON/OFF WiFi, Turn ON/OFF mobile network, Turn On/Off
GPS and so on. These buttons let us switch ON/OFF instantly which will help us to conserve
battery life.
Browser: The Android OS browser is one of the best browsers on the mobile market. It generally
loads pages faster than Safari or any other browser, has Flash support and simply does
everything a browser should do. For example, iPhone has Safari browser. It is stable, has no Flash
support, so we cannot watch Youtube videos or any related contents, it is not flexible but
monopolistic.
Open to Carrier: If we know Java programming language then we are open to Android world.
Market: Android OS has an android market. The android apps are free and work as well.
Mobile Application Development 14 Android and its Tools

6, Future: The future mobile phones are basically going to be smart phones.
7. Muti-Notification: Android phones have multi-notification system. With android the app have
access to the notification system and call all report.
8. Google Integration: The Android has inbuilt google support. For example, Google Map, G-Mail
etc.
9. Open Source: The code of android OS as well as the apps is available.
10. Endless Personalization: The Android cell phone allows to configuration their mobile to look and
behave exactly like they want.

E@8 Android Versions


e The version history of the Android mobile operating system began with the public release of the
Android beta on November 5, 2007. The first commercial version, Android 1.0, was released on
September 23, 2008.
e Android is continually developed by Google and the Open Handset Alliance, and it has seen a number
of updates to its base operating system since the initial release.
e Following table lists versions of Android:
Sr. Version and
No. Logo Description Features

1. Android 1.0 Android 1.0, the first commercial |1. Access to web email servers,
version of the software, was supporting POP3, IMAP4, and SMTP.
released on September 23, 2008. | 2. Camera support but- however, this
The first commercially available version lacked the option to change
Android device was the HTC the camera's resolution, white
Dream. balance, quality, etc.
3. Wi-Fiand Bluetooth support.
Notifications appear in the Status
bar, with options to set ringtone, LED
or vibration alerts.
5. Supports instant messaging, text
messaging, and MMS.
2. Android 1.1 On February 9, 2009, the Android |1. Ability to save attachments in
1.1 update was released, initially messages.
for the HTC Dream only. Android | 2, Details and reviews available when a
1.1 was known as "Petit Four" user searches for businesses on
internally, though this name was Maps.
not used officially. 3. Support added for marquee in
system layouts.
3. Android 1.5 On April 27, 2009, the Android 15 | 1. Support for Widgets.
! update was released, based on| 2, Video recording and playback in
Linux kernel 2.6.27. This was the MPEG-4 and 3GP formats.
first release to officially use a|3, Ability to upload videos to YouTube.
codename based on a dessert item | 4 Supports animated screen
("Cupcake"), a theme which would transitions.
be used for all releases| 5 uto-rotation option.
henceforth.
Contd_.
Mobile Application Development 15 Android and Its Tools

4. Android 1.6 On September 15, 2009, Android Voice and text entry’ search
Donut 1.6 - dubbed Donut - was enhanced to include bookmark
released, based on Linux kernel history, contacts, and the web.
2.6.29, Support for WVGA (Wide Video
Graphics Array) screen resolutions.
Ability for developers to include
their content in search results.
Supports indicators of battery
usages allows users to determine
which applications/services takes
most battery power.
New control panel for setting up and
configuring Virtual Private Network
(VPN).
Android 2.0/2.1 On October 26, 2009, the Android Improved typing speed on virtual
Eclair 2.0 SDK was released, based on keyboard, with smarter dictionary


Linux kernel 2.6.29 and that learns from word usage and
codenamed Eclair. includes contact mames as
suggestions.
Numerous new camera features,
including flash support, digital
zoom, scene mode, white balance,
color effect and macro focus.
Bluetooth 2.1 support.
Microsoft Exchange email support,
with combined inbox to browse
email from multiple accounts in one
page.
Expanded Account sync, allowing
users to add multiple accounts to a
device for synchronization of email
and contacts.
Refreshed browser UI with
bookmark thumbnails, double-tap
zoom and support for HTML5.
Android 2.2 On May 20, 2010, the SDK for Speed up of the application
Froyo Android 2.2 (Froyo, short for performance due to JIT compiler.
frozen yogurt) was released, Support for the Android Cloud to
based on Linux kernel 2.6,32. Device Messaging (C2DM) service,
Improved Microsoft Exchange
support, including security policies,
auto-discovery etc.
Supports USB tethering and Wi-Fi
hotspot functionality.
Mobile Application Development 1.6 Android and its Tools

Support for installing applications to


the expandable memory, (memory
card).
Support for high-PPI displays (up to
320 ppi), such as four-inch 720p
screens.
Quick switching between multiple
keyboard languages and _ their
dictionaries.
7. | Android 2.3/2.4 On December 6, 2010, the Faster, more intuitive text input in
Gingerbread Android 2.3 (Gingerbread) SDK virtual keyboard, with improved
was released, based on Linux accuracy, better suggested text and
kernel 2.6.35. voice input mode.
Support for extra-large screen sizes
and resolutions (WXGA and higher).
support for VoIP (Voice over Internet
Protocol) internet telephony.
Updated user interface design with
increased simplicity and speed.
Support for Near Field
Communication (NFC), allowing the
user to read an NFC tag embedded in
a poster, sticker, or advertisement.
Support for multiple cameras on the
device.
Support for voice or video chat using
Google Talk.
8. Android On February 22, 2011, the Android Optimized tablet support with a new
3.0/3.1/3.2 3.0 (Honeycomb) SDK - the first “holographic” user interface.
Honeycomb tablet-only Android update — was Added System Bar, featuring quick
released, based on Linux kernel access to notifications, status, and
2.6.36. The first device featuring soft navigation buttons, available at
this version, the Motorola Xoom the bottom of the screen.
tablet, was released on February Multiple browser tabs replacing
24, 2011. browser windows, plus form auto-fill
and a new “incognito” mode allowing
anonymous browsing.
Quick access to camera exposure,
focus, flash, zoom, front-facing
camera, time-lapse, and _ other
camera features.
Simplified multitasking - tapping
Recent Applications in the System
Bar allows users to see snapshots of
the tasks underway and quickly jump
from one application to another.
Mobile Application Development 17 Android and its Tools

Redesigned keyboard, making typing


fast, efficient and accurate on larger
screen sizes.
Support for multi-core processors.
Ability to encrypt all user data.
Resizable Home screen widgets.
10. High-performance Wi-Fi lock,
maintaining high-performance Wi-
Fi connections when device screen is
off.
11. Improved hardware support,
including optimizations for a wider
range of tablets.
12. Increased ability of applications to
access files on the SD card, e.g. for
synchronization.
9. Android The SDK for Android 4.0.1 (Ice Ability to access applications directly
4.0/4.0.1/4.0.2 Cream Sandwich), based on Linux from lock screen.
Ice Cream kernel 3.0.1, was publicly released Ability to shut down applications
Sandwich on October 19, 2011. Ice Cream from the recent apps list with a
Sandwich was the last version to swipe.
officially support Adobe Systems’ Ability to access applications directly
Flash player. from lock screen.
Improved visual voicemail with the
ability to speed up or slow down
voicemail messages.
Soft buttons from Android 3.x are
now available for use on phones.
Improved camera application with
zero shutter lag, time lapse settings,
panorama mode, and the ability to
zoom while recording.
Support for the WebP image format.
8. Android Beam, a_ near-field
communication feature allowing the
rapid short-range exchange of web
bookmarks, contact info, directions,
YouTube videos and other data.
Improvements to graphics,
databases, _spell-checking and
Bluetooth functionality.
10. Smoother screen rotation and
Improved phone number
recognition.
Contd...
Mobile Application Development 18 Android and its Tools

10. Android Google announced Android 4.1 Smoother User Interface (UI):
4.1/4.2/4.3 (Jelly Bean) at the Google I/O (i) Vsync timing across all drawing
Jelly Bean conference on June 27, 2012. and animation done by the
Based on Linux kernel 3.0.31, Jelly Android framework, including
Bean was an incremental update application rendering, touch
with the primary aim of events, screen composition and
improving the functionality and display refresh.
performance of the user (ii) Triple buffering in the graphics
interface. Jelly Bean 4.2 was based pipeline.
on Linux kernel 3.4.0, and . Bi-directional text and other
debuted on Google's Nexus 4 and language support and Expandable
Nexus 10, which were released on notifications.
November 13, 2012. Google Improved camera application and
released Jelly Bean 4.3 under the support Multichannel audio.
slogan "An even sweeter Jelly . Tablets with smaller screens now use
Bean" on July 24, 2013. an expanded version of the interface
layout and home screen used by
phones.
Lock screen improvements,
including widget support (removed
again in 2014) and the ability to
swipe directly to camera.
. Supports Group Messaging.
OpenGL ES 3.0 support, allowing for
improved game graphics.
. Reworked camera UI, previously
introduced on Google Play edition
phones.
11. Android 4.4 Google announced Android 4.4 Built-in screen recording feature.
KitKat KitKat on September 3, 2013 and Ability for applications to use
released October 31, 2013. “immersive mode" to keep the
navigation and status bars hidden
while maintaining user interaction.
Wireless printing capability.
Storage Access Framework, an API
allowing apps to retrieve files in a
consistent manner,
Better application compatibility for
the experimental Android Runtime
(ART).
Enforcing SELinux (Security-
Enhanced Linux).
New framework for UI transitions.
. Ability for applications to trigger
translucency in the navigation and
status bars.
Contd...
Mobile Application Development 1.9 Android and its Tools

12. Android 5.0/5.1 Android 5.0 "Lollipop" was Support for 64-bit CPUs.
Lollipop unveiled under the codename OpenGL ES3.1 and _ Android
"Android L" on June 25, 2014, Extension Pack (AEP) on supported
during Google I/O. It became GPU configurations.
available as official over-the-air Android Runtime (ART) with Ahead-
(OTA) updates on November 12, Of-Time (AOT) compilation and
2014, for select devices that run improved Garbage Collection (GC),
distributions of Android serviced replacing Dalvik that combines
by Google, including Nexus and bytecode interpretation with trace-
Google Play edition devices. Its based Just-in-Time (JIT) compilation.
source code was made available User-customizable priorities for
on November 3, 2014. application notifications and smart
lock feature.
A flashlight-style application is
included, working on supported
devices with a camera flash. Audio
input and output through USB
devices.
. Third-party applications regain the
ability to read and modify data
located anywhere on_ external
storage, such as on SD cards.
WebViews receive updates
independently through Google Play
for security reasons, instead of
relying on system-wide vendor
updates.
. Ability to join Wi-Fi networks and
control paired Bluetooth devices
from quick settings.
High-definition voice calls, available
between compatible 4G LTE devices
running Android 5.1.
13. Android 6.0 Android 6.0 "Marshmallow" was Contextual search from keywords
Marshmallow unveiled under the codename within apps.
“Android M" during Google I/O on . Introduction of Doze mode, which
May 28, 2015, for the Nexus 5 and reduces CPU speed while the screen
Nexus 6 phones, Nexus 9 tablet, is off in order to save battery life,
and Nexus Player set-top box, . App Linking for faster instinctive
under the build number MPZ44Q. opening of links with corresponding
The third developer preview applications.
(MPA44G) was released on August
. Native fingerprint reader support.
17, 2015 for the Nexus 5, Nexus 6,
. Automatic full data backup and
Nexus 9 and Nexus Player devices,
restore for apps.
and was updated to MPA44I that
brought fixes related to Android
for Work profiles.
Contd_.
Mobile Application Development 1,10 Android and its Tools

14, | Android 7.0/7.1 | Android "Nougat" (codenamed N |1. Ability to screen zoom.
Nougat in-development) is the major 7.0 |2. Improvements to file browser.
ee release of the Android operating |3. Daydream Virtual Reality platform
system. It was first released as a (VR interface).
developer preview on March 9,|4- Multi-window support, —_ which
Ry goer 2016, with factory images for supports floating apps on a desktop
current Nexus devices, as well as layout.
with the new “Android Beta 5. New JIT Compiler, making for 75
Program" which allows supported percent faster app installations and

devices to be upgraded directly to ee ae reduction in compiled


the Android Nougat beta via over- 6. Just In Time (JIT) compiler with code
the-air update. Final release was profiling to ART, which lets it
on August 22, 2016. constantly improve the performance
of Android apps as they run.
7. Picture-in-picture support for
Android TV.
15. | Android 8.0/8.1 | Android Oreo is the 8 major |1. Multi-display support.
Oreo release of the Android operating |2. Support Google Play Protect.
7 system. It was first released as a |3. 2 times faster boot time.
developer preview on March 21,|4- Picture-in-picture support and
2017, with factory images for Adaptive icons.
© current Nexus and Pixel devices. |5- Neural networks API and Shared
> a The final developer preview was memory API functionality.
é released on July 24, 2017, with the |©- Supports Programmatic — Safe
stable version released in August Browsing actions:
2017. 7. Visual changes to 'Power OFF' and
‘Restart’ including a new screen and
floating toolbar.
16. | Android9.0 Pie | Android "P" is the 9" major |1. Lock screen security changes include
version of the Android operating the possible return of an improved
system. It was first announced by NFC Unlock.
Google on March 7, 2018, and the 2. Support for display cutouts.
first developer preview was 3. A new _ gesture-based _system
released on the same day. Second ae agi the OS . like
. . . on an iPhone X, remove ome
BT aut‘ die ve ‘ ee, button and multitask button.
.. 4. A new "Lockdown" mode which
final beta of Android P (fifth : : * a gs
. . disables biometric authentication
preview, also considered as a once activated.
Release Candidate") was released 5. Richer messaging notifications.
on July 25, 2018. The first offical 6. New transitions for switching
release was released on August 6, between apps, or activities within
2018. apps.
7. The "dock" now has a_ semi-
transparent background and
Rounded corners across the UI.
8. New User Interface (UI) for quick
setting menu.
Contd...
Mobile Application Development 111 Android and its Tools

17. Android 10 Android 10is the10™ major New permissions to access location

a
released 17" version of in background and to access
the Android mobile operating background and to access photo,
system on September 3, 2019. video and audio files.
A feature known as “bubbles” can be
used to present content from
supported apps in pop-up overlays,
(similarly to the overlay-based “chat
heads" feature of Facebook
Messenger). Apps can spawn bubbles
via notifications.
Several major security and privacy
changes are present in Android 10
{apps can be restricted by users to
only having access to location data
when they are actively being used in
the foreground. There are also new
restrictions on the launching of
activities by background apps)
Android Go for Android 10 uses less
storage than the previous release,
and has improved the enhancement
of speed, security and upgraded
storage tracking.
Android 10 features with the new
encryption standard
WPA3 encryption protocol and
Enhanced Open, which introduce
opportunistic encryption for Wi-Fi.
Support biometric authentication,

§es9 Features of Android


e Fig. 1.4 show features of Android OS.
Open Source

External storage

Storage

(| * Streaming Media Support

ss Voice based features

Video Calling

Multitasking
Web Browser
Accessibility
Fig. 1.4: Features of Android
Mobile Application Development 1,12 Android and its Tools

Android is an open source, lightweight and powerful operating system which supports great
features. Few features of them are listed below:
1, Storage: SQLite, a lightweight relational database, is used for data storage purposes.
2, Multitasking: Multitasking of application, with unique handling of memory allocation, will be
existing.
3. Web Browser: The web browser available in Android OS is based on the open-source WebKit
layout engine, attached with Chrome’s V8 JavaScript engine. The browser scores 100/100 on top
of the Acid3 test on Android 4.0.
Open Source: Android is open-source operating system. The source code for Android is open to
the public, dissimilar iOS, which is kept secret by Apple. This way that anyone can work on the
operating system, not only one company developers. Therefore, app developers for android
devices are able to implement extra features of their apps, due to the access they have to contain
the source code. Again these are only some of the unique features to Android. iOS also have
many key abilities that are missing on android devices. In the end it is up to us to decide which
operating system we would rather have. Anyone of we choose will be the right decision for us.
Accessibility: Built in text to speech in Android OS is provided by Talk back for people with low
or no vision, Enhancements for people through hearing disabilities are available as is other aids.
Media Support: Android OS supports the audio/video/still media formats like WenM, H.263,
H.264, AAC, HE-AAC, MPEG-4 SP, AMR, AMR-WB, MP3, MIDI, WAV, JPEG, PNG, GIF, OggVorbis,
FLAC, BMP, WebP.
Streaming Media Support: Android OS support RTP/RTSP streaming, HTML progressive
download. Adobe Flash Straming (RTMP) and HTTP Dynamic Streaming are supported by the
Flash plugin. Apple HTTP Live Streaming is support through RealPlayer for Android, and through
the operating system for the duration Android 3.0 (Honeycomb).
Voice Based Features: Google search through voice has been available since Android operating
system release. Voice activities for navigation, calling, texting etc. are supported on android 2.2
forwards. As of Android 4.1, Google has expanded Voice actions with the ability to talk back and
read answers from Google's Knowledge Graph when queried with specific commands. The ability
to control hardware have not been implemented yet.
Multitouch: Android OS have native support for multitouch which was initially made available
in handsets such as HTC Hero. These features was originally disabled at the kernel level. Google
has released an update version for Nexus One and Motorola Droid which enables multi touch
natively.
10. External Storage: Number of Android devices include microSD slot and can read microSD cards
formatted with FAT32, Ext3 or Ext4 file system. To allow use of high-capacity storage media such
as USB flash drives and USB HDDs, many Android tablets also include USB ‘A’ receptacle. Storage
format with FAT32 is handled by Linux Kernel VFAT driver. As third party solutions are necessary
to handle other popular file systems such as NTFS, HFS Plus and ex FAT.
iL. Video Calling: Video calling through Google Talk is available within Android 2.3.4 and later.
Gingerbread allows Nexus § to place Internet calls with a SIP account. This allows for enhanced
VoIP dialing to other SIP accounts and even phone numbers. Skype 2.1 offer video calling in
android 2.3, include front camera support, Users with the Google+ Android app can video chat
with other Google+ users through hangouts,
12. Handset Layout: The Android OS is adaptable to the size of the display device. The graphical
rendering of individual screens is done by the 2D/3D library based on OpenGL ES 2.0
specifications and traditional of smart phones.
13. GCM: Google Cloud Messaging (GCM) is a service that lets developers send short message data to
their users on Android devices, without needing a proprietary sync solution.
14. Wi-Fi Direct: A technology that lets apps discover and pair directly, over a high-bandwidth peer-
to-peer connection.
Mobile Application Development 1,13 Android and its Tools

TOOLS AND SOFTWARE REQUIRED FOR DEVELOPING AN ANDROID


APPLICATION
Generally to build an application for Android we should have Java Development Kit (JDK), Android
SDK, and a development environment.
The Android SDK is compatible with Windows, Mac and Linux operating systems to build android
applications based on our requirements.
We can setup android development environment using following two ways:
1. Setup Eclipse IDE Manually (Depreciated) and
2. Android Studio.
Initially Google supported a Manual Eclipse IDE Setup for android development environment by
downloading required components like Eclipse IDE, Android SDK, Java Development Kit (JDK) etc.
from official site.
Afterwards Google introduced a component called Android Studioto make environment setup
process simple. Android Studio is the official IDE for Android application development.
By using Android Studiobundle we can easily setup android development environment in any
operating system to implement Android applications.
Android Studio is the combination of components (Eclipse IDE, Android SDK, Android Virtual Device
and Eclipse Plugin) to allow users to implement android applications.
By downloading Android Studiodirectly from Google website to setup we can easily setup
development environment.
Check following steps to know more details about setting up android development environment to
implement required apps using Android Studio.
Download and Installing Android Studio:
In this section we are going to explain how to install android studio on windows machine which is
having Windows 10 operating system.
Download the latest version of Android Studio from above URL and launch Android Studio.exe file by
double clicking on it.
The initial android studio setup screen will open like as shown below in that click Next to continue
for further steps of environment setup, (See Fig. 1.5).
Now we need to select a required components to setup an android environment. Here we selected all
three components (Android Studio, Android SDK and Android Virtual Device) and click Next like as
shown in Fig. 1.6.
am Android Studio Setup — x @® Andro Studio Setup = x

Choose Components
Welcome
to Android Studio Setup Choose which features of Android Stixbo you want to install,

Setup wil guide you through the installation of Androsd (Check the components you want to instal and uncheck the components you don’t want to
Studio, retell. Cick Next to continue.
It is recommended
that you dose al other applicators
before gtarting Setup. The: wal make it porsile to upclate
relevant system files without having to reboot your ‘Select components
to install:
comouter . [7] Android sox
Oick Next to contmue. [¥] Android Virtual Device

‘Space required: 5.1G5

<Back Cancel (seed ne) [eet]


Fig. 1.5 Fig. 1.6
Mobile Application Development 1.14 Android and its Tools

« Now we need to agree the License agreements to proceed further, click on I Agree button like a
shown in Fig. 1,7.
* Now we need to specify the local machine drive location to install Android Studio and Android SDK.
After selecting the location path to install required components, click Next like as shown in Fig. 1.8.
- x wm Androed Studio Setup - x
Homme Agreed Cenhguanen Serge
Please review the homme term before rstaling Andros Stucke fetal Locators

Press Page oer to ane the rest of the agreement Avsired Stucke Inetalation Locator
Fo Get arte seth te Andre SOM, vou must agree he Feber
acree to et ‘ter
terme ard * The location
ee spectiedeemust huew at inet S00) of free apace,

| c:lProgram Pies |Androct rere Sache |


[fies a the Amro SCH Licerne Agreement (the Loree Agreement’)
|. return
ke and rc te ens Aarne se dey seen Ee reine
shating ee Arad aystem flex, packaged AP, amd STR Mirary fhes anc hoc, if and
[chen they are mack avaliable) m kcerwed bs you subgect ts ur terme of the Ler Se ale recs eater st amet 3.208 ob hee sper.
[Apeeset The Leerme Agreement form a legally ring contact betmeen youard —_
* | ©: )Lisers purchaser’ eit acai! a
IV yo accent the tere of the agreement, cick I Agnes t continue. You must accept fhe
agreement i etal Arcrod Studio.

a <tod |[et>) cored


Fig. 1.7 Fig. 1.8
e Now select the start menu folder to create a shortcuts for android studio and click Install like as
shown in Fig. 1.9.
e Once we click Install button the installation process will start and click Next after completion of
installation like as shown in Fig. 1.10.
= x am Android Studio Setup -

Qwose Sat Meru Fobter batafieteon Complete


Choose a Start Menu falter for the Android Studs shorten. Setup was completed succesafuly.

‘Select the Start Mera felier in which you would Ie te create the program's shertouts. You Compieted
anagoie tame ncain tian mee. a
fered et eta} J Show deta |
hp «
Accesetality
Admennntrateee Took
Chrome Japs
Osa
Docker
Gt
HP Melp and Support
5
evel *
(F1de net cremate shorteuta

{tie | wtt] | coment <td coral


Fig. 1.9 Fig. 1.10
e After that it will show installation completion wizard in that click Finish to launch android studio
like as shown in Fig, 1.11.
e¢ While launching Android Studio it will give us an option to import settings from previous version of
studio. In case if we don’t have any previous version, select second option and click OK like as shown
in Fig. 1.12.
om Dndiroed Yate hetup -

‘Completing
Android Studio Sotup

(Chek Frrwaty tov che Setar.

You can impart your settings from a previous version of Studio.

Berane CO Fiment te port setings from a esto beaten


‘Specify config folder or installation home of the previous version of Studio:
i S tutlane com Il )
(@ Ido not have a previous version of Studio or I do not want to import my settings

a)
Fig. 1.11 Fig. 2.12
Mobile Application Development 1,15 Android and its Tools

Now android studio will open a welcome wizard window in that click Next to validate our current
Android SDK and development environment setup like as shown in Fig. 1.13.
Now select a Standard installation type and click Next to install a common settings and options like
as shown in Fig. 1.14.
OD Antica
Stentie Siete Wisard - Oo & ® Android Studio Setup Wizard - ao x

‘Wakccrma bacS! Thai uatup wit will wale your cument Andtéed SDI and
dewiopand exmemmant tetup Yeu all hoe Das option to deserletdl a rub Lesa
SDE or uae wn evicting installation. Once the uenap aurard completex, you cam (Choose
the type of setup you want for Android Studia:
imped an exichng Androl pp inte Aadrnd Stade on stat a new Andiced paegect.
(© Senden
Androad Studio will be ovstalled sath the most common rethngs and options.
Recommended for most wiers.

a O CatomYou can cuttomize installaton settings and components inctathed.


| EE (cone) | Previous | QI | conce Finish

Fig. 1.13 Fig. 1.14


Now verify settings and click Finish to complete android studio setup process like as shown in
Fig. 1.15.
After completion of required components installation click on Finish like as shown in Fig. 1.16.
OP Androvd Stushe Setue Wiceed - o x

yaad Downloading Components

H you mest te cevere of change any of your installahos nethegn, click Prevsout. POTENT UME ERAT? LAP pOe TR Lots Lane et a) sae soUToeN mnereis- 27 pecwege.
ma
Parsing Cr \Osers\ sortasert Apo cal Aetrodat Sain systes-Images\ andtrois-2¥\geogie_apis
‘Curverd Setonege at@\package.mml
| SD Compenents to Download Parsing C:\lsers\surdaseri\AppDete\Locel\Astreit Sain tools \peckage.mat
Androl SE Build Took 26 | 52.1 MB
Andre SC Pucferm-Tooh = 7.16 MB Andreid SOE ia up to dete.
|_ Google Reponingy: 1a

1) a ied

g- Fig. 1.16
After completion of all required components installation we will be able to see Android Studio
welcome window like as shown in Fig. 1.17.
© Weekcme be Ancona She - x

Android Studio
Version 2.3.3

(0 Matt one Andread Taste pened


Opesos eaunng Andros’
testes paper
Chet
et pect em Verma Comet =
of bepar pejt ficipes ADT, fii ote
(Cf henge aeArneson
repr
@tutiene com
SO Conige- Gali ~

Fig. 1.17
This is how we can setup android development environment on windows machine which is having
Windows 10 operating system using android studio IDE.
lobile Application Development 1,16 Android and its Tools

<3) ANDROID ARCHITECTURE


Fig. 1.18 shows architecture of Android OS. Android architecture is a software stack of components
to support a mobile device needs.
Android software stack contains a Linux Kernel, collection of C/C++ libraries which is exposed
through an application framework services, runtime and application.
The main components of android architecture are, Applications, Android Framework, Android
Runtime, Platform Libraries and Linux Kernel.
In these components Linux Kernel is the main component in android to provide its operating system
functions to mobile and Dalvik Virutal Machine (DVM) which is responsible for running a mobile
application.
Applications

(tone) (_coneas ) (_ preme ) (browser) |


[ SMS | ( E-Mail | [ Clock | ( Calander ] [

Applications Framework

[ Activity Manager } [ window Manager ] [ content Providers | ( View System }

[ Package Manager ] (Telephony Manager] [Resource Manager | ( Location Manager ] [Netification Manager]

Libraries Android Runtime

Surface Manager ] ( Media Framework ] ( SQLite }

OpenGL/ES } ( FreeType ] [ Webkit } Dalvik Virtual Machine

SGL } ( SSL ] ( Libe ]

Linux Kernel

Display Driver | [ Camera Driver | [Flash Memory Driver] [ Binder (IPC)Driver |

Keypad Driver ] [ Wi-Fi Driver ] ( Audio Driver ] [Power Management |


_

Fig. 1.18: Architecture of Android


Fig. 1.18 shows the following various layers that make up the Android Operating System (OS):
1. Applications:
The top layer of Android architecture is Applications. The native and third party applications like
Contacts, Email, Music, Gallery, Clock, Games, etc. whatever we will build those will be installed on
this layer only.
The application layer runs within the Android run time using the classes and services made available
from the application framework.
Application Framework:
§

The Application Framework provides the classes used to create an Android application. It also
provides a generic abstraction for hardware access and manages the user interface and application
resources.
It basically provides the services through which we can create the particular class and make that
class helpful for the Applications creation.
Mobile Application Development 1.17 Android and its Tools

The application framework includes services like telephony service, location services, notification
manager, NFC service, view system, etc. which we can use for application development as per our
requirements.
3. Android Runtime:
* Android Runtime environment is an important part of Android rather than an internal part and it
contains a components like core libraries and the Dalvik Virtual Machine (DVM).
* The Android run time is the engine that powers our applications along with the libraries and it forms
the basis for the application framework.
(i) Dalvik Virtual Machine (DVM) is a register-based virtual machine like Java Virtual Machine
(JVM). It is specially designed and optimized for android to ensure that a device can run multiple
instances efficiently. It relies on the Linux kernel for threading and low-level memory
management.
(ii) The core libraries in android runtime will enable us to implement an android applications using
standard JAVA programming language.
4. Platform Libraries:
e The Platform Libraries includes various C/C++ core libraries and Java based libraries such as SSL,
libc, Graphics, SQLite, Webkit, Media, Surface Manger, OpenGL etc. to provide a support for android
development.
« Following are the summary details of some core android libraries available for android development.
Media library for playing and recording an audio and video formats:
(i) The Surface manager library to provide a display management.
(ii) SGLand OpenGL Graphics libraries for 2D and 3D graphics.
(iii) SQLite is for database support and FreeType for font support.
(iv) Web-Kit for web browser support and SSL for Internet security.
5. Linux Kernel:
¢ Linux kernel is a bottom layer and heart of the android architecture. It exists at the root of android
architecture and contains all the low-level device drivers fro the various hardware components of an
Android device.
* Linux Kernel is responsible for device drivers, power management, memory management, device
Management and resource access.
* It manage all the drivers such as display drivers, camera drivers, Bluetooth drivers, audio drivers,
memory drivers, etc. which are mainly required for the android device during the runtime.
¢ The Linux kernel will provides an abstraction layer between the device hardware and the remainder
of the stack. It is responsible for memory management, power management, device management,
resource access, etc.
Android (Hello World) Example:
Android Studio is the official Integrated Development Environment (IDE) for Android app
development, based on IntelliJ IDEA.
Android Studio offers even more features that enhance our productivity when building Android
apps, such as:
A fast and feature-rich emulator.
awphwn Pp

User friendly IDE.


A flexible Gradle-based build system.
A unified environment where we can develop for all Android devices.
Instant Run to push changes to the running app without building a new APK.
Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging
and App Engine.
Mobile Application Development 1.18 Android and its Tools

e The first step is to create a simple Android Application using Android studio. When we click on
Android studio icon, it will show screen as shown in Fig. 1.19.
* We can start our application development by calling Start a new Android Studio project. In a new
installation frame should ask Application name, package information and location of the project.
(See Fig. 1.20).

* Welcome to Android Studio

cnet Penge Cie Sat

a Mae a rare Ardem asthe prope?

& par ors amacting Arden Ss propre

i lenpatt on Aer ete et

_ (Che's cut prague feos Niemen Comme

EE rt pec en AT. Gen te


Bi Condigare

e Docs end Hee Tes

Fig. 1.19
e After entered application name, it going to be called select the form factors our application runs on,
here need to specify Minimum SDK, in we have declared as API23: Android 6.0(Mashmallow),
(See Fig. 1.21).
e The next level of installation should contain selecting the activity to mobile, it specifies the default
layout for Applications (See Fig. 1.22).

yd tet Be cy eRe)

Fig. 1.21 Fig. 1.22

* At the final stage it going to be open development tool to write the application code.
.
ew
Mobile Application Development 1,19 Android and its Tools

Anatomy of Android Application:


« Before we run our app, we should be aware of a few directories and files in the Android project,
(See Fig. 1.24).
ae 0+ oF
v © manifests 5
1 AndroidManifestam|
v Oj. ————__ 1
> £ com.ecampletutonialspoint7.myapplication
» 1 com.exampletutorialspoint7.myapplication (androidTest)
» [) com.examplettutonalspoint?.myapplication (test)
vy Gars

5 drawable 2
v ED layout
i activity_mainaml 3
* ED mipmap
» [ic launcher.png (5)
¥ 2) values 4 |
& colorsxmi
» [0 dimens.xml (2)
fee stringsxml
& stylesxml
¥ © Gradle Scripts
(© build.gradle (Project: MyApplication)
e build.gradie (Module app) —_—$——— ns 6
E) proguard-rules.pro (ProGuard Rules for app)
(a gradle.properties (Project Properties)
& settings.gradle (Project Settings)
(ai local.properties (SDK Location)

Fig. 1.24: Anatomy of Android Application


¢ The description of Fig. 1.24 is given in following table:
Sr. No. Folder, File & Description
1, Java: This contains the java source files for our project. By default, it includes an
MainActivity.java source file having an activity class that runs when our app is launched
using the app icon.
2. res/drawable-hdpi: This is a directory for drawable objects that are designed for high-
density screens.
res/layout: This is a directory for files that define our app's user interface.
4, res/values: This is a directory for other various XML files that contain a collection of
resources, such as strings and colours definitions.
5. AndroidManifest.xml: This is the manifest file which describes the fundamental
characteristics of the app and defines each of its components.
6. Build.gradle: This is an auto generated file which contains compileSdkVersion,
buildToolsVersion, applicationld, minSdkVersion, targetSdkVersion, versionCode and
versionName.
« The given section will give a brief overview of the important application files.
The Main Activity File:
e The main activity code is a Java file MainActivity.java. This is the actual application file which
ultimately gets converted to a Dalvik executable and runs our application.
Mobile Application Development 1,20 Android and its Tools

Following is the default code generated by the application wizard for application:
package com.example.helloworld;
import android. support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}
Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. The
onCreate() method is one of many methods that are figured when an activity is loaded.
The Manifest File:
Whatever component we develop as a part of our application, we must declare all its components in
a manifest.xml which resides at the root of the application project directory.
This file works as an interface between Android OS and our application, so if we do not declare our
component in this file, then it will not be considered by the OS.
For example, a default manifest file will look like as following file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.niralibooks.myapplication”>
<application
android: allowBackup="true"
android: icon="@mipmap/ic_launcher"
android: label="@string/app_name"
android: supportsRtl="true"
android: theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android: name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER” />
</intent-filter>
<factivity>
</application>
</manifest>
Here, <application>...</application> tags enclosed the components related to the application.
Attribute android:icon will point to the application icon available under res/drawable-hdpi. The
application uses the image named ic_launcher.png located in the drawable folders.
The <activity> tag is used to specify an activity and android:name attribute specifies the fully
qualified class name of the Activity subclass and the android:label attributes specifies a string to use
as the label for the activity. We can specify multiple activities using <activity> tags.
Mobile Application Development 1.21 Android and its Tools

The action for the intent filter is named android.intent.action.MAIN to indicate that this activity
serves as the entry point for the application. The category for the intent-filter is named
android.intent.category.LAUNCHER to indicate that the application can be launched from the
device's launcher icon.
The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to the
app_name string defined in the strings.xml file, which is "HelloWorld”. Similar way, other strings get
populated in the application.
Following is the list of tags which we will use in our manifest file to specify different Android
application components:
1. <activity> elements for activities.
2, <service> elements for services.
3. <receiver> elements for broadcast receivers.
4. <provider> elements for content providers.
Android Application Components:
Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that describes
each component of the application and how they interact.
There are following four main components that can be used within an Android application:
1. Activities: They dictate the UI and handle the user interaction to the smart phone screen.
2, Services: They handle background processing associated with an application.
3. Broadcast Receivers: They handle communication between Android OS and applications.
4, Content Providers: They handle data and database management issues.
There are additional components which will be used in the construction of above mentioned entities,
their logic and wiring between them. These components are:
1. Fragments: Represents a portion of user interface in an Activity.
2. Views: UI elements that are drawn on-screen including buttons, lists forms etc.
3. Layouts: View hierarchies that control screen format and appearance of the views.
4, Intents: Messages wiring components together.
5. Resources: External elements, such as strings, constants and drawable pictures.
6. Manifest: Configuration file for the application.
Strings File:
The strings.xml file is located in the res/values folder and it contains all the text that our application
uses. For example, the names of buttons, labels, default text, and similar types of strings go into this
file, This file is responsible for their textual content.
For example, a default strings file will look like as following file:
<resources>

<string name="app_name">HelloWorld</string>
<string name="hello_world" >Hello world! </string>
<string name="menu_settings” >Settings</string>
<string name="title_activity_main” >MainActivity</string>
</resources>

Layout File:
The activity_main.xml is a layout file available in res/layout directory, that is referenced by our
application when building its interface.
Mobile Application Development 1,22 Android and its Tools

We will modify this file very frequently to change the layout of application, For "Hello World!”
application, this file will have following content related to default layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android: layout_width="match_parent"
android: layout_height="match_parent" >
<TextView
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: layout_centerHorizontal="true”
android: layout_centerVertical="true"
android: padding="@dimen/padding
medium"
android: text="@string/hello_world"
tools:context=".MainActivity” />

</RelativeLayout>
This is an example of simple RelativeLayout. The TextView is an Android control used to build the
GUI and it have various attributes like android:layout_width, android:layout_height etc which are
being used to set its width and height etc.
The @string refers to the strings.xml file located in the
res/values folder. Hence, @string/hello_world refers to the
hello string defined in the strings.xml file, which is "Hello
World!".
Running the Application:
Let us try to run our Hello World! application we just
created. We assume we had created our AVD while doing
environment set-up. To run the app from Android studio,
open one of our project's activity files and click Run @ icon
from the tool bar.
Android studio installs the app on our AVD and starts it
and if everything is fine with our set-up and application, it
will display following Emulator window as shown in
Fig. 1.25. Fig. 1.25
Advantages of Android Operating System:
1. Supports 2D and 3D Graphics: It supports various platforms like 2D and 3D. Earlier we used to
watch movies and play games almost in 2D, but nowadays various applications are using 3D
format. To provide different graphics in videos, games OS should support 3D format. Android
supports 2D and 3D format to provide a better advantage in videos and in games.
Supports Multiple Languages: Android supports different languages. We can say all famous
languages about more than 100. By using this feature it is easy to adopt to different languages.
Earlier in the feature phones English is to be the only language in the mobile devices.
Faster Web Browser: As it enabled with web browser we surf web easily without complexity just
like in a computer. It easily loads multimedia so that it makes web browsing faster.
Video Calling: Faster data connection enables to do video call. We can take advantage of
bandwidth and new generation networks using Android.
Mobile Application Development 1.23 Android and its Tools

5. Open Source Framework: It makes users to make their own applications and to make changes
required for themselves. Enthusiasts can make Andriod more powerful and useful by developing
themselves. As it is an open source operating system, we can use it easily and without cost in the
equipments.
Uses of Tools are Very Simple: It makes use of a single button to do more than assigned work.
For example, volume control button can be made to click a photo by changing simple algorithm
in the android.
Availability of Apps: Anyone can make use lot of free apps in the app store and from other
android stores. It gives freedom to install from third party users.
Great Social Networking Integration: Integration can be made to different social networking
sites, so we can enhance features. Free to customize the applications and features, using user
enabled development.
Better Notification System: It makes users to check important notifications directly from the
dashboard. It makes work easy. Earlier we used to go for every application refresh to check
updates.
10. Updated User Interface Design: Interfacing that means human to machine integration made to
update in android. Touchscreen made very useful change in the mobile use. It enables zooming
and tapping features which perform very effectively in the Android operating system.
11, At a Time Applications: Can run numerous applications which allow consumers to help save
time and efforts.
Low Chance of Crashing: The Android OS is very smooth and easy to operate and less chances of
crashing down.
Stability: Stability and security is better than other mobiles OS as it is based on Linux Kernel. The
Linux based operating system enabled with high security with unix. Every operation goes into
command mode. If detected any security threats it goes to basic mode by storing to another
application like cloud computing and crashes all the data on the device.
14, Multitasking: Android phones can run many applications, it means we can browse while
listened to the song.
Disadvantages of Android Operating System:
1. Need Internet Connection: Android requires an active internet connection. At least there should
be a GPRS internet connection in our area, so that the device is ready to go online according to
our needs.
Advertising: Application in the Android phones can indeed be obtained easily and for free, but
the consequences in each of these applications, will always be ads on display, either the top or
bottom of the application.
Wasteful Battery: Android more wasteful than any other operating system, because this
operating system is a lot of “process" in the background that lead to the battery quickly drains.
Many Applications contain Virus: The virus inserted android applications like Counter Strike
Ground Force. Android Application contain virus also present in the Android Market.
Slow Response: Compared to ‘iOS’ of Apple, Windows 8 of Microsoft, when we open same app in
the ios and windoes8. We observe the slow response of the android when we open apps in the
different platforms.
Heat: Compared to other operating systems android makes use of processes very efficient. This
makes processor to get heat. Some hardware companies take care to reduce heat, but it went in
vain when we operate it a long time and at low battery.
Mobile Application Development 1,24 Android and its Tools

| Practice Questions
What is Mobile application?
What is Mobile application development?
aR weN

What is Android?
PNA

Enlist features of Android OS?


State advantages and disadvantages of Android OS?
Describe architecture of Android diagrammatically.
What is OHA?
Explain the term Android ecosystem in detail.
What are the features of Android? Enlist any six of them.
BY

Describe various Android versions with their features.


Explain need of Android OS.
BREE

How to install and setup Android Studio?


What is Android studio? How to create an application on it?
>!

Explain the following terms;


=

(i) Android application


(ii) Android kernel.
15. What are the tools required for developing Android application?
16. Describe OHA with the help of diagram.
17. Enlist and explain any 4 features of Android.
18. Compare various Operating systems with Android 0.S.
19. Explain the concept of Android Ecosystem.
20. Explain any 4 advantages and disadvantages of Android 0.S.
21. Describe the concept of Anatomy of Android Application.
22. Draw and explain the architecture of Android.
23. Write down the steps how to download and install Android Studio.
24. List and state the use of Android versions.
25. Write down the steps is to create a simple Android Application using Android studio.
+, .o. .*,
+o > **
2...
Installation and
Configuration of Android
| Chapter Outcomes... |
[=] Describe function of the given component to operate the specified IDE.
f]_ Explain the given term related to virtual machine.
{| Explain the given basic term related to Android development tools.
[al Describe the features of given Android emulator.
[a] Describe the steps to configure the given android development environment.

| Learning Objectives...
{] To learn Android Installation
Ml To study Configuration of Android

INTRODUCTION
* Android Studio is Google's officially supported IDE for developing Android apps. Android is
an Operating System for mobile devices developed by Google, which is built upon Linux kernel.
© Inthis chapter, a new android learner/beginner will have a brief understanding of Android SDK and
Android ADT. We will also learn about the concepts like Android AVD, Dalvik Virtual Machine (DVM)
and to know how to do installation of eclipse and SDK.

OPERATING SYSTEM
© To develop an Android program, the necessary supporting operating systems used in a computer can
‘be as follows:
1. Windows XP (32-bit), Vista (32-bit or 64-bit) or Windows 7 (32-bit or 64-bit) Windows 8/10 (32-bit
or 64-bit).
2. Mac OS X (10.5.8 or later (Intel chips only)).
3. Linux (Ubuntu Linux version 8.04 or later and GNU C Library 2.7 or later).
Java JDK
¢ An Android operating system program is developed in the Java programming language we have to
install Java Development Kit (JDK) in computer which is free software where the JDK includes the
Java SE Runtime (JRE).
e Android Studio uses the Java tool chain to build, so we need to make sure that we have the Java
Development Kit (JDK) installed on the computer before we start using Android Studio.
ERE] android spk
e The Android Software Development Kit (SDK) allows developers to create applications for the
Android platform. The Android SDK is the most important software of android which is installed.
[2.1]
Mobile ication Development 22 tion and Ci tion of Android

* The Android SDK provides to test android applications, the API libraries, an emulator,
documentation, sample code, developer tools, and tutorials which help us to build, test and debug
apps from Android.

i if | | | 4
Sample
Debugger Libraries Emulator Documentation Tutorials
Code
Fig. 2.1: Android SDK Components
¢ The android SDK provides the tools and Application Programming Interfaces (APIs) for developers to
create applications on the Android platform using the Java programming language.
* Android SDK can be downloaded from https://developer.android.com/studio using Android SDK
Manager which is free.
e We find the Android SDK in a zip file and have to unzip its contents into a folder. We can also create
Android Virtual Devices (AVD) via the Android SDK, which run in the emulator.
e Android SDK is made up of two main parts namely, the tools and the packages. When we first install
the SDK, all we obtain are the basic tools. These are executables and supporting files that will help us
to develop applications.
e Some Android SDK, features include:
No licensing, distribution, or development fees.
pune

Wi-Fi hardware access.


IPC message passing.
Shared data stores.
An integrated open source WebKit-based browser.
ay

Full support for application that integrate Map controls as part of their interface.
7. Peer-to-Peer (P2P) support using Google Talk.
Platform Used:
© To develop Android application we use the Android Studio, Android Debug Bridge, AVD Manager,
Eclipse, IntelliJ and AIDE different Integrated Development Environment (IDEs) which supports
multiple languages such as Java, C, C++, COBOL, Python, etc. It is such type of environment upon
which the extensible plug-in can run.
(4) ANDROID DEVELOPMENT TOOLS
¢ In Android it is necessary to connect Eclipse with the Android SDK. Linking is represented by the
plugin named Android Development Tool (ADT), which extends the capabilities of Eclipse and allows
the rapid development of Android projects or apps.
e¢ ADT in Android is a plugin for the Eclipse IDE which provides a suitable environment to develop an
Android application where creation, compilation and debugging are possible.
e ADT in Android can able to set up new Android projects, create an application UI, inset packages
based on the Android Framework API, debug (or clear-up) our applications using the Android SDK
tools and export signed (or unsigned) .apk files in order to distribute in the application.
e Also Android ADT provides custom XML editors and debug output pane from which we get the
unbelievable enhance during develop the Android applications.
* Android Developer Tools Bundle (ADT Bundle) provides Eclipse + ADT plugin, Android SDK Tools,
Android Platform. Tools, Most recent Android platform, Newest Android system image for the
emulator and so on.
Mobile ication Development 23 tion and Ci tion of Android

Create a new
Android application

Create an ‘ADT Compile and


Application debug Android
Ul applicatons

Access the tools Create digital certificates


for accessing the for code-singing of APK
Android emulators (Android Application
and devices Packages)

Fig. 2.2: Android ADT (Functions)


1 Android Studio:
As the official Integrated Development Environment (IDE) for all Android applications, Android
Studio always seems to top the list of preferred tools for developers.

Android Studia

="
_ ; i
cl i all
Bee *

Fig. 2.3: Android Studio


Google created Android Studio back in 2013, It replaced or should we say it eclipsed? Eclipse Android
Development Tools (ADT) as the primary IDE for native Android app development.
Android Studio provides code editing, debugging, and testing tools all within an easy-to-use drag-
and-drop interface. It is free to download and is supported not only by Google, but also by a large and
actively engaged community of Android developers.
ADB (android Debug Bridge):
Android Studio includes the Android Debug Bridge, which is a command-line tool or “bridge” of
communication between Android devices and other computers that can be used during development
and the overall debugging and QA (Quality Assurance) process,
By connecting an Android device to the development PC and entering a series of terminal
commands, a developer is able to make modifications as needed to both devices.
. AVD Manager:
Another useful feature of Android Studio is the AVD Manager, the short form for Android Virtual
Device.
Mobile ication De t 24 tion and Ci tion of Android

The AVD Manager is an emulator used to run Android apps on a computer. This allows developers the
ability to work with all types of Android devices to test responsiveness and performance on different
versions, screen sizes, and resolutions.
Eclipse:
As we mentioned above, there was Eclipse before there was Android Studio. For a long time, Eclipse
was the officially preferred IDE for all Android application development.
Even though Google no longer offers support for Eclipse, many developers still use it to create
Android and other cross-platform apps, as it works very well with many different programming
languages.
Fabric:
Fabric is the development platform behind Twitter's mobile application.
It gives developers the ability to build better mobile apps by providing them with a suite of “kits” that
they can pick and choose from. These kits include everything from beta-testing to marketing and
advertising tools.
Google purchased Fabric from Twitter in January of 2017. Uber, Spotify, Square, Groupon, Yelp, and
more big-name companies have utilized Fabric in developing their mobile applications.
FlowUp:
FlowUp allows us to monitor the performance of all our production apps. Handy dashboards let us
keep track of our stats and metrics, including CPU and disk usage, memory usage, frames per
second, bandwidth and more.
FlowUp is a monthly subscription-based SaaS solution with pricing determined by the total number
of users in the company.
GameMaker :Stdio
For Android game developers, one of the most popular development tools is GameMaker: Studio.
GameMaker provides everything we need to create 2D games using very little code. It is an extremely
user-friendly application with a simple drag-and-drop interface.
GameMaker Studio is targeted to beginner and leamer gaming developers.
Genymotion:
Another Android emulator, Genymotion helps developers test and preview an application on over
3,000 device scenarios.
Genymotion is popular among gaming developers because it comes with pre-installed standard
Android images and graphics that are quite useful in the testing process. It also provides greater
speed than testing an app on an actual Android device.
Genymotion is a cross-platform development tool and supports many different programming
languages and environments.
Gradle;
Back in 2013, Google endorsed Gradle as a build system for Android apps. Based on Apache Maven
and Apache Ant, Gradle is one of the most popular development tools for creating large-scale
applications involving Java.
Developers like using Gradle in conjunction with Android Studio because it’s very easy to add
external libraries using a single line of code.
1 . IntelliJ IDEA:
From the developers at JetBrains, IntelliJ IDEA is designed for ultimate programmer productivity. It’s
extremely fast and features a full suite of development tools right out of the box.
At $149 per year, IntelliJ IDEA certainly isn’t cheap. However, there is a free, open source community
edition available and the full extended version is free to students for one year.
Mobile ication Development 25 tion and Ci tion of Android

[EE anprop virtua DEvIcE (Av)


« An Android Virtual Device (AVD) represents a device configuration. An AVD is a configuration that
defines the characteristics of an Android phone, tablet, Wear OS, Android TV, or Automotive OS
device that we want to simulate in the Android Emulator.
e An AVD is an emulator configuration that enables to model an actual device by calling hardware and
software options to be emulated by the Android Emulator.
e The AVD Manager is an interface we can launch from Android Studio that helps us to create and
manage AVDs.
e An AVD is used for testing the Android applications. To open the AVD Manager, do one of the
following:
Select Tools + AVD Manager.

Click AVD Manager in the toolbar.


Ahardware sketch

Consists of

Amapping to a system image AVD | Emulated storage (secure digital)

tests

Fig. 2.4: Android AVD


Things about AVDs:
e An AVD contains a hardware profile, system image, storage area, skin, and other properties. We
recommend that we create an AVD for each system image that our app could potentially support
based on the <uses-sdk> setting in our manifest.
1. Hardware Profile:
¢ The hardware profile defines the characteristics of a device as shipped from the factory. The AVD
Manager comes preloaded with certain hardware profiles, such as Pixel devices and we can define or
customize the hardware profiles as needed.
© Notice that only some hardware profiles are indicated to include Play Store. This indicates that these
profiles are fully CTS compliant and may use system images that include the Play Store app.
2. System Images:
*® Asystem image labeled with Google APIs includes access to Google Play services.
¢ Asystem image labeled with the Google Play logo in the Play Store column includes the Google Play
Store app and access to Google Play services, including a Google Play tab in the Extended controls
dialog that provides a convenient button for updating Google Play services on the device.
* To ensure app security and a consistent experience with physical devices, system images with the
Google Play Store included are signed with a release key, which means that we cannot get elevated
privileges (root) with these images.
© If we require elevated privileges (root) to aid with our app troubleshooting, we can use the Android
Open Source Project (AOSP) system images that do not include Google apps or services.
Mobile ication Development 26 tion and C tion of Android

Storage Area:
¥

The AVD has a dedicated storage area on our development machine. It stores the device user data,
such as installed apps and settings, as well as an emulated SD card.
If needed, we can use the AVD Manager to wipe user data, so the device has the same data as if it
were new.
Skin:
An emulator skin specifies the appearance of a device. The AVD Manager provides some predefined
skins. We can also define our own, or use skins provided by third parties.
5. AVD and app Features:
Be sure our AVD definition includes the device features our app depends on.
En EMULATORS
Android Emulator is responsible for running, debugging and testing the Android application.
The Android SDK comes with a virtual mobile device emulator that rums on the computer. The
emulators enables us trail product to develop android application without using a physical device.
The Android Emulator mimics all the hardware and software features of typical mobile devices,
except that it cannot place annual phone calls.
It provides a selection of navigation and control keys which we can “press” using our mouse or
keyboard to generate events for our applications. If provides a screen in which our application is
displayed together with any other active android applications.
The Android Emulator runs on a full Android system stack, down to the kernel level including a set
of preinstalled applications that we can access from our applications.
We can select the version of the android system we wish to run in the emulator by configuring AVDs,
and we can also modify the mobile device skin and key mappings.
While launching the emulator at the runtime, we can use a variety of commands and options to
control its behavior.
The Android emulator offers dynamic binary translation of device machine code to the OS and
processor architecture of our development machine.
In short Android Emulator tool helps to start the emulator from the command line.
DALVIK VIRTUAL MACHINE (DVM)
Dalvik is a register-based Virtual Machine (VM) that’s been optimized to ensure that a device can run
multiple instances efficiently.
The DVM uses the device's underlying Linux kernel to handle low-level functionality including
security, threading and process and memory management.
It is also possible to write C/C++ applications that run directly on the underlying Linux OS. While we
can do this, in most cases there’s no reason we should need to.
Google selected Java as the language for developing Android applications, thereby it got away with
both JME and the JVM in favour of an alternate development target, the Dalvik virtual machine.
Google have also chosen to use an alternative and limited implementation of the standard JAVA
libraries. Both of these are unusual Java and effectively represent fork of the Java platform.
The key figure in Google’s implementation of JVM is Dan Bornstein, who has written the Dalvik VM-
Dalvik is the name ofa town in Iceland.
Dalvik VM takes the generated Java class files and combines them into one or more Dalvik Executable
(.dex) files. It reuses duplicate information from numerous class files, effectively reducing the gap
requirement by half from a traditional .jar file.
Android OS uses the Dalvik Virtual Machine (DVM) with just-during-time compilation to run Dalvik
bytecode, which is frequentaly translated from Java bytecode.
Google has also fine-tuned the garbage collection in the Dalvik VM, but it has chosen to remove Just-
In-Time (JIT) compiler, in early releases. Android 2.3 has added JIT.
Mobile icatic 27 tion and Ce fion of Android

Dalvik VM use a different kind of assembly-code generation, in which it uses registers as the primary
units of data storage instead of the stack.
Google expects to accomplish 30% lesser instructions as a result. The Dalvik VM relies on the Linux
Kernel for underlying functionality such as threading and low-level memory management.
We must remember that the final executable code in android as a result of the Dalvik VM, is based.
not on Java byte code but on .dex files instead. This means we cannot directly execute Java byte code;
we have to start with Java class files and then converts them to linkable .dex files.
This performance is extended into the rest of the Android SDK. For example, the android SDK uses
XML extensively to define UI layouts.
However, all of this XML is complied to binary files before these binary files become resident on the
devices. Android provides special mechanisms to use this XML data.
Android programs are complied into .dex (Dalvik Executable) files, which are in turn zipped into a
single .apk file on the device .dex files can be created by automatically translating compiled
applications written in the Java Programming language.
The android uses a particular virtual machine i.e, the Dalvik Virtual Machine (DVM) to run Java based.
applications.
Dalvik is a vital part of Android which is normally use mobile devices such as mobile phones and
tablet computers, embedded devices for example smart TVs and media streamers etc.
Dalvik can use own byte format i.e. Dalvik byte code which is different from Java byte code which is
different from Java byte code.
So Java class files can not directly run on android, they need to get converted in the Dalvik byte code
format which is compiled by the Dex compiler.
yA Jar S .apk

Magonumeer —[_ede Magi Nimes


class { dex \

Vesion of Class Cr
file format SHA-1
Signature other Strings
mstant Pool Heterogeneous Constant Pool
Sone Constant Pool

Access Flags

class Interfaces

Constant Pool [es]

Method
Methods Method Constant Pool

Attributes: Attributes
Field List

——
F

Local Variables

Fig. 2.5: Android Dalvik Virtual Machine (DVM)


Mobile Development 28 tion and Ce tion of Android

DVM in Android operating system contains following:


1 File Header: Dex files start the simple header with some checksums and offsets to other
structures.
. Notes: All non-string fields are stored in little-endian format. It would appear that the checksum
and signature fields are assumed to be zero when calculating the checksum and signature.
String Table: This table stores the length and offsets for every string in the dex file including
string constants, class names, variable names and more.
. Class List: A list of all classes referenced or contained in this dex file.
Field Table: A table of fields of all classes defined in this dex file.
Method Table: A table of methods of all classes in this dex file.
Class Definition Table: A table of class definition for all classes either defined in this dex file or
has a method or field accessed by code in this dex file.
Filed List: Stores data for pre-initialized fields in a class. The list is formed of a 32-bit integer
containing the number of entries followed by the entries themselves.
. Method List: A list of methods for a particular class. Begins with a 32 bit integer that contains the
number of items in the list.
10. Code Header: This header contains the information about the code that implements the
methods.
11. Local Variable List: A list of variables for a particular method. Begins with a 32 bit integer that
contains the number of items in the list.
Difference between Java Virtual Machine (JVM) and Dalvik Virtual
Machine (DVM)
Fig. 2.6 shows concept of JVM and DVM.
Java Compiler

Java Compiler

Java Byte Code Java Byte Code


an

Kowee

Java Byte Code


by JVM

Dalvik Byte Code

Dalvik Executable
by DVM

{a) JVM (b) DVM


Fig. 2.6
Mobile 29 and Ci of Android
* Following table differentiate between JVM and DVM:
Sr. No. JvM DVM
1. JVM supports multiple operating systems. | DVM supports only Android Operating System.
2. JVM forms separate classes in separate | DVM forms multiple class in .dex byte code file.
.class byte code files.
3. It is based on stack based virtual machine | It is based on register based virtual machine
architecture. architecture.
4. JVM runs on more memory. DVM runs on less memory.
5. The executable format of JVM is JAR. The executable format of DVM is APK.
6. JVM has different constant pools. DVM has common constant pool.
7. It runs .class byte code directly. The .class byte codes are optimized to .odex
format before executing in DVM.

[E2GH steps To INSTALL AND CONFIGURE ANDROID STUDIO AND SDK


e Before any work can begin on the development of an Android application, the first step is to
configure a computer system to act as the development platform.
« This involves a number of steps consisting of installing the Android Studio Integrated Development
Environment (IDE) which also includes the Android Software Development Kit (SDK) and OpenJDK
Java development environment.
EXCH system Requirements
* Android application development may be performed on any of the following system types:
Windows 7/8/10 (32-bit or 64-bit).
wn pe

MAC OS 10.10 or later (Intel based systems only).


Linux systems with version 2.19 or later of GNU C Library (glibc).
Minimum of 3GB of RAM (8GB is preferred).
Awa

Approximately 4GB of available disk space.


1280 x 800 minimum screen resolution.
Ez Downloading the Android Studio Package
Most of the work involved in developing applications for Android will be performed using the
Android Studio environment. The content and examples in this book were created based on Android
Studio version 3.2 which at the time writing is the current version.
«The latest release of Android Studio may be downloaded from the primary download page which can
be found at the following URL:
http: //developer.android.com/studio/index.html

y | Installing Android Studio


* Once, downloaded, the exact steps to install Android Studio differ depending on the operating

pre
stem on which the installation is being performed.
Installation on Windows
« Locate the downloaded Android Studio installation executable file, (named android-studio-ide-
<version>-windows.exe) in a Windows Explorer window and double-click on it to start the
installation process, clicking the Yes button in the User Account Control dialog if it appears.
© Once, the Android Studio setup wizard appears, work through the various screens to configure the
installation to meet our requirements in terms of the file system location into which Android Studio
should be installed and whether or not it should be made available to other users of the system.
Mobile ication Development 2.10 tion and C tion of Android

* When prompted to select the components to install, make sure that the Android Studio, Android SDK
and Android Virtual Device options are all selected.
* Although there are no strict rules on where Android Studio should be installed on the system, the
installation was performed into C:\Program Files\Android\Android Studio and that the Android
SDK packages have been installed into the user’s AppData\Local\Android\sdksub-folder. Once, the
options have been configured, click on the Install button to begin the installation process.
* On versions of Windows with a Start menu, the newly installed Android Studio can be launched
from the entry added to that menu during the installation.
* The executable may be pinned to the task bar for easy access by navigating to the Android Studio\bin
directory, right-clicking on the executable and selecting the Pin to Taskbar menu option.
* Note that the executable is provided in 32-bit (studio) and 64-bit (studio64) executable versions. If we
are running a 32-bit system be sure to use the studio executable.
& #4 Installation on MAC OS
e Android Studio for MAC OS is downloaded in the form of a disk image (.dmg) file. Once, the android-
studio-ide-<version>-mac.dmefile has been downloaded, locate it in a finder window and double-
click on it to open it as shown in Fig. 2.7.
@.¢6 ‘Andiroid Studio 20

Fig. 2.7: Installation Wizard on MAC OS


¢ To install the package, simply drag the Android Studio icon and drop it onto the Applications folder.
The Android Studio package will then be installed into the Applications folder of the system, a
process which will typically take a few minutes to complete.
¢ To launch Android Studio, locate the executable in the Applications folder using a Finder window
and double-click on it.
* For future easier access to the tool, drag the Android Studio icon from the Finder window and drop it
onto the dock.
E} installation on Linux
e Having downloaded the Linux Android Studio package, open a terminal window, change directory to
the location where Android Studio is to be installed and execute the following command:
unzip /<path to package>/android-studio-ide-<version>-linux.zip
e Note that the Android Studio bundle will be installed into a sub-directory named android-studio.
Therefore, assuming that the above command was executed in /home/demo, the software packages
will be unpacked into /home/demo/android-studio.
e To launch Android Studio, open a terminal window, change directory to the android-studio/bin sub-
directory and execute the following command:
./studio.sh
Mobile ication Development 241 tion and Ci tion of Android

When running on a 64-bit Linux system, it will be necessary to install some 32-bit support libraries
before Android Studio will run. On Ubuntu these libraries can be installed using the following
command:
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 1ib32z1 libbz2-1.0:1386
On RedHat and Fedora based 64-bit systems, use the following command:
sudo yum install zlib.i686 ncurses-libs.i686 bzip2-libs. i686

ya | Android Studio Setup Wizard


The first time that Android Studio is launched after being installed, a dialog will appear providing
the option to import settings from a previous Android Studio version.
If we have settings from a previous version and would like to import them into the latest installation,
select the appropriate option and location. Alternatively, indicate that we do not need to import any
previous settings and click on the OK button to proceed.
Next, the setup wizard may appear as shown in Fig. 2.8 though this dialog does not appear on all
platforms.
ve Pte
=, (oman

(Welcome!
This wizard wll set up your development environment for Andraid Studio.
Additionally,
tht wizard wil help port existing Android apps into Android Studio
0 create nase Andiold application project.

TH) § voll
Cnet res

Fig. 2.8: Android studio setup Wizard


If the wizard appears, click on the Next button, choose the Standard installation option and click on
Next once again.
Android Studio will proceed to download and configure the latest Android SDK and some additional
components and packages. Once this process has completed, click on the Finish button in the
Downloading Components dialog at which point the Welcome to Android Studio screen should then
appear, (See Fig. 2.9}.
e Welcome to, Android Studio,

-
Android Studio

© Start onew Android Studio project:


1 Open an etng Android Stud proact
‘Check out project from Version Control +
Prof or debug
APK
&f teport project (Gradie, Ecipse ADT, etc.)

oF import an Android
code sample

© Configure Get Help =


Fig. 2.9
Mobile ication Development 2.42 tion and Ci tion of Android

Installing additional Android SDK Packages


The steps performed so far have installed Java, the Android Studio IDE and the current set of default
Android SDK packages. Before proceeding, it is worth taking some time to verify which packages are
installed and to install any missing or updated packages.
This task can be performed using the Android SDK Settings screen, which may be launched from
within the Android Studio tool by selecting the Configure > SDK Manager option from within the
Android Studio welcome dialog.
Once, invoked, the Android SDK screen of the default settings dialog will appear as shown in
Fig. 2.10.
oe DetoahPreerences
a ‘Appearance
@ Sehavier » System Settings » Android SOK
© Appearance &.netavier Manager forte Android SX and Tool Used by Androl! Stutlo
Appeerence ‘Aviseold SOK Location: [Users/nobamyth/Lbeary/
Anco ee on
Mana and Tooters GR 50% Toon 0x Upcate Stes
© System Settings
Past pertAndroid SDK Platform package inchides the Android plstform end sources pertaining to on
level
by detaun. Once installed, narod Buode eu utomcahy war for upeoen Check
HTTP Proxy, ae package deteis” to display individusl SDK components.
‘weet | avon
G Ancroic 6.9 i) 2
Aner 7. 1 (Nougat! 3
Anais 7.0 (Nougat) 2 2
Ancroid 6.0 (war imtiow) 23 3
Android 5.1 (Lollipop) 2 2
Anda B. (Loop) ” 2
Arcos40 (KitKat Wear 20 2
Ane 4.8 (tat) 0 rf
Android4.3 (Jelly Bean) 3 3
Ancroid 2 (ty Bean} 0 a
Android 4.1 (Jelly Bean) 5
Android 4.0.3 fexCroarSandwch) 15 5
Anatol 4.0 leeCreamSandwien) 44 4 Not istates
‘Sow Package Detala

2 oes
Fig. 2.10
The Android SDK has been installed. To install older versions of the Android SDK simply select the
checkboxes corresponding to the versions and click on the Apply button.
It is also possible that updates will be listed as being available for the latest SDK. To access detailed
information about the packages that are available for update, enable the Show Package Details
option located in the lower right-hand corner of the screen. This will display information similar to
that shown in Fig, 2.11.
Name ‘API Level Revision Status
Android TV intel x86 Atom System Image 25 6 Not Installed
Android Wear for China ARM EABI v7a System Image 25 3 Not installed
Android Wear for China intel x86 Atom System image 25 3 Not installed
‘Android Wear ARM EABI v7a System Image 25 3 Not installed
Android Wear intel x86 Atom System Image 25 3 Not installed
Google APis ARM 64 vBa System Image 25 8 Not installed
Google APis ARM EAB! v7a System Image 25 8 Not installed
Google APIs intel x86 Atom System Image 25 8 Not installed
'S _ Google APis intel x86 Atom_64 System Image 25 6
’ Android 7.0 (Nougat)
Google APIs 24 4 Not installed
Fig. 2.11
The Fig. 2.11 highlights the availability of an update. To install the updates, enable the checkbox to
the left of the item name and click on the Apply button.
In addition to the Android SDK packages, a number of tools are also installed for building Android
applications. To view the currently installed packages and check for updates, remain within the SDK
settings screen and select the SDK Tools tab as shown in Fig. 2.12.
Mobile ication Development 2.13 tion and Ci tion of Android
os Tern breerences
a Appanranen A Babavier | Spatmm Satings | Andrabd SDH
~ Repeernees MBaherier ——-Manajar for he Android SX an Tcl und by Ancroe aslo
— ‘Ancrld
SK tociton: Rneryelaryth/LErary Aner ist
+ Mare
tenon ond Tookers
eon arate setae SX Goiope
{50K Patorme
1008.
_=>- 0K Up ee
posers ees es ow nee aoe ear wo
HTTP Prony
voome
iage ace (hu Oxo tools
za ue
Notiications narod ats AP Smuaons '
Gulch nts Andis Auto Ovehtop Hebd Unt emator 1 Not nated
Pach Veron 1B dred tmutse 2013 pate Ava: 20.1.4
Ani SOx Pat orm-Toole 2600
foreae 1B Aner $54 Toole 2802 Update Ava 38.1.0
» eater enantio for Androl SOx 1 Net meta
Pg Googe Par AP Exoantion Horry 1 No nated
. all, Ensen, Desliymant Geog Pay tug Uoreryneery
nw useing ‘1 ratte
ot tated
Teele Mh finnom ms nie a neste
‘tom Pactage Dab

2 omen ss
Fig. 2.12
¢ Within the Android SDK Tools screen, make sure that the following packages are listed as Installed in
the Status column:
Android SDK Build Tools.
ene

Android Emulator.
Android SDK Platform Tools.
Android SDK Tools.
past ane

Google Play Services.


Instant Apps Development SDK.
Intel x86 Emulator Accelerator (HAXM Installer).
ConstraintLayout for Android.
Solver for ConstraintLayout.
10. Android Support Repository.
11, Google Repository.
12. Google USB Driver (Windows only).
* Inthe event that any of the above packages are listed as Not Installed or requiring an update, simply
select the checkboxes next to those packages and click on the Apply button to initiate the installation
process.
* Once, the installation is complete, review the package list and make sure that the selected packages
are now listed as Installed in the Status column. If any of them are listed as Not installed, make sure
they are selected and click on the Apply button again.
Making the Android SDK Tools Command Line Accessible
© Most of the time, the underlying tools of the Android SDK will be accessed from within the Android
Studio environment. However, there will also be instances where it will be useful to be able to invoke
those tools from a command prompt or terminal window.
e Inorder for the operating system on which we are developing to be able to find these tools, it will be
necessary to add them to the system's PATH environment variable.
e Regardless of operating system, the PATH variable needs to be configured to include the following
paths (where, <path_to_android_sdk_installation>represents the file system location into which the
Android SDK was installed):
<path_to_android_sdk_installation>/sdk/tools
<path_to_android_sdk_installation>/sdk/tools/bin
<path_to_android_sdk_installation>/sdk/platform-tools
Mobile ication De t 2.44 tion and C: tion of Android

¢ The location of the SDK on our system can be identified by launching the SDK Manager and referring
to the Android SDK Location: field located at the top of the settings panel as highlighted in Fig. 2.13
Appearance & Behavior >» System Settings > Android SDK

Manager for the Android SDK and Tools used by Andi ‘St

Android SDK Location:

SDK Platforms [SRRREEEBINI) SDK Update Sites


Below are the available SDK developer tools. Once installed, Android Studio will automatically
check for updates. Check "show package details" to display available versions of an SDK Tool.

Fig. 2.13
e¢ Once, the location of the SDK has been identified, the steps to add this to the PATH variable are
operating system dependent.
Windows 7
* Right-click on Computer in the desktop start menu and select Properties from the resulting menu.
e Inthe properties panel, select the Advanced System Settings link and, in the resulting dialog, click
on the Environment Variables.
« In the Environment Variables dialog, locate the Path variable in the System variables list, select it
and click on Edit. Locate the end of the current variable value string and append the path to the
Android platform tools to the end, using a semicolon to separate the path from the preceding values.
* For example, assuming the Android SDK was installed into, C:\Users\demo\AppData\Local\ Android\sdk,
the following would be appended to the end of the current Path value:
C:\Users\demo\AppData\Local\Android\sdk\platform-tools
C:\Users\demo\AppData\Local\Android\sdk\tools
€:\Users\demo\AppData\Local\Android\sdk\tools\bin
e Click on OK in each dialog box and close the system properties control panel. Once, the above steps
are complete, verify that the path is correctly set by opening a Command Prompt window
(Start > All Programs — Accessories + Command Prompt) and at the prompt enter:
echo %Path%
e The returned path variable value should include the paths to the Android SDK platform tools folders.
Verify that the platform-tools value is correct by attempting to run the adb tool:
adb
© The tool should output a list of command line options when executed. Similarly, check the tools path
setting by attempting to launch the AVD Manager command line tool (don’t worry if the avdmanager
tool reports a problem with Java - this will be addressed later):
avdmanager
e In the event that a message similar to the following message appears for one or both of the
commands, it is most likely that an incorrect path was appended to the Path environment
variable: 'adb' is not recognized as an internal or external command, operable program or batch file.
Windows 8
* Onthe start screen, move the mouse to the bottom right-hand corner of the screen and select Search
from the resulting menu. In the search box, enter Control Panel. When the Control Panel icon
appears in the results area, click on it to launch the tool on the desktop.
* Within the Control Panel, use the Category menu to change the display to Large Icons. From the list
of icons select the one labeled System.
e Follow the steps outlined as Windows 7.
Mobile ication Development 2.45 tion and Ci tion of Android

Boo Windows 10
e Right-click on the Start menu, select Settings from the resulting menu and enter “Edit the system
environment variables” into the Find a setting text field.
e Inthe System Properties dialog, click the Environment Variables... button. Follow the steps outlined

Linux
as Windows 7.

* On Linux, this configuration can typically be achieved by adding a command to the .bashrc file in
our home directory (specifics may differ depending on the particular Linux distribution in use).
e Assuming that the Android SDK bundle package was installed into /home/demo/Android/sdk, the
export line in the .bashrcfile would read as follows:
export PATH=/home/demo/Android/sdk/platform-tools: /home/demo/Android/sdk/tools:/home
/demo/Android/sdk/tools/bin: /home/demo/android-studio/bin: $PATH
* Note also that the above command adds the android-studio/bin directory to the PATH variable. This
will enable the studio.sh script to be executed regardless of the current directory within a terminal
window.
MAC OS
« A number of techniques may be employed to modify the $PATH environment variable on MAC OS.
Arguably the cleanest method is to add a new file in the /etc/paths.ddirectory containing the paths
to be added to $PATH.
e Assuming an Android SDK installation location of /Users/demo/Library/ Android/sdk, the path may
be configured by creating a new file named android-sdk in the /etc/paths.d directory containing the
following lines:
/Users/demo/Library/Android/sdk/tools
/Users/demo/Library/Android/sdk/tools/bin
/Users/demo/Library/Android/sdk/platform-tools
* Note that since this is a system directory which will be necessary to use the sudo command when
creating the file. For example:
sudo vi /etc/paths.d/android-sdk
Updating Android Studio and the SDK
e From time to time new versions of Android Studio and the Android SDK are released. New versions
of the SDK are installed using the Android SDK Manager. Android Studio will typically notify us
when an update is ready to be installed.
¢ To manually check for Android Studio updates, click on the Configure — Check for Update menu
option within the Android Studio welcome screen, or use the Help > Check for Update menu option
accessible from within the Android Studio main window.
Practice Questions
1. What is OS? Explain OS requirements for Android.
What is JDK?
pon

What is SDK?
How to install Android Studio?
Describe DVM with diagram.
Noy

What is JVM? Compare JVM and DVM.


Explain the term emulator in detail.
Mobile Application De’ t 2,16 and Configuration of Android

8. What is AVD?
9. What is ADT? Describe in detail.
10. Differentiate between JDK and SDK.
11. Explain how to configure Android studio and SDK.
12. Define the terms: JDK, SDK, AVD, ADT.
13. Describe the concept of Android SDK.
14, Explain the term ADT with different tools.
15. Explain AVD in detail.
16, Define the role of Emulator in Android application development.
17, Explain the importance of DVM with the help of diagram.
18. Differentiate between JVM and DVM.
19, Enlist the system requirements for Android Studio installation.
20. Explain how to configure Android studio and SDK.
atete ateote ote
ate
63).
UI Components
and Layouts ,
Chapter Outcomes...
@] Explain with relevant analogy the given directory structure.
{fl Describe the steps to use the given Android rich UI component.
{§] Describe the steps to use the given type of layout.
{@] Develop the given basic Android application.

| Learning Objectives...
@] To learn Control Flow and Directory Structure in Android
{s] To study Components ofa Android Screen
@] Tounderstand Fundamentals of UI Design
{1 To learn various Layouts in Android (Linear, Absolute, Frame, Table, Relative etc.)

Ex!) INTRODUCTION
e Designing an User Interface (UI), will be one of our most important tasks during Android
development. Android app's User Interface (UI) is everything that the user can see and interact with.
« Android provides a variety of pre-built UI components such as structured layout objects and UI
controls that allows building the Graphical User Interface (GUI) for the app.
e Android also provides other UI modules for special interfaces such as dialogs, notifications and
menus.
¢ Understanding layouts is important for good Android application design. A layout defines the
structure for a user interface in the app, such as in an activity. All elements in the layout are built
using a hierarchy of View and ViewGroup objects.
e A View is considered as a basic building block for a Android User Interface (UI). A View usually draws.
something the user can see and interact with. Whereas, a ViewGroup is an invisible container that
defines the layout structure for View and other ViewGroup objects.
« The View objects are usually called “widgets” and can be one of many subclasses, such
as Button or TextView. The ViewGroup objects are usually called "layouts" can be one of many types.
that provide a different layout structure, such as LinearLayout.
e Input controls are the interactive components in the app's user interface. Android provides a wide
variety of controls we can use in the UI, such as buttons, text fields, seek bars, check box, zoom
buttons, toggle buttons and many more.
© The Android directory is the place to put all our files, in whatever folder hierarchy we want.

[3.1]
Mobile ication De 3.2 Ul Com and Layouts

CONTROL FLOW
* The steps in control flow of an Android application is given below:
Step 1: Click on Android Studio icon.

Fig. 3.2
Step 3: Give the Project Name and click ‘Next’.
ee LT) =F
Mobile ication Development 33 ULC and Layouts

Step 4; Select your SDK to and click next Target Android Devices.
Sana AA ARSON Be ROTTTIBO 7
een nee en = Moe read
i
‘Select the form fmcters sd exis 50% i

} ae
Tie ,
ee ener a
seca

Fig. 3.4
Step 5: To add the project on mobile select the proper activity here we select the empty activity and
click Next.

Fig. 3.5
Step 6: Give the activity name and click Finish.
ry =
Mobile ication De 34 Ul Com and Layouts

Android Studio Screen/Window Elements (Components):


e Fig. 3.7 shows Android Studio is an Integrated Development Environment (IDE).
jor
[Ete et pew tmeuee Goce mewn Sete Bult Muri Jets CS mete Ee J
02
[awa +0 KOS ane nism ook re tEne? ar]
}
05 04
eo
tre amd cmv lhe Rms omens ante
Bencomaly

#05
BD eterno
a amin

04
[aree +4 none sees wouncrwe |
& ne val

Fig. 3.7: Android Studio IDE


¢ For understanding the different components of UI just split the Android Window into parts and give
some numbering, (See Fig. 3.7).
1. Menu Bar: Menu Bar contains the drop-down menus to perform different functions.
2. Toolbar: Toolbar contains graphical view of some commonly usable buttons.
3. Navigation Bar: Navigation Bar shows the selected file hierarchy which helps developer to
directly navigate to the parent directories of the file or switch between different files.
4, Tool Buttons Bar: Tools Buttonsbar allows to switch between different tools in different
windows (Project Tool, Preview, Console Windows).
5. Project Tool Window: There are three project tool windows in the interface which allows
developer to use in different ways. Project Tool Window in the left side allows developer to
navigate through all the tools provided in the left side Tool Buttons such as Project hierarchy
view, Favourites, Structure view etc. Right side Project Tool Window allows to navigate between
the right Tool Buttons like Application Interface Preview on different devices, Gradle functions
etc. Bottom Project Tool Window allows to navigate between the bottom Tool Buttons like
Terminal, Run, Android etc.
6, Editor Window: Editor window open the selected file to allows developer to edit them as per the
requirements.
7. Status Bar: The status bar displays informational messages about the project and the activities
of Android Studio. It also contain a button in the left corner which lists all the tools menu button.
Hovering over items or button in the status bar will provide a description of that field.

[Ea pmecrory stRucTURE


e The Project tool window has several views, including the Android view, the Project view and
the Packages view. Each view shows the same stuff, but each view organizes this stuff a bit
differently.
Mobile Application Development UI Components and Layouts
The button just at above the left pane (shown by the arrow, see Fig. 3.8) is used to open the selection
box for choosing the preferred method of viewing the file hierarchy.
File Edit View Navigate Code Analyze Refactor Build oi Android *
Dale’ 4 xO AR +914 Project
[3 MyFirstApp ) Ca app ) [5 src) [5 androidTest ) [5 java) Packages
Scratches

Project Files
Problems
Production
Tests
Local Unit Tests
Android Instrumented Tests

Fig. 3.8 Fig. 3.9


Android and Project are the most useful views, though the Android view may hide certain folders
from us. By default, Android Studio will set the view to Android. The Project tool window provides a
simple tree interface with files and nested folders that we can toggle.
When we create an application in Android Studio, we find that the project is divided into an App
folder and Gradle scripts, (See Fig. 3.10).
The App folder (See Fig. 3.11) contains three subfolders (manifests, java and res) that make up our
application. They are divided so that it should be fairly easy to determine which resources go in
which folder.
If we expand all of the folders in the project explorer we will see a vast array of files and folders. Most
of them are managed by Android Studio. We will focus on the key folders and file types that we will
be using as Android developers.
of Android 5
aor
YBa maniests
Tk AndrontMandest
xm!
7 majva
¥ Bt combrainbellemyfintapp
© & MainaActivity
> En com.brainbelLmyfintapp (ondroidTest)
EY Caapp > Bt com.brsinbelLemyfirstapp (test)
a) > © manifests ¥ Bares
+ En drawable
> Cijave &ic tauncher_backgroundam!
>» Cares & ic launcher foreground.xmt (24)
¥ Bi layout
& ectivity.mainam!
7 Ea mipmap
> Bm ic Jauncher.png (3)
iclauncher.mi (anypi-v26)
» Bic launcher.round.png (5)
Fig. 3.10 ic launcher,roundaim (anydpi-v24)
Bl values
& colorsml
i sringsam!
i stylesaml
|¥ (© Gradle Scripts
© build.gradle (Project: MyFirstApp)
© build.gradle (Module: app)
Hh gradle-wrapper.properties (Gradle Version)
@ proguard-rules.pro (ProGuard Rules for spp)
i gradie properties (Project Properties)
© settings.gradle (Project Settings)
fi local-properties (SDK Location)

Fig. 3.11: Android Application Directory Strucutre


Mobile icatic 3.6 Ul Comp and Layouts

1. Manifests Folder:
© This is where we would put our manifest files. Most Android apps have single manifest file. But an
app may have several manifest files due to application versioning or for supporting specific
hardware.
* An AndroidManifest.xml file is generated inside manifest folder by Android Studio when we create a
project. This file contains the configuration parameters of the project such as permissions, services
and additional libraries.
* Amianifest file also provides information to the OS and Google Play store about app.
2. Java Folder:
« Let us take a look at what is in the java folder. This is the folder in our project where we will be
storing all of the source code files written in Java programming language.
¢ AMainActivity.java is automatically created in this folder by Android Studio, All of classes will be
available here, and Android Studio will even bundle together the package path so that we can work
with the files without having to drill down through the folders that make up our package.
3. Res Folder:
« It contains folders that help us to separate and sort the resources of our application. Resources
basically mean all the needed files except the source code.
¢ For example, while developing an app, we need to include resource files such as the app-logo, photos,
sounds, videos or animations. Each file type should be added to its own folder to observe with the
Android development standards.
* When we use Android Studio to create a new application, some folders will be automatically
generated for us. However, these folders are not the only ones we can use in project.
« The following are the folders that can be used inside of the res folder:
(i) Drawable Folder:
° The drawable folder contains graphics that can be drawn to the screen. For example, images files
(png, jpg and gif), various XML (clip drawable, insert drawable, layer list, level list, scale drawable,
shape draggable, state list, transition drawable), and predetermined frame animations can be placed
here:
(a) Bitmap File: Android supports bitmap files in three formats: .png (preferred), .jpg (acceptable),
.gif (discouraged).
(b) Nine-Patch File: A PNG nine-patch file with stretchable regions to allow image resizing based on
content.
(c) Layer List: An XML file that contains an array made up of other drawables.
(d) State List: An XML file that is used for images that have multiple or different states of
appearance.
(e) Level List: An XML file that is used to display other drawables that can be accessed based on the
level requested through setImageLevel().
(f) Transition Drawable: An XML file that contains a drawable that can be transitioned between two
items.
(g) Inset Drawable: An XML file that is used to place one drawable inside the bounds of another
drawable.
(h) Clip Drawable: An XML file consisting of points that is used in conjunction with another
drawable to create a clipped objected.
(i) Scale Drawable: An XML file that contains a drawable that changes the dimension value of
another drawable based on its current value.
(j) Shape Drawable: An XML file that contains the values of geometric shape, color, size, and similar
attributes.
Mobile lication Ds 37 UI Comp and Layouts

(ii) Layout Folder:


* The layout folder contains XML files used for the layouts. These file are used to set up the layout for
the Activity and is used for basic alignment of the layouts, components, widgets, and similar
resources that are used for the UI of application.
« The activity_main.xml is automatically created in this folder by Android Studio. Layout folder may
have multiple layout folders to handle different devices. This can be helpful when working with
layouts that need to be adjusted for devices with more or less screen space available.
(iii) Mipmap Folder:
e The mipmap folder contains the launcher icon files for the app.
« A launcher icon is a graphic that represents app to users. The mipmap folder was introduced in
Android 4.3.
(iv) Values Folder:
e The values folder contains XML files that contain simple values, such as strings, integers, and colors.
The values folder is used to keep track of the values we will be using in our application.
¢ To create applications with an easier maintenance cycle, it is highly recommended to no longer
hard-code values into our code. Instead, place values in XML files inside of the values folder.
« When we create a new project with Android Studio, the following XML files will be generated
automatically namely, colors.xml, strings.xml and styles.xml.
(v) Other Folders:
¢ Not all folders may be shown for our resources but we can create other folders for other resources in
our application.
e Following list describes each folder name as well as what should be stored in that folder:
(a) animator: XML files that define property animations.
(b) anim: XML files that define tween animations.
(c) color: XML files that define a state list of colors.
(d) menu: XML files that define application menus.
(e) raw: Any files to save in their raw form. For example, sound and video files are placed in the raw
folder.
(f) xml: Any XML files that can be read at runtime.
(g) font: Font files with extensions such as ttf, otf, ttc, XML files.
Gradle Scripts:
« APK files are built using the gradle build system, |¥ © Gradle Scripts
which is integrated in the Android Studio. & build.gradle (Project: MyFirstApp)
¢ When we start an app, the gradle build scripts are © build.gradle (Module: app)
automatically created. If we have special [ai gradie-wrapper properties (Gradle Version)
requirements for our project, we can specify these B) proguard-rutes.pro (ProGuard Rules for app)
requirements here. [ai gradle.properties (Project Properties)
. * . & settings.gradle (Project Settings)
e The gradle scripts folder contains the scripts used to [i local. properties (SDK Location)
build the app are configuration files, properties files,
and setting files.
Fig. 3.12
COMPONENTS OF A SCREEN
e An activity provides the window in which the app draws its UI. This window typically fills the screen,
but may be smaller than the screen and float on top of other windows.
« Generally, one activity implements one screen in an app. For instance, one of an app’s activities may
implement a Preferences screen, while another activity implements a Select Photo screen.
Mobile Development 3.8 Ul Cr and Layouts

* Activities serve as the entry point for


a user's interaction with an app and Status Bor
are also central to how a user
navigates within an app, (as with the onay neds ~ Action Gar
Back button) or between apps, (as
with the Recent button). View
* An activity represents a single (Tater)
screen with a User Interface (UI), in- HaisActiy ClableLavont
short an Activity performs actions View
on the screen. For example, an (EaitText)
4 = a4 + ViewGroup
e-mail application might have one (Relative Layout)
activity that shows a list of new e-
mails, another activity to compose
an email, and another activity for bien
reading e-mails. ‘Android
* An Activity displays the user Soft Keys
interface of our application, which
may contain widgets like buttons,
image buttons, text boxes, labels etc. Fig. 3.13: Components of Android Mobile Screen

¢ Typically we define our UI using XML file (for example the activity_main.xml file located in the res
then inside a folder called layout), which may look like this:
<?xml version="1,.0" encoding="utf-8"?>
<android. support.constraint.ConstraintLayoutxmlns:android="http: //schemas.android.com
/apk/res/android”
xmlns:app="http: //schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools”
android: layout_width="match_parent”
android: layout_height="match_parent”
tools: context=".MainActivity">
<TextView
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android:text="Hello World!”
app: layout_constraintBottom_toBottomO0f="parent"
app: layout_constraintLeft_toLeftOf="parent"
app: layout_constraintRight_toRightOf="parent”
app: layout_constraintTop_toTopOf="parent" />
</android, support. constraint .ConstraintLayout>

e During the runtime, we can load the XML UI in the onCreate() event handler in our Activity class,
using the setCotentview() method of the Activity class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
¢ During compilation time, each element in the XML file is compiled into its equivalent Android GUI
class, with an attribute represents by methods. The android system then creates the User Interface
(UI) of the Activity when it is loaded.
Mobile ication De 3.9 Ul Com and Layouts

[E23 FuNDAMENTALs OF UI DESIGN


Every item in a user interfaces is a subclass of the Android View class which is present inside the
package (android.view). The android SDK provides a set of pre-built views that can be used to
construct the user interface.
Typical examples include items such as Button, ImageButton, checkbox, ProgressBar and Tectview
classes.
Views:
The basic building block for user interface in Android is a View, which is created from the View class
and occupies a rectangular area on the screen and is responsible for drawing and event handling.
Views are the base class for all visual interface elements (commonly known as controls or widgets).
All User Interface (UI) controls, including the layout classes, are derived from View.
A View is an object/widget that draws something on the screen by the help of user interact.
Examples of widgets are buttons, text boxes, labels etc.
. ViewGroup:
The ViewGroup is a subclass of View and provides invisible container that hold other Views or other
ViewGroups and define their layout properties.
View groups are extensions of the View class that can contain multiple child Views. In order to
Extend the ViewGroup class to create compound controls made up of interconnected child views.
A ViewGroup provides the layout in which we can order the appearance and sequence of views.
Examples of ViewGroup are FrameLayout, LinearLayout etc.
Fragments:
Fragments represents a portion of user interface in an Activity. Fragments, introduced in Android
3.0 which uses API level 11 are used to encapsulate portions of our UI.
This encapsulation makes fragments particularly useful when optimizing our UI layouts for
different screen sizes and creating reusable User Interface (UI) elements.
Each Fragment includes its own User Interface (UI) layout and receives the related input events but
is tightly bound to the activity into which each must be embedded. Fragments are similar to UI view
controller in iPhone development.
4. Activities:
Activities dictate the UI and handle the user interaction to the smart phone screen. Activities
represent a single screen that user interact.
Activities are the Android equivalent of Forms in traditional windows desktop development. To
display a UI we assign a View (usually a layout or fragment) to an Activity.

ee UI LAYOUTS
A layout defines the structure for a User Interface in the application. There are number of Layouts
provided by Android which we will use in almost all the Android applications to provide different
view, look and feel.
Each layout in Android has a set of attributes which define the visual properties of that layout. There
are few common attributes among all the layouts and their are other attributes which are specific to
that layout.
Layouts in Android are very important for GUI based apps. The Android SDK includes the following
layout views that may be used within an Android user interface design.
1. LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally.
2. RelativeLayout is a view group that displays child views in relative positions.
3. TableLayout is a view that groups views into rows and columns.
4. AbsoluteLayout enables us to specify the exact location of its children.
Mobile lication De 3.10 UI Com, and Layouts

5, FrameLayout is a placeholder on screen that we can use to display a single view.


6. ListView is a view group that displays a list of scrollable items.
7. GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.
LinearLayout
¢ Android LinearLayout is a view group that aligns all children in either vertically or horizontally.
Linear layout in Android allow us to arrange components horizontally in a single column or
vertically in a single row.
* Vertically or horizontally direction depends on attribute android:orientation. LinearLayout is simple
and easy to use, it creates a scroll bar if the length of the window exceeds the length of the screen.
¢ LinearLayout are one of the simplest and common type of layouts used by Android developers to
keep controls within their interfaces. The linear layout works as much as its name implies, it
organizes the controls either a vertical or horizontal pattern.
* When the layout's orientation is set to vertical, all child controls within organized in a single
column, and when the layout's orientation is set to horizontal, all child controls within in single row.

Android-orientation="horizontal" Android:orientation="vertical"

(
Ld
Ld
Fig. 3.14: LinearLayout (Vertical and Horizontal)
* LinearLayouts can be defined within XML layout resourses or programmatically in the applications
Java code. This linear layout's orientation is set to be vertical, causing each of the view controls to
display in single column from top to bottom.
e Each TextView control has its text attributes set to a color, with the same color set as the background
for the control; each control is stretched to the width of the screen by setting the controls
layout_width attribute to fill_parent. Child views can be arranged either horizontally or vertically.
« We have seen that android mobile screen size are different from device to device, some mobile sizes
are same, Suppose we are developing one application which contains a text field and button, when
the application changes from one mobile to the other mobile then the problem is regarding the
layout of the component. It happens because the size of screen varies.
Attributes of LinearLayout:
1, Id: Unique identifier of layout.
2. Orientation: Attribute to set LinearLayout orientation as vertical or horizontal.
3. Layout_Weight: This attribute assigns “importance” value at each component.
4. Gravity: This attribute shows object position in x-y plan such as center, right, top, bottom and
left.
5. Weight_sum: This attribute defines the maximum weighted sum.
6. Divider: This is drawable to use as a vertical divider between buttons.
Constructors of LinearLayout:
* LinearLayout(Context context)
* LinearLayout (Context context, AttributeSetattrs)
Mobile ication De 344 Ul Com and Layouts

« LinearLayout (Context context, AttributeSetattrs, intstyleAttribute)


* LinearLayout (Context context, AttributeSetattrs, intstyleAttribute, intstyleRes)
Example:
¢ LinearLayout looks different if the attributes values are set different for two LinearLayouts, such as
vertical LinearLayout or horizontal LinearLayout.
© Following example shows vertical LinearLayout. Here is the activity_linear_vertical xml
<?xml version="1.0" encoding="utf-8"
?>
<LinearLayout android: layout_width="368dp"
android: layout_height="495dp"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools: layout_editor_absolutex="8dp"
tools: layout_editor_absoluteY="8dp"
xmlns:android="http: //schemas.android. com/apk/res/android">
<Button
android: id="@+id/button5"
android: layout_width="match_parent”
android: layout_height="wrap_content"
android:text="Button1" />
<Button
android: id="@+id/button6"
android: layout_width="match_parent™
android: layout_height="wrap_content"
android:text="Button2" />
<Button
android: id="@+id/button?”
android: layout_width="match_parent”™
android: layout_height="wrap_content"
android:text="Button3" />
<Button
android: id="@+id/buttons”
android: layout_width="match_parent"
android: layout_height="wrap_content"
android:text="Button4" />
</LinearLayout>

Output:
ey
Mobile ication De 3.42 Ul Com and Layouts

e Here, is another example which shows horizontal LinearLayout. Below is the code for
activity_linear_horizontal
xml.
<?xml version="1.0" encoding="utf-8"
?>
<LinearLayout android: layout_width="368dp"
android: layout_height="495dp"
xmlns;:tools="http://schemas.android.com/tools"
android:orientation="horizontal”
tools: layout_editor_absoluteX="8dp"
tools: layout_editor_absoluteY="8dp"
xmlns;android="http;
//schemas. android. com/apk/res/android”>
<Button
android:id="@+id/button4"
android: layout_width="wrap_content"
android: wrap_content"
android: 1"
android:text="Button4” />
<Button
android: id="@+id/button3"
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: layout_weight="1"
android:text="Button3" />
<Button
android: id="@+id/button2"
android: layout_width="wrap_content”™
android: layout_heigh wrap_content”
android: layout_weight="1"
android:text="Button2" />
<Button
android: id="@+id/button"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: layout_weight="1"
android:text="Button1" />
</LinearLayout>
Output:

ee)
Mobile ication De 3.13 Ul Com and Layouts

3.5.2 | AbsoluteLayout
AbsoluteLayout is based on the simple idea of placing each control at an absolute position.
We specify the exact x and y coordinates on the screen for each
control AbsoluteLayout is not recommended for most UI (20, 35)
development since absolutely positioning every element on the
screen makes an inflexible UI that is much more difficult to
maintain. (100, 85)
An AbsoluteLayout lets us specify exact locations (x/y
coordinates) of its children. AbsoluteLayouts are less flexible
and harder to maintain than other types of layouts without
absolute positioning. (15, 185)
Consider what happens if a control needs to be added to the user
interface UI, we would have to change the position of every
single element that is shifted by the new control. This allows
child views to be positioned at specified x and y coordinates
within the containing layout view. Fig. 3.15: AbsoluteLayout

Example: In main.xml add following code.


<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android: layout_width="fill_parent”
android: layout_height="fill_parent">
<TextView
android: layout_x="11@px"
android: layout_y="11@px"
android:text="User Name"
android: layout_width="wrap_content"
android: layout_height="wrap_content" />
<EditText
android: layout_x="258px"
android: layout_y="8@px"
android :width="1e0px"
android: layout_width="20édp"
android: layout_height="wrap_content" />
<TextView
android: layout_x="11@px"
android: layout_y="20@px"
android: text="Password”
android: layout_width="wrap_content"
android: layout_height="wrap_content" />
<EditText
android: layout_x="25@px"
android: layout_y="158px"
android:width="16@px"
android: layout_width="2eedp"
android: layout_height="wrap_content" />
<Button
android: layout_width="wrap_content"
android: layout_height= wrap_content"
android:text="Log In"
Mobile Application Development 3.14 UI Components and Layouts
android: Layout_x="3@@px"
android: layout_y="388px"/>
</AbsoluteLayout>
« Now Open java — package — MainActivity.java and paste the below code.
import android. support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android. view.Menu;
import android. view.MenuItem;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState) ;
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//no inspection Simplifiable If Statement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);

PVetel hace}
ede ca) 9)

User Name

Password
Mobile lication Ds 3.15 Ul Com and Layouts

FrameLayout
* FrameLayout is designed to block out an area on the screen to display a single item. Generally,
FrameLayout should be used to hold a single child view, because it can be difficult to organize child
views in a way that's scalable to different screen sizes without the children overlapping each other.
e FrameLayouts are one of the simplest layout }—> FrameLayout
types used to organize controls within the user
interface of an Android application.
« The purpose of FrameLayout is to allocate an
area of screen. FrameLayout in android is for | Component1
displaying a single view.
* In the Fig. 3.16, the black frame is the Component 2
FrameLayout and in colors, we can find four
different components. The gravity settings of
each of those components look like this:
o Component 1 - (Top Left).
Fig. 3.16: FrameLayout
o Component 2 - (Top Right).
o Component 3 - (Bottom Left). ae eed
o Component 4 - (Bottom Right).
e Wecan add multiple children to a FrameLayout
. tas us FrameLayout
and control their position within the
FrameLayout by assigning gravity to each child,
. . . o ImageView big
using the android:layout_gravity attribute.
: = A a ImageView samll
e FrameLayouts are one of the most efficient Fr ameliagputD emo
types of layouts used by Android developers to
TextView
organize view controls. They are used less often
than some other layouts, simply because they
are generally used to display only one view, or
views which overlap. Fig. 3.17: FrameLayout
¢ The FrameLayout is often used as a container layout, as it generally only has a single child view
(often another layout, used to organize more than one view).
XML Attributes of FrameLayout:
1. android:id: This attribute will give the unique identity to the FrameLayout. When we want to access
the FrameLayout from the Java class, this id will give us the reference via findViewByld() method.
* Value of this attribute should be unique across the whole android app to reduce the complexity.
For example,
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas .android.com/tools"
android: id="@+id/frame"
android: layout_width="2@@dp"
android: layout_height="3@@dp"
android: foreground="@color/colorAccent"
tools: context=".MainActivity">
Mobile icatie 3.16 Ul Com and Layouts:

2. android:foreground: This attribute allows us to draw to certain view on the whole FrameLayout. The
value of this property can be a color, a drawable file or a simple image. Possible color values are
“rgb”, “#argb”, “#rrggbb”, or “#aarrggbb” according to various RGB values.
© Now make a new project in android studio. Do not touch the MainActivity.java class. Keep it as it is.
Add the below source code in activity_main.xml file.
<?xml version="1.@" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android: id="@+id/frame"
android: layout_width="20edp"
android: layout_height="3@@dp"
android: foreground="@color/colorAccent"
tools: context=".MainActivity">
<Button
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: layout_marginTop="98dp"
android: text="Button"/>
<TextView
android: layout_width="10@dp"
android: layout_height="S@dp"
android: textSize="29sp"
android: background="@color/colorPrimary"
android: textColor="#fff"
android:text="I am TextView" />
</FrameLayout>
3. android:visibility: We can apply this attribute to any child of the FrameLayout. Possible values for
visibility are visible, invisible and gone.
o Visible means that the view is present and we can also see it.
o Invisible means that the view is present and we can not see it.
o Gone means that view is not present and so we can not see it.
4. android:measureAllChildren: This property defines whether to measure all the children including
those who are with “Gone” visibility state or to measure only those who have “visible” or “invisible”
state. This property can have “True” or “False” value. If true then it will include the child with gone
visibility otherwise not.
Methods of FrameLayout:
1. generateLayoutParams(AttributeSet attrs): It Returns a new set of layout parameters based on the
supplied attributes set.
2. getAccessibilityClassName(): Return the class name of this object to be used for accessibility
purposes,
3. getMeasureAllChildren(): Determines whether all children, or just those in the VISIBLE or INVISIBLE
state, are considered when measuring. It will return boolean value, (True or False). If it returns false
then compiler will consider only VISIBLE or INVISIBLE state of children of FrameLayout. For true, it
will consider VISIBLE, INVISIBLE and GONE state of children of FrameLayout.
4. setForegroundGravity(intforegroundGravity): Describes how the foreground is positioned.
5. setMeasureAllChildren(booleanmeasureAll): Sets whether to consider all children, or just those in
the VISIBLE or INVISIBLE state, when measuring.
Mobile icatic 3.17 Ul Comp and Layouts

6. shouldDelayChildPressedState(): Return true if the pressed state should be delayed for children or
descendants of this ViewGroup.
7. generateDefaultLayoutParams(): Returns a set of layout parameters with a width of ViewGroup.
LayoutParams.MATCH_PARENT, and a height of ViewGroup.LayoutParams.MATCH_PARENT.
8. generateLayoutParams(ViewGroup.LayoutParams lp): Returns a safe set of layout parameters
based on the supplied layout params.
9. onLayout(boolean changed, int left, int top, int right, int bottom): Called from layout when this
view should assign a size and position to each of its children.
10. onMeasure(intwidthMeasureSpec, intheightMeasureSpec): Measure the view and its content to
determine the measured width and the measured height. This method is invoked by measure (int,
int) and should be overridden by sub classes to provide accurate and efficient measurement of their
contents.
Example 1; For FrameLayout:
MainActivity.java
Public class MainActivity extends AppCompatactivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState);
setContentView(R.
layout .activity_main) ;

}
In the activity_main.xml file,
<?xml version="1.8" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas .android.com/apk/res/android"
xmlns:tools="http://schemas .android.com/tools"
android: id="@+id/framelayout"
android: layout_width="20@dp"

android: layout_height="38@dp"
tools: context=".MainActivity">
<Button
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_marginTop="9@dp"
android: layout_marginLeft="2@dp"
android: text="Button"/>
<TextView
android: layout_width="10@dp"
android: layout_height="5@dp"
android: textSize="2@sp"
android: layout_marginTop="2@dp”
android: layout_marginLeft="2@dp"
android: background="@color/colorPrimary"
android: textColor= EE"
android:text="I am TextView" />
</FrameLayout>
Mobile icati 3.18 Ul Comp and Layouts

Output:

Example 2: Again, do not change anything in the MainActivity.java file. Code for activity_main.xml
is like the below:
<?xml version="1,0" encoding="utf-8"
?>
<FrameLayoutxmlns: android="http: //schemas. android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android: id="@+id/framelayout"
android: layout_width="match_parent”
android: layout_height="match_parent”

tools:context=".MainActivity">
<ImageView
android: layout_width="match_parent”
android: layout_height="match_parent”
android: scaleType="fitxy"
android: src="@mipmap/ic_launcher_round"/>
<Button
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_marginTop="@dp"
android: layout_gravity="center_horizontal”
android: layout_marginLeft="@dp"
android: text="Button"
/>
<TextView
android: layout_width="10edp"
android: layout_height="5@dp"
android: textSize="20sp"
android: layout_gravity="center"

android: background="@color/colorPrimary”
android: textColor="#fff"
android:text="I am TextView" />
</FrameLayout>
Mobile lication Ds 3.19 Ul Com and Layouts

TableLayout
Android TableLayout going to be arranged groups of views into rows and columns. We will use the
<TableRow> element to build a row in the table. Each row has zero or more cells; each cell can hold
one View object.
TableLayout arranges child views into a grid format of columns and rows. Each row within a table is
represented by a TableRow object child, which contains a view object for each cell.
TableLayout organizes content into columns and <TableLayout>
rows. The rows are defined in the layout XML code, Row 4
and the columns are determined automatically by
Android, which is done by creating at least one Row2 | Row2 | Row2
column for each element. column 1] column 2 column 3
So, for example, if we have a row with two elements
and a row with five elements then we would have a Row 3 Row 3
layout with two rows and five columns. column 1 column 2
We can specify that an element should occupy more
than one column using android:layout_span. So if
we have a row with two elements and each element
has android:layout_span="2" then we will have at
least six columns in our table.
By default, Android places each element in the first
unused column in the row. We can indicate the </TableLayout>
column an element should occupy using
Fig. 3.18: TableLayout
android:layout_column.
In Android, TableLayout is a ViewGroup subclass which is used to display the child View elements in
rows and columns. TableLayout containers do not display border lines for their rows, columns, or
cells.
A TableLayout is exactly what we might expect, a grid of made up of rows and columns, where a cell
can display a view control. From a user interface design perspective, a TableLayout is comprised of
TableRow controls, one for each row in our table. The contents of a TableRow are simply the view
controls that will go in each “cell” of the table grid.
The appearance of a TableLayout is governed by several additional rules. First, the number of
columns of the entire table matches the number of columns in the row with the most columns.
Second, the width of each column is defined as the width of the widest content in the column.
Mobile lication Ds 3.20 Ul Com and Layouts

¢ The TableLayout’s child rows and cells layout_width attributes are always MATCH PARENT -
although they can be put in an XML file, the actual value can't be overridden.
e The TableLayout’s layout_height of a cell can be defined, but a TableRow attribute for layout_height
is always WRAP_CONTENT.
¢ Cells can span columns, but not rows. This is done through the layout_span attribute of the child
view of a TableRow. A cell is a single child view within a TableRow. If we want a more complex cell
with multiple views, use a layout view to encapsulate the other views.
« Some rules can be modified. Columns can be marked as stretchable, which means that the width can
expand to the size of the parent container. Columns can also be marked as shrinkable, which means
that they can be reduced in width so the whole row will fit in the space provided by the parent
container. We can also collapse an entire column.
Example: For TableLayout
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http: //schemas.android.com/apk/res/android”
android: id="@+id/tableLayout1"
android: layout_width="match_parent”
android:
android:
android: stretchColumns="*">
<TableRow
android: id="@+id/tableRow4"
android: layout_height="wrap_content"
android: layout_width="match_parent"
android: gravity="center_horizontal">
<TextView
android: id="@+id/textView9"
android: layout_width="match_parent"
android: layout_height="wrap_content"
android: textStyle="bold”
android: typeface="serif"
android: textSize="18dp"
android: text="Weather Table"
android: gravity="center"
android: layout_span="6"></TextView>
</TableRow>
<TableRow
android: id="@+id/tableRow1"
android: layout_height="wrap_content"
android: layout_width="match_parent">
<TextView
android: id="@+id/TextView@4"
android: text=""></TextView>
<TextView
android: id="@+id/TextView@4"
android: text="Feb 7"
android: textStyle="bold”
android: typeface="serif"></TextView>
Mobile icatic 3.21 Ul Comp and Layouts

<TextView
android: id="@+id/TextView@3"
android:text="Feb 8"
android: textStyle="bold"
android: typeface="serif"></TextView>
<TextView
android: id="@+id/TextView@2"
android:text="Feb 9"
android: textStyle="bold"
android: typeface="serif"></TextView>
<TextView
android: id="@+id/TextViewo1"
android:text="Feb 10"
android: textStyle="bold"
android: typeface="serif"></TextView>
<TextView
android:text="Feb 11"
android: id="@+id/textView1"
android: textStyle="bold"
android: typeface="serif"></TextView>
</TableRow>
<TableRow
android: layout_height="wrap_content"
android: id="@+id/tableRow2"
android: layout_width="match_parent">
<TextView
android: text="Day High"
android: id="@+id/textView2"
android: textStyle="bold"></TextView>
<TextView
android: id="@+id/textView3"
android: text="28°F"
android: gravity="center_horizontal"></TextView>
<TextView
android: text="26°F"
android: id="@+id/textViewa"
android: gravity="center_horizontal"></TextView>
<TextView
android: text="23°F"
android: id="@+id/textViewS"
android:gravity="center_horizontal"></TextView>
<TextView
android: tex' 17°F"
android: id= @+id/textView6”
android: gravity="center_horizontal"></TextView>
<TextView
android: text="19°F"
android: id="@+id/textView7"
android: gravity="center_horizontal"></TextView>
Mobile 3.22 UI Comp and Layouts
</TableRow>
<TableRow
android: layout_height="wrap_content”
android: id="@+id/tableRow2"
android: layout_width="match_parent">
<TextView
android: text="Day Low”
android: id="@+id/textView2"
android: textStyle="bold"></TextView>
<TextView
android: text="15°F"
android: id="@+id/textView3”"
android: gravity="center_horizontal"></TextView>
<TextView
android: text="14°F"
android: id="@+id/textViews”
android: gravity="center_horizontal"></TextView>
<TextView
android: text="3°F"
android: id="@+id/textViews”
android: gravity="center_horizontal"></TextView>
<TextView
android: text="5°F"
android: id="@+id/textView6”
android: gravity="center_horizontal"></TextView>
<TextView
android: text="6°F"
android: id="@+id/textView7"
android: gravity="center_horizontal"></TextView>
</TableRow>
<TableRow
android: id=" @+id/tableRow3"
android: layout_height="wrap_content"
android: layout_width="match_parent"
android: gravity="center">
<TextView
android: id="@+id/textVviews”
android: text="Conditions”
android: textStyle="bold"></TextView>
<ImageView
android: id="@+id/imageView1"
android: src="@drawable/hot"></ImageView>
<ImageView
android: id="@+id/imageView2"
android: src="@drawable/pt_cloud”></ImageView>
<ImageView
android: id="@+id/imageView3"
android: src="@drawable/snow"></ImageView>
Mobile ication De t 3.23 Ul Com and Layouts

<ImageView
android: id="@+id/imageView4"
android: src="@drawable/1t_snow" ></ImageView>
<ImageView
android: id="@+id/imageView5"
android: src="@drawable/pt_sun"></ImageView>
</TableRow>
</TableLayout>

Weather Table

3 RelativeLayout
¢ RelativeLayout as the name suggests, shows position of components relative to each other. The
position can be specified with respect to consecutive elements or to the parent component.
* RelativeLayout is most flexible layout provided by Android. It lets
us to position elements on the screen. By default, it sets all
components at the top left of the layout.
e Android RelativeLayout enables us to specify how child views are
positioned relative to each other. The position of each view can
be specified as relative to sibling elements or relative to the
parent.
e RelativeLayout is a view group that displays child views in
relative positions.
e The position of each view can be specified as relative to sibling
elements (such as to the left-of or below another view) or in
positions relative to the parent RelativeLayout area. (such as
Fig. 3.19: RelativeLayout
aligned to the bottom, left or center).
© RealativeLayout is probably the most powerful and flexible of the layout managers, which allows
child views to be positioned relative both to each other and the containing layout view through the
specification of alignments and margins on child views.
e For instance, child View X may be configured to be positioned in the vertical and horizontal center of
the containing RelativeLayout view. View Y, or on other hand, might also be configured to be
centered horizontally within the layout view, but positioned 30 pixels on top of the top edge of View
X, thereby making the vertical position relative to that of View X.
« The RelativeLayout manager can be of particular use when designing a user interface that must
work on avariety of screen sizes and orientations.
e In RelativeLayout the elements based on their relationships with each other, and with the parent
container. This is possibly the most complicated layout, and we require several properties to actually
get the layout we want.
Mobile 3.24 UI Comp and Layouts
* These properties will layout elements comparative to the parent container.
Sr.
No. Properties Description

1. | android: layout_alignParentBottom It places the bottom of the element on the bottom of the
container.
2. android: layout_alignParentLeft It places the left of the element on the left side of the
container.
3. | android: layout_alignParentRight It places the right of the element on the right ide of the
container.
4. | android: layout_alignParentTop It places the element at the top of the container.
5. | android: layout_centerHorizontal It centers the element horizontally within its parent
container.
6. | android: layout_centerInParent It centers the element both horizontally and vertically
within its container.
7. | android: layout_centerVertical It centers the elements vertically within its parent
container.
e These properties allow us to layout elements relative to other elements on screen. The value for each
element is the id of the element we are using to layout the new element.
* Every element that is used this way must have an ID defined using android:id="@a+id/viewname”
where, viewname is replaced with the desired id. We use “@id/viewname’” to refer to an element by
its id.

Properties Description

1 android: layout_above It places the element above the specified element.


2 android: layout_below It places the element below the specified element.
3. | android: layout_toLeftOf It places the element to the left of the specified element.
4 android: Layout_toRightof It places the element to the right of the specified
element.
5. | android: layout_alignBaseline It aligns baseline of the new element with the baseline of
the specified element.
6. | android: layout_alignBottom It aligns bottom of the new element with the bottom of
the specified element.
7. | android: layout_alignLeft It aligns left edge of the new element with the left edge
of the specified element.
8. | android: layout_alignRight It aligns right edge of the new element with the right
edge of the specified element.
9. | android: layout_alignTop It aligns top of the new element with the top of the
specified element.
Example: For RelativeLaout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android= ‘ttp://schemas.android.com/apk/res/android"
android: layout_width="fill_parent”
android: layout_heigh ¥ill_parent” >
Mobile ication De t 3.25 Ul Com and Layouts
<Button
android:i “@+id/btnButton1"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android itext="Button 1"/>
<Button
android: id="@+id/btnButton2"
android: “wrap_content”
android: ‘wrap_content”"
android:
android: layout_toRightOf="@+id/btnButtoni"/>
<Button
android: id="@+id/btnButton3"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android :text="Button 3"
android: layout_below="@+id/btnButton1"/>
<TextView
android:i “@+id/textView1"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: layout_below="@+id/btnButton3"
android: layout_marginTop="94dp"
android :text="User :"
android: textAppearance="?android:attr/textAppearanceLarge” />
<EditText
android: id="@+id/editText1"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_alignParentRight="true"
android: layout_alignTop="@+id/textView1"
android: layout_toRightOf="@+id/btnButton3" />
<Button
android: "@+id/btnSubmit”
android: layout_width="wrap_content”
android: layout_height="wrap_content”
android: layout_alignParentRight="true”
android: layout_below="@+id/editText1"
android itext="Submit" />
</RelativeLayout>
Output:
Mobile Application Development 3.26 UI Components and Layouts

| Practice Questions
What is meant by control flow?
wp wenawpwner

Explain screen elements for Android.


What is directory?
Describe directory structure in detail.
Explain the term fundamentals of UI design in detail.
What is meant by layout?
Explain Linearlayout with example.
Describe FrameLayout with example.
Explain the following terms:
(i) TableLayout
(ii) AbsoluteLayout.
10. Define the term Layout.
11. Write down the control flow of an Android application step by step.
Describe directory structure of Android application.
List the different components of a screen.
14, Explain the term fundamentals of UI design in detail.
List various layouts used in Android UI design.
16. Develop an Android application using linear layout.
17. Develop an Android application using absolute layout.
18. Develop an Android application using frame layout.
19. Develop an Android application using relative layout.
20. Develop an Android application using table layout.
lus

4...
Designing User
Interface with View |,
Chapter Outcomes...
Develop rich user interfaces for the given Android application.
Seee

Develop Android application using the given view.


Explain the significance of the given display alert.
Develop the given application using time and date picker.

Learning Objectives...
To learn Designing User Interface with View in Android
ID)

To study varoious UI Controls


il

To learn Text View, Edit Text; Checkbox, Button (Image and Toggle), Progress Bar etc., with Examples
To understand List View, Grid View, Image View, Scroll View, Date Picker etc., with Examples
wl

Xa wrropucrion
* View class represents the basic building block for User Interface (UI) components. A View occupies a
rectangular area on the screen and is responsible for drawing and event handling. View is the base
class for widgets, which are used to create interactive UI components (buttons, text fields, etc.).
¢ The ViewGroup subclass is the base class for layouts, which are invisible containers that hold other
Views (or other ViewGroups) and define their layout properties.
* AViewGroup is a special view that can contain other views (called children.) The view group is the
base class for layouts and views containers.
e The view is the component which Android provides us to design the layouts of the app. A View is a
superclass for all the UI components.
View

—— os]
TextView ImageView ViewGroup

rN f
EditText Button ImageButton

_—— _———~
CheckBox RadioButton ToggleButton

Fig. 4.1: linheritance Hierarchy of Designing User Interface (U1) with View
[4.1]
Mobile Application Development 42 Designing User Intertace with View
Input controls are the interactive components in the app's User Interface (UI). Android provides a
wide variety of controls we can use in the UI, such as buttons, text fields, seek bars, checkbox, zoom
buttons, toggle buttons, and many more.
This chapter deals with how to design a page by using Graphical User Interface (GUI), as it is very
important to design a good looking page for apps in Android. Here we will discuss GUI like TextView
(Label), Button, EditText(TextField), CheckBox etc.
The User Interface (UI) for each component of the app is defined using a hierarchy of View and
ViewGroup, as shown in Fig. 4.1. Each view group is an invisible container that organizes child views,
while the child views may be input controls or other widgets that draw some part of the UL

Co TextView
ATextView displays text to the user and optionally allows them to edit it. A TextView is a complete
text editor, however the basic class is configured to not allow editing.
A standard read-only text label that supports string formatting, multiline display and automatic
word wrapping. A TextView is a entire text editor, however the basic class is configured to not allow
editing. A TextView Inherits all of TextView attributes and Inherits all TextView methods
Attributes/Properties of TextView:
1. id: Supply an identifier name of this view, to later retrieve it with View.findViewByID() or
Activity.findViewByld().
<TextView
android: id="@+id/simpleTextView"
android: layout_width="wrap_content"
android: layout_height="wrap_content"/>
alpha: This property of the view as a value between 0 (entirely transparent) and 1(Completely
Opaque).
auto link: Controls whether links such as urls and email addresses are automatically found and
converted to clickable links.
gravity: The gravity attribute is an optional attribute which is used to control the alignment of the
text like left, right, center, top, bottom, center_vertical, center_horizontal etc. Below is the example
code with explanation included in which we set the center_vertical gravity for text of a TextView.
<TextView
android: id="@+id/simpleTextView"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: text="Hello"
android: textSize="2@sp"
android: gravity="center_vertical"/>
text: This attribute is used to set the text in a TextView. We can set the text in xmlas well as in
the Java class. Below is the example code with explanation included in which we set the text “Hello”
in a text view.
<TextView
android: id="@+id/simpleTextView"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android:textSize="25sp"
android:text="Hello"/><!--Display Text as Hello-->
Mobile Application Development 43 Designing User Interface with View
6. textColor: This attribute is used to set the text color of a TextView. Color value is in the form of
“#argb”", “#rgb”, “#rrggbb”, or “#aarrggbb”. Below is the example code with explanation included in
which we set the red color for the displayed text.
<TextView
android: id="@+id/simpleTextView"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: text="Hello"
android: layout_centerInParent="true"
android: textSize="25sp"
android: textColor="#f00"/><!--red color for text view-->
7. textSize: This attribute is used to set the size of text of a TextView. We can set the text size in sp (scale
independent pixel) or dp(density pixel). Below is the example code in which we set the 20sp size for
the text of a text view.
<TextView
android: id="@+id/simpleTextView"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: text="Hello”
android: layout_centerInParent="true”
android:textSize="45sp"/><|--Set size-->
8. textStyle: This attribute is used to set the text style of a TextView. The possible text styles are bold,
italic and normal. If we need to use two or more styles for a text view then “|” operator is used for
that. Below is the example code with explanation included in which we set the bold and italic text
styles for text.
<TextView
android: id="@+id/simpleTextView"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: text="Hello"
android: layout_centerInParent="true”
android: textSize="45sp"
android: textStyle="bold|italic"/><!--bold and italic text style of text-->
9. background: The background attribute is used to set the background of a text view. We can set a
color or a drawable in the background of a TextView.
10. padding: This attribute is used to set the padding from left, right, top or bottom. In above example
code of background we also set the 10dp padding from all the side’s of text view. Below is the
example code with explanation included in which we set the black color for the background, white
color for the displayed text and set 10dp padding from all the side's for text view.
<TextView
android: id="@+id/simpleTextView"
android: layout_width="wrap_content"
android: layout_height="wrap_content
android: text="Hello"
android: layout_centerInParent="true
android: textSize="45sp"
android: padding="1@dp"
android: textColor="#fff"
android: background="#006" />
Mobile Application Development 44 Designing User Interface with View

Example: This example will take us through simple steps to show how to create our own Android
application using LinearLayout and TextView. In this example we are going to create a simple UI, that
includes only TextView with different attributes. Following is the content of the modified main activity
file src/com.example.demo/Main Activity.java. This file can include each of the fundamental lifecycle
methods.
package com.example.demo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android. view. View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
@0verride
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//--- text view---
TextView txtView = (TextView) findViewById(R.id.text_id);

}
Following will be the content of res/layout/activity_main.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android: layout_width="match_parent”
android: layout_height="match_parent"
android: paddingBottom="@dimen/activity_vertical_margin"
android: paddingLeft="@dimen/activity_horizontal_margin”
android: paddingRight="@dimen/activity_horizontal_margin"
android: paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android: id="@+id/text_id"
android: layout_width="3@8dp"
android: layout_height="260dp"
android: capitalize="characters"
android: text="hello_world"
android: textColor="@android:color/holo_blue_dark"
android: textColorHighlight="@android: color/primary_text_dark"
android: layout_centerVertical="true"
android: layout_alignParentEnd="true"
android: textSize="S5@dp"/>
</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants:
<?xml version="1.6" encoding="utf-8"?>
<resources>
<string name="app_name">demo</string>
</resources>
Mobile Application Development 45 Designing User Interface with View

Following is the default content of AndroidManifest.xml:


<?xml version="1.6" encoding="utf-8"?>
«manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo" >
<application
android: allowBackup="true"
android: icon="@drawable/ic_launcher"
android: label="@string/app_name"
android: supportsRtl="true"
android: theme="@style/AppTheme" >
<activity
android: name="com.example.demo.MainActivity"
android: label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER” />
</intent-filter>
<factivity>
</application>
</manifest>
e Let us try to run the application. Assume we had created our AVD while doing environment setup. To
run the app from Android studio, open one of our project's activity files and click Run Gicon from
the toolbar. Android studio installs the app on our AVD and starts it and if everything is fine with our
setup and application, it will display following Emulator window:

EF editrext
* An editable text entry box that accepts multiline entry, word wrapping and hint text. A EditText is an
overlay over TextView that configures itself to be editable. It is the predefined subclass of TextView
that includes rich editing capabilities.

Fig. 4.2: Styles of EditText


Mobile Application Development 4.6 Designing User Interface with View
Properties of EditText:
1. alpha: The alpha property of the view, as a value between O (completely transparent) and 1
(Completely opaque) [float].
id: The id is an attribute used to uniquely identify a text EditText. Below is the example code in which
we set the id of a EditText.
<EditText
android: id="@+id/simpleEditText”
android: layout_height="wrap_content"
android: layout_width="match_parent"/>
gravity: The gravity attribute is an optional attribute which is used to control the alignment of the
text like left, right, center, top, bottom, center_vertical, center_horizontal etc. Below is the example
code with explanation included in which we set the right gravity for text of a EditText.
<EditText
android: id="@+id/simpleEditText"
android: layout_width="fill_parent”
android: layout_height="wrap_content"
android:text="Enter Email"
android: gravity="right"/><!--gravity of a edit text-->
text: The text attribute is used to set the text in a EditText. We can set the text in xml as well as in
the java class. Below is the example code in which we set the text “Username” in a edit text.
<EditText
android: id="@+id/simpleEditText"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android: text="Username"/><!--set text in edit text-->
hint: The hint is an attribute used to set the hint i.e. what we want user to enter in this edit text.
Whenever, user start to type in edit text the hint will automatically disappear. Below is the example
code with explanation in which we set the hint of a edit text.
<EditText
android: id="@+id/simpleEditText"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android:hint="Enter Your Name Here"/><!--display the hint-->
6. textColor: The textColor attribute is used to set the text color of a text EditText. Color value is in the
form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”. Below is the example code with explanation
included in which we set the red color for the displayed text of a EditText.
<EditText
android: id="@+id/simpleEditText”
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_centerInParent="true”
android: text="Password"
android: textColor="#f0e"/><!--set the red text color-->
textColorHint: The textColorHint is an attribute used to set the color of displayed hint. Below is the
example code with explanation included in which we set the green color for displayed hint of a edit
text.
Mobile Application Development 47 Designing User Interface with View
<EditText
android: id="@+id/simpleEditText”
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android:hint="Enter Your Name Here"
android: textColorHint="#8f6"/><!--set the hint color green-->
textSize: The textSize attribute is used to set the size of text of a edit text. We can set the text size in
sp (scale independent pixel) or dp (density pixel). Below is the example code in which we set the 25sp
size for the text of a edit text.
<EditText
android: id="@+id/simpleEditText"
android: layout_width="fill_parent"
android: layout_height="wrap_content”
android: layout_centerInParent="true"
android: text="AbhiAndroid"
android:textSize="25sp" /><!--set 25sp text size-->
textStyle: The textStyle attribute is used to set the text style of a edit text. The possible text styles are
bold, italic and normal. If we need to use two or more styles for a edit text then “|" operator is used
for that. Below is the example code with explanation included, in which we set the bold and italic text
styles for text.
<EditText
android: id="@+id/simpleEditText"
android: layout_width="f1i11_parent"
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android: text="Email"
android: textSize="25sp"
android: textStyle="bold|italic"/><!--set bold and italic text style-->
10. background: The background attribute is used to set the background of a edit text. We can set a color
or a drawable in the background of a edit text. Below is the example code with explanation included
in which we set the black color for the background, white color for the displayed hint and set 10dp
padding from all the side's for edit text.
<EditText
android: id="@+id/simpleEditText”
android: layout_width="fill_parent"
android: layout_height="wrap_content”
android: layout_centerInParent="true"
android:hint="Enter Your Name Here"
android: padding="1@dp"
android: textColorHint="#f ff"
android:textStyle="bold|italic”
android: background="#006"/><!--set background color black-->
11, padding: The padding attribute is used to set the padding from left, right, top or bottom. In above
example code of background we also set the 10dp padding from all the side's of edit text.
Example: In activity_main.xml add following code.
<?xml version="1.60" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools”
Mobile Application Development 48 Designing User Interface with View

android: id="@+id/activity_main”
android: layout_width="match_parent”
android : layout_height="match_parent"
android: paddingBottom="@dimen/activity_vertical_margin"
android: paddingLeft="@dimen/activity_horizontal_margin"
android: paddingRight="@dimen/activity_horizontal_margin"
android: paddingTop="@dimen/activity_vertical_margin”
tools: context="com.example.edittextexample.MainActivity">
<EditText
android: id="@+id/editText1"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_alignParentLeft="true"
android: layout_alignParentStart="true"
android: layout_alignParentTop="true"
android: layout_marginLeft="5@dp"
android: layout_marginStart="5@dp"
android: layout_marginTop="24dp"
android: ems="10"
android: hint="@string/name"
android: inputType="textPersonName"
android: selectAllOnFocus="true” />
<EditText
android: id="@+id/editText2"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_alignLeft="@+id/editText1"
android: layout_alignStart="@+id/editText1"
android: layout_below="@+id/editText1"
android: layout_marginTop="19dp"
android: ems="10"
android: hint="@string/password_@_9"
android: inputType="numberPassword" />
<EditText
android: id="@+id/editText3"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_alignLeft="@+id/editText2"
android: layout_alignStart="@+id/editText2"
android: layout_below="@+id/editText2"
android: layout_marginTop="12dp"
android: ems="16"
android: hint="@string/e_mail"
android: inputType="textEmailAddress" />
<EditText
android: id="@+id/editText4”
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: layout_alignLeft="@+id/editText3"
android: layout_alignStart="@+id/editText3"
android: layout_below="@+id/editText3"
android: layout_marginTop="18dp"
android: ems="10"
android: hint="@string/date"
android: inputType="date" />
Mobile Application Development 49 Designing User interface with View

<EditText
android: id="@+id/editText5"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_alignLeft="@+id/editText4"
android: layout_alignStart="@+id/editText4"
android: layout_below="@+id/editText4"
android: layout_marginTop="18dp"
android:ems="16"
android: hint="@string/contact_number"
android: inputType="phone" />
<Button
android: id="@+id/button"
style="@android: style/Widget. Button"
android: layout_width="match_parent"
android: layout_height="wrap_content"
android: layout_alignParentLeft="true”
android: layout_alignParentStart="true"
android: layout_below="@+id/editText5s”
android: layout_marginTop="62dp"
android: text="@string/submit"
android: textSize="16sp"
android: textStyle="normal|bold" />
</RelativeLayout>
In MainActivity.java add the below code:
package com.example.edittextexample;
import android. support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android. view.View;
import android.widget .Button;
import android. widget .EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button submit;
EditText name, password, email, contact, date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.editText1);
password = (EditText) findViewById(R.id.editText2);
email = (EditText) findViewById(R.id.editText3);
date = (EditText) findViewById(R.id.editText4);
contact = (EditText) findViewById(R.id.editText5);
submit = (Button) findViewById(R.id.button);
submit. setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (name.getText().toString().isEmpty() | |
password. getText().toString().isEmpty() || email.getText().toString().isEmpty() ||
date.getText().toString().isEmpty() || contact.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(), "Enter the Data",
Toast. LENGTH_SHORT).show();
Mobile Application Development 4,10 Designing User Interface with View

} else {
Toast.makeText(getApplicationContext(), "Name - " +
name.getText().toString() + " \n" + "Password - " + password.getText().toString()
+" \n" + "E-Mail - " + email.getText().toString() + " \n" + “Date - "
+ date. getText().toString() + " \n" + “Contact - "
+ contact.getText().toString(), Toast.LENGTH_SHORT).show();

}
y)3

}
“xm BUTTON
e In Android operating system, Button represents a push button. A Button is a Push-button which can
be pressed, or clicked, by the user to perform an action.
« A Push buttons can be clicked, or pressed by the user to perform an action. There are different types
of buttons used in android such as CompoundButton, ToggleButton, RadioButton.
e Button is a subclass of TextView class and compound button is the subclass of Button class.On a
button we can perform different actions or events like click event, pressed event, touch event etc.
Properties of Button:
1. Auto link: Controls whether links such as urls and email addresses are automatically found and
converted to clickable links.
2. Clickable: Defines whether this view reacts to click events.
3. id:id is an attribute used to uniquely identify a text Button. Below is the example code in which we
set the id of a Button.
<Button
android: id="@+id/simpleButton"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: text="Android"/>
4. gravity: The gravity attribute is an optional attribute which is used to control the alignment of the
text like left, right, center, top, bottom, center_vertical, center_horizontal etc, Below is the example
code with explanation included in which we set the right and center vertical gravity for text of a
Button.
<Button
android: id="@+id/simpleButton"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: text="Android"
android: layout_centerInParent="true"
android: gravity="right|center_vertical"/><!--set the gravity of button-->
5. text: The text attribute is used to set the text in a Button. We can set the text in xml as well as in
the Java class. Below is the example code with explanation included in which we set the text “Learn
Android” in a Button.
<Button
android: id="@+id/simpleButton"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android:text="Learn Android "/><!--display text on button-->
Mobile Application Development 41 Designing User Interface with View
6. textColor: The textColor attribute is used to set the text color of a Button. Color value is in the form
of “#argb”, “#rgb", “#rrggbb”, or “#aarrggbb”. Below is the example code with explanation included
in which we set the red color for the displayed text of a Button.
<Button
android: id="@+id/simpleButton"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android: text="Android"
android: textColor="#f00"/><!--red color for the text-->
7. textSize: The textSize attribute is used to set the size of the text on Button. We can set the text size in
sp (scale independent pixel) or dp (density pixel). Below is the example code in which we set the 40sp
size for the text of a Button.
<Button
android: id="@+id/simpleButton”
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android: text="Android"
android: textSize="4@sp"/><!--48sp text size-->
8. textStyle: The textStyle attribute is used to set the text style of a Button. The possible text styles are
bold, italic and normal. If we need to use two or more styles for a Button then “|” operator is used for
that. Below is the example code with explanation included, in which we set the bold and italic text
styles for text of a button.
<Button
android: id="@+id/simpleButton"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android: text="Android"
android:textSize="4@sp"
android:textStyle="bold|italic"/><!--bold and italic text style-->
9. background: The background attribute is used to set the background of a Button, We can set a color
or a drawable in the background of a Button. Below is the example code in which we set the gren
color for the background, Black color for the displayed text and set 20dp padding from all the side’s
for Button.
<Button
android: id="@+id/simpleButton"
android: layout_width="fill_parent”
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android: text="Download"
android: textSize="4@sp"
android: padding="20dp"
android: textColor="#806"
android:textStyle="bold|italic"
android: background="#147D@3" /><!--Background green color-->
10. padding: The padding attribute is used to set the padding from left, right, top or bottom. In above
example code of background we also set the 10dp padding from all the side's of button.
Mobile Application Development 4.12 Designing User Interface with View
11, drawableBottom: The drawableBottom is drawable to be drawn to the below of the text. Below is the
example code in which we set the icon to the below of the text. Make sure we have image saved in our
drawable folder name ic_launcher.
<Button
android: id="@+id/simpleButton”
android: layout_width="fill_parent”
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android: background="#147De3"
android:text="Download Code"
android: textSize="20sp"
android: padding="15dp"
android:textStyle="bold|italic"
android: drawableBottom="@drawable/ic_launcher"/><!--image drawable on button-->
12, drawableTop, drawableRight and drawableLeft: Just like the above attribute we can draw drawable
to the left, right or top of text. In the below example we set the icon to the right of the text. In the
same way we can do for other two attribute by own:
<Button
android: id="@+id/simpleButton"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_centerInParent="true"
android: background="#147003"
android:text="Download Code"
android:textSize="28sp"
android: padding="15dp"
android:textStyle="bold|italic"
android: drawableRight="@drawable/ic_launcher"/><!--image drawable on Right side of
Text on button-->

Example: Of Button and TextView. In activity_main.xml add following code:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmins:tools="http://schemas.
android. com/tools”
android: layout_width="match_parent"
android: layout_height="match_parent"
android: paddingBottom="@dimen/activity_vertical_margin"
android: paddingLeft="@dimen/activity_horizontal_margin"
android: paddingRight="@dimen/activity_horizontal_margin”
android: paddingTop="@dimen/activity_vertical_margin"
tools: context=".MainActivity">
<TextView
android: id="@+id/simpleTextView"
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: layout_centerHorizontal="true"
android: text="Before Clicking”
android: textColor="#f66"
android:textSize="25sp"
android: textStyle="bold|italic"
android: layout_marginTop="5@dp"
/>
<Button
android: id="@+id/btnChangeText"
Mobile Application Development 4.13 Designing User Interface with View

android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: layout_centerInParent="true"
android: background="#f60"
android: padding="16dp"
android:text="Change Text"
android:textColor="#fff"
android: textStyle="bold"/>
</RelativeLayout>
In MainActivity.java add the following code
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android. view.Menu;
import android. view.MenuItem;
import android.view. View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extendsAppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //set the layout
finalTextView simpleTextView =(TextView) findViewById(R.id.simpleTextView);
//get the id for TextView
Button changeText =(Button) findViewById(R.id.btnChangeText); //get the id for button
changeText .setOnClickListener(newVview.OnClickListener(){
@Override
publicvoid onClick(View view){
simpleTextView.setText("After Clicking");
//set the text after clicking button

After Clicking

ra ImageButton
An ImageButton is an AbsoluteLayout which enables us to specify the exact location of its children.
This shows a button with an image (instead of text) that can be pressed or clicked by the user.
In Android, ImageButton is used to display a normal button with a custom image in a button. In
simple words we can say, ImageButton is a button with an image that can be pressed or clicked by
the users
Mobile Application Development 4.14 Designing User Interface with View
e By default it looks like a normal button with the standard button background that changes the color
during different button states.
Font Awesome Text

QOFAorwneé
Basic Buttons

Rounded Buttons

Fig. 4.3: Image Buttons


Properties of ImageButton:
1. id: The id is an attribute used to uniquely identify a image button. Below is the example code in
which we set the id of a image button.
<ImageButton
android: id="@+id/simpleImageButton"
android: layout_width="wrap_content”
android: layout_height="wrap_content"/>
2. src: The src is an attribute used to set a source file of image or we can say image in the image button
to make layout look attractive. Below is the example code in which we set the source of an image
button. Make sure we have saved an image in drawable folder name, home, before using below code.
<ImageButton
android: id="@+id/simpleImageButton”
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: src="@drawable/home"/><!--src(source)file from drawable folder which display
an imagebutton-->
3. background: The background attribute is used to set the background of an image button. We can set
a color or a drawable in the background of a Button. Below is the example code in which we set the
black color for the background and an home image as the source of the image button.
<ImageButton
android: id="@+id/simpleImageButton"
android: layout_width="wrap_content”
android: layout_height="wrap_content"”
android: src="@drawable/home"
android: background="#000"/><!-- black background color for image button-->
4, padding: The padding attribute is used to set the padding from left, right, top or bottom of the
ImageButton.
* paddingRight: Set the padding from the right side of the image button.
paddingLeft: Set the padding from the left side of the image button.
* paddingTop: Set the padding from the top side of the image button.
« paddingBottom: Set the padding from the bottom side of the image button.
e padding: Set the padding from the all side’s of the image button.
Below is the example code of padding attribute in which we set the 20dp padding from all the side’s
of a image button.
<ImageButton
android: id="@+id/simpleImageButton”
Mobile Application Development 4.15 Designing User Interface with View
android: layout_width="wrap_content”
android: layout_height="wrap_content”
android: background="#000"
android: src="@drawable/home"
android: padding="2@dp"/><!-- set 2@dp padding from all the sides of the view-->
* In the below example of ImageButton we display two custom image buttons with source and
background. One is simple image button with simple background and other one is a round corner
image button and whenever we click on an button, the name of the button will be displayed in a
toast. Below is the code and final output:
Step 1: Create a new projectand name it ImageButtonExample. In this step wecreate a new
project in android studio by filling all the necessary details of the app like app name, package
name, api versions etc.
SelectFile — New — NewProjectandFill the forms and click “Finish" button.
Step 2: Right click on drawable — New -— Drawable resource file and create new xml file
name custom_image-buttton.xml and add following code. In this Step we create drawable xml in
which we used solid and corner properties, solid is used to set the background color for the image
button and corner is used to set the radius for button corners.
<?xml version="1.0" encoding="utf-8"?>
<shapexmlns:android="http://schemas.android.com/apk/res/android">
<solidandroid: color="#900"/><!-- background color for imagebutton-->
<cornersandroid:radius="20dp"/><!-- round corners for imagebutton-->
</shape>
Step 3: Open app —> layout — activity_main.xml (or) main.xml and add following code: In this step, we
open an xml file and add the codewhich display two custom image buttons by using src,
background, gravity and other attributes in Relative Layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android: layout_width="match_parent"
android: layout_height="match_parent"
android: paddingBottom="@dimen/activity_vertical_margin"
android: paddingLeft="@dimen/activity_horizontal_margin"
android: paddingRight="@dimen/activity_horizontal_margin"
android: paddingTop="@dimen/activity_vertical_margin"
tools: context=".MainActivity”>
<!--Make sure to save two images home and youtube in drawable folder-->
<ImageButton
android: id="@+id/simpleImageButtonHome"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: layout_centerHorizontal="true"
android: background="@drawable/custom_image_button"
android: padding="26dp"
android: src="@drawable/home" />
<ImageButton
android: id="@+id/simpleImageButtonYouTube”
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_below="@+id/simpleImageButtonHome"
android: layout_centerHorizontal="true"
android: layout_marginTop="2@dp"
android: background="#605"
android: padding="26dp"
Mobile Application Development 4,16 Designing User Interface with View

android: src="@drawable/youtube"
/>
</RelativeLayout>
Step 4: Open app > package — MainActivity.java. In this step, we add the code to initiate the image
button’s and then perform click event on them and display the text for selected item using a
toast.
import android.app.Activity;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android. view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate view's
ImageButton simpleImageButtonHome
=(ImageButton)findViewById(R.id.simpleImageButtonHome);
ImageButton simpleImageButtonYouTube
=(ImageButton) findViewById(R.id.simpleImageButtonYouTube);
// perform click event on button's
simpleImageButtonHome. setOnClickListener(newView.OnClickListener(){
@Override
public void onClick(View view){
Toast .makeText(getApplicationContext(), "Home Button”, Toast.LENGTH_LONG).show();
// display the toast on home button click
}
})5
simpleImageButtonYouTube.setOnClickListener(newView.OnClickListener(){
@Override
publicvoid onClick(View view){
Toast.makeText(getApplicationContext(), "YouTube Button", Toast.LENGTH_LONG).show();
// display the toast on you tube button click
}
5
}
}
Output: Now start the AVD in Emulator and run the App. You will see two ImageButton out of which
top one is round corner. Click on any image and its name will be displayed on screen.
Mobile Application Development 4.17 Designing User Interface with View

ToggleButton
In Android, ToggleButton is used to display checked and unchecked
OFF ON
state of a button. ToggleButton basically ON/OFF button with a light _f '
indicator which indicate the current state of toggle button.
A ToggleButton displays checked/unchecked states as a button. It is
basically an ON/OFF button with a light indicator.
The most simple example of ToggleButton is doing ON/OFF in sound,
Bluetooth, wifi, hotspot etc. It is a subclass of compoundButton. Fig. 4.4: ToggleButton
1. id: The id is an attribute used to uniquely identify a toggle button.
<ToggleButton
android: id="@+id/simpleToggleButton"
android: layout_width="wrap_content"
android: layout_height="wrap_content"/>
checked: The checked is an attribute of toggle button used to set the current state of a toggle button.
The value should be true or false where true shows the checked state and false shows unchecked
state of a toggle button. The default value of checked attribute is false. We can also set the current
state programmatically. Below we set true value for checked attribute sets the current state to
checked.
<ToggleButton
android: id="@+id/simpleToggleButton"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: checked="true" /><!-- set the current state of the toggle button-->
gravity: The gravity attribute is an optional attribute which is used to control the alignment of the
text in ToogleButton like left, right, center, top, bottom, center_vertical, center_horizontal etc.
<ToggleButton
android: id="@+id/simpleToggleButton"
android: layout_width="fill_parent”
android: layout_height="wrap_content”
android: layout_centerHorizontal="true"
android: checked="true"
android: gravity="right|center_vertical"/><!-- gravity of the toggle button-->
4. textOn and textOff: The textOn attribute is used to set the text when toggle button is in checked/on
state. We can set the textOn in XMLas well as in thejavaclass. Below is the example code with
explanation included in which we set the textOn “Enabble Attribute Of Toggle button” for a toggle
button.
<ToggleButton
android: id="@+id/simpleToggleButton"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: checked="true"
android: layout_centerHorizontal="true"
android: textOff="Disable"
android: textOn="Enable"/><!--text to be displayed whenever toggle button is checked->
textColor: The textColor attribute is used to set the text color of a toggle button. Color value is in the
form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”. Below we set the red color for the displayed text
of a Toggle button.
<ToggleButton
android: id="@+id/simpleToggleButton"
Mobile Application Development 4.18 Designing User Intertace with View
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: checked="false"
android: textOff="On State”
android: textOn="0ff State"
android: layout_centerHorizontal="true"
android: textColor="#f00" /><!--red color for displayed text-->
6. textSize: The textSize attribute set the size of the text of a toggle button. We can set the text size in
sp (scale independent pixel) or dp (density pixel). Below we set the 25sp size for the text of a toggle
button.
<ToggleButton
android: id="@+id/simpleToggleButton"
android: layout_width="wrap_content”
android: layout_height="wrap_content”
android: checked="false"
android: textOff="0n State"
android: textOn="0ff State"
android: layout_centerHorizontal="true"
android: textColor="#f80"
android: textSize="25sp"/><!-- 25sp displayed text size-->
7. textStyle: The textStyle attribute is used to set the text style of the text of a Toggle button. We can
set bold, italic and normal. If we need to use two or more styles for a text view then “|” operator is
used. Below we set the bold and italic text styles for text of a toggle button.
<TogegleButton
android: id="@+id/simpleToggleButton"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: checked="true"
android:textOff="Off State"
android:textOn="0n State"
android: textSize="25sp"
android: layout_centerHorizontal="true”
android: textColor="#f00"
android: textStyle="bold|italic"/><!--bold and italic text style for displayed text-->
8. background: The background attribute is used to set the background of a toggle button. We can set a
color or a drawable in the background of a toggle button. Below we set the black color for the
background and red color for the displayed text of a ToggleButton.
<ToggleButton
android: id="@+id/simpleToggleButton"
android: layout_width="wrap_content”
android: layout_height="wrap_content”
android: checked="true"
android: textOff="Off State"
android: textOn="0n State"
android: textSize="25sp"
android: layout_centerHorizontal="true"
android: textStyle="bold|italic"
android: textColor="#f80"
android: background="#@00"/><!--Black Color Background-->
9. padding: The padding attribute is used to set the padding from left, right, top or bottom.
e paddingRight: Set the padding from the right side of the toggle button.
e paddingLeft: Set the padding from the left side of the toggle button.
Mobile Application Development 4.19 Designing User Interface with View
« paddingTop: Set the padding from the top side of the toggle button.
* paddingBottom: Set the padding from the bottom side of the toggle button.
* Padding: Set the padding from the all side's of the toggle button.
Below we set the 40dp padding from all the side's of the toggle button.
<ToggleButton
android: id="@+id/simpleToggleButton"
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: checked="true"
android: textOff="Off State”
android: textOn="0n State”
android: textSize="25sp"
android: layout_centerHorizontal="true"
android: textColor="#f8e"
android: padding="4@dp"/><!--4@8dp padding from all the side's of toggle button-->
10. drawableBottom, drawableTop, drawableRight and drawableLeft: These attribute draw the
drawable below, top, right and left of the text of ToggleButton. Below we set the icon to the Top of the
text of a ToggleButton. In the similar way we can try for other three attribute ourself.
<!--Make sure to add ic_launcher image in drawable folder-->
<ToggleButton
android: id="@+id/simpleToggleButton"
android :layout_width="wrap_content”
android :layout_height="wrap_content"
android: checked="true"
android: textOff="0ff State”
android: textOn="On State"
android: layout_centerHorizontal="true"
android :textColor="#000"
android :drawableTop="@drawable/ic_launcher"/><!--drawable icon at the bottom of text
of top buttton-->
Example:
Step 1; Create a new project and name it ToggleButtonExample. In this step we create a new project for
ToggleButton in Android Studio by filling all the necessary details of the app like app name,
package name, api versions etc.
Select File + New — NewProject —> Fill the forms and click "Finish" button.
Step 2: Open res — layout — activity_main.Xml (or) main.xml and add following code. In this step we
open an xml file and add the code for displaying two toggle button and one normal Button.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android: layout_width="match_parent"
android: layout_height="match_parent"
android:orientation="vertical"
android: paddingBottom="@dimen/activity_vertical_margin"
android: paddingLeft="@dimen/activity_horizontal_margin"
android: paddingRight="@dimen/activity_horizontal_margin”
android: paddingTop="@dimen/activity_vertical_margin"
tools: context=".MainActivity">
<LinearLayout
android: layout_width="wrap_content"
android: layout_height="wrap_content”
Mobile Application Development 4.20 Designing User Interface with View
android: layout_gravity="center_horizontal"
android:orientation="horizontal">
<ToggleButton
android: id="@+id/simpleToggleButton1"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_gravity="center_horizontal"
android: checked="false"
android: drawablePadding="2@dp"
android: drawableRight="@drawable/ic_launcher
android: textColor="#600" />
<ToggleButton
android: id="@+id/simpleToggleButton2"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_gravity="center_horizontal"
android: layout_marginLeft="5@dp"
android: checked="true"
android: drawableLeft="@drawable/ic_launcher”
android: drawablePadding="2@dp"
android: textColor="#000" />
</LinearLayout>
<Button
android: id="@+id/submitButton"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_marginTop="5édp"
android: background="#@f0"
android: padding="1@dp”"
android: text="Submit"
android: textColor="#fff"
android: textSize="2@sp"
android: textStyle="bold"/>
</LinearLayout>
Step 3: Open app — java > package > MainActivity.java.
In this step we open MainActivity where we add the code to initiate the Toggle Buttons and normal
Button. After initiating we perform click event on button and display the text of current state of
ToggleButton using a Toast.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android. view.Menu;
import android. view.MenuItem;
import android. view. View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity{
ToggleButton simpleToggleButton1, simpleToggleButton2;
Button submit;
@Override
protected void onCreate(Bundle savedInstanceState){
Mobile Application Development 4.21 Designing User Intertace with View
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate toggle button's
simpleToggleButton1 =(ToggleButton) findViewById(R.id.simpleToggleButton1);
simpleToggleButton2 =(ToggleButton) findViewById(R.id.simpleToggleButton2);
submit =(Button) findViewById(R.id.submitButton);
submit. setOnClickListener(newView.OnClickListener(){
@Override
public void onClick(View view){
String status ="ToggleButtonl : "+ simpleToggleButton1. getText()+"\n"+"ToggleButton2 :
"+ simpleToggleButton2.getText();
Toast.makeText(getApplicationContext(), status, Toast.LENGTH_SHORT).show();// display the
current state of toggle button's
}
})3
}
}
Output: Now start the AVD in Emulator and run the App. You will see two ToggleButton and submit
Button. Click on the submit button which will display the state of ToggleButton.

Le ee ee)

[ZR4l RadioButton AND RadioGroup


A RadioButton has two states, either checked or unchecked. This allows the user to select one option
from a set. A RadioGroup class is used for set of radio buttons.
In Android, RadioButton are mainly used together in a RadioGroup. In RadioGroup checking the one
radio button out of several radio button added in it will automatically unchecked all the others.
It means at one time we can checked only one radio button from a group of radio buttons which
belong to same radio group.
RadioButton is a two state button that can be checked or unchecked. If a radio button is unchecked
then a user can check it by simply clicking on it.
Once, a RadioButton is checked by user it can not be unchecked by simply pressing on the same
button. It will automatically unchecked when we press any other RadioButton within same
RadioGroup.
Properties of RadioButton:
1. id: The id is an attribute used to uniquely identify a radio button.
<RadioButton
android: id="@+id/simpleRadioButton"
android: layout_width="wrap_content"
android: layout_height="wrap_content"/>
Mobile Application Development 4,22 Designing User Interface with View

2. checked: The checked attribute in radio button is used to set the current state of a radio button. We
can set it either true or false where true shows the checked state and false shows unchecked state of
a radio button. As usual default value of checked attribute is false. We can also set the current state
in Java. Below we set true value for checked attribute which sets the current state to checked of a
Button
<RadioButton
android: id="@+id/simpleRadioButton"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: checked="true"/><!-- set the current state of the radio button-->
gravity: The gravity attribute is an optional attribute which is used to control the alignment of text
like left, right, center, top, bottom, center_vertical, center_horizontal etc. Below is the example code
with explanation included in which we set the center gravity for the text of a radio button.
<RadioButton
android: id="@+id/simpleRadioButton"
android: layout_width="fill1_parent"
android: layout_height="wrap_content"
android: checked="true"
android: text="I am a Button"
android: gravity="center"/><!-- center gravity of the text-->
textColor: The textColor attribute is used to set the text color of a radio button. Color value is in the
form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”. Below we set the red color for the displayed text
of a radio button.
<RadioButton
android: id="@+id/simpleRadioButton"
android: layout_width="wrap_content”
android: layout_height="wrap_content”
android: checked="true"
android: layout_centerHorizontal="true"
android: text="Male"
android: textColor="#f60" /><!--red color for displayed text-->
Setting textColor of RadioButton text In Java Class: Below we set the text color of a radio button
programmatically.
/*Add in Oncreate() funtion after setContentView()*/
RadioButton simpleRadioButton = (RadioButton) findViewById(R.id.simpleRadioButton);
// initiate radio button
simpleRadioButton.setTextColor(Color.RED); //red color for displayed text of radio button
textSize: The textSize attribute is used to set the size of the text of a radio button. We can set the text
size in sp (scale independent pixel) or dp (density pixel). Below we set the 25sp size for the text ofa
radio button.
<RadioButton
android: id="@+id/simpleRadioButton"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: checked="true"
android: layout_centerHorizontal="true"
android: text="AbhiAndroid"
android: textColor="#f80"
android: textSize="25sp"/><!--setting text size-->
Mobile Application Development 4.23 Designing User Interface with View

6. textStyle: The textStyle attribute is used to set the text style of the text of a radio button. The possible
text styles are bold, italic and normal. If we need to use two or more styles for a text view then “|”
operator is used. Below is the example code with explanation included in which we set the bold and
italic text styles for text of a radio button.
<RadioButton
android: id="@+id/simpleRadioButton"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: checked="true"
android: textSize="25sp"
android: layout_centerHorizontal="true"
android: text="Male"
android: textColor="#f@0"
android: textStyle="bold|italic"/><!-- bold and italic text style-->
7. background: The background attribute is used to set the background of a radio button. We can set a
color or a drawable in the background of a radio button. Below we set the black color for the
background and red color for the displayed text of a radio button.
<RadioButton
android: id="@+id/simpleRadioButton”
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: checked="true"
android: textSize="25sp"
android: textStyle="bold|italic"
android: padding="2@dp"
android: layout_centerHorizontal="true"
android: text="Male"
android: textColor="#f80"
android: background="#006"/><!-- black background for radio button-->
Setting Background of RadioButton in Java Class: Below we set the background color of a radio
button programmatically.
/*Add in Oncreate() funtion after setContentView()*/
RadioButton simpleRadioButton = (RadioButton) findViewById(R.id.simpleRadioButton);
simpleRadioButton. setBackgroundColor(Color. BLACK) ;
8. padding: The padding attribute is used to set the padding from left, right, top or bottom.
« paddingRight: Set the padding from the right side of the radio button.
* paddingLeft : Set the padding from the left side of the radio button.
e paddingTop : Set the padding from the top side of the radio button.
e paddingBottom: Set the padding from the bottom side of the radio button.
« Padding: Set the padding from the all side’s of the radio button.
Below we set padding attribute of 20dp padding from all the side’s of the radio button.
<RadioButton
android: id="@+id/simpleRadioButton"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: checked="true"
Mobile Application Development 4.24 Designing User Interface with View
android: textSize="25sp"
android: textStyle="bold|italic"
android: layout_centerHorizontal="true"
android: text="AbhiAndroid"
android: textColor="#f80"
android: padding="2@dp"/><!--2@dp padding from all the sides of radio button-->
9. drawableBottom, drawableTop, drawableLeft and drawableRight: These attribute draw the
drawable to the below of the text of RadioButton. Below we set the icon to the right of the text ofa
RadioButton.
<RadioButton
android: id="@+id/simpleRadioButton"
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: checked="true"
android: textSize="25sp"
android: padding="2@dp"
android: layout_centerHorizontal="true"
android:text="AbhiAndroid"
android: textColor="#fe0"
android: drawableRight="@drawable/ic_launcher" /><!-- drawable icon at the right of
radio button-->
Example: In activity_main.xml add the following code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android: layout_width="fill_parent"
android: layout_height="fill_parent"
android:orientation="vertical" >
<RadioGroup
android: id="@+id/radioSex"
android: layout_width="wrap_content"
android: layout_height="wrap_content" >
<RadioButton
android: id="@+id/radioMale”
android: layout_width="wrap_content”
android: layout_height="wrap_content”
android: text="@string/radio_male"
android: checked="true" />
<RadioButton
android: id="@+id/radioFemale"
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: text="@string/radio_female" />
</RadioGroup>
<Button
android: id="@+id/btnDisplay”
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: text="@string/btn_display" />
</LinearLayout>
Mobile Application Development 4.25 Designing User Interface with View

Inside activity “onCreate()” method, attach a click listener on button.


File : MyAndroidAppActivity.java
import android.app.Activity;
import android.os.Bundle;
import android. view. View;
import android. view. View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget .RadioGroup;
import android.widget.Toast;
public class MyAndroidAppActivity extends Activity {
private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
private Button btnDisplay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R. layout.main) ;
addListenerOnButton();
}
public void addListenerOnButton() {
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
@0verride
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId{);
// find the radiobutton by returned id
radioSexButton = (RadioButton) findViewById(selectedId);
Toast .makeText(MyAndroidAppActivity.this,
radioSexButton.getText(), Toast.LENGTH_SHORT).show();

be)

foe
Female
Mobile Application Development 4.26 Designing User Intertace with View

Wy | CheckBox
ACheckBox is an ON/OFF switch that can be toggled by the user. A two-state button represented by a
checked or unchecked box.
o Likea Swing JCkeckBox
o Example taken from Visual Guide to Android GUI widgets.
o Inherits all of TextView attributes and Button attributes.
id: The id is an attribute used to uniquely identify a check box. Below we set the id of a image button.
<CheckBox
android: id="@+id/simpleCheckBox”
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android:text="Simple CheckBox"/>
checked: The checked is an attribute of check box used to set the current state of a check box. The
value should be true or false where true shows the checked state and false shows unchecked state of
a check box. The default value of checked attribute is false. We can also set the current state
programmatically. Below is an example code in which we set true value for checked attribute that
sets the current state to checked.
<CheckBox
android: id="@+id/simpleCheckBox"
android: layout_width="wrap_content”
android: layout_height="wrap_content”
android:text="Simple CheckBox"
android: checked="true"/><|--set the current state of the check box-->
Setting Current State of CheckBox in Java Class: Below we set the current state of CheckBox
in java class.
/*Add in Oncreate() funtion after setContentView()*/ // initiate a check box
CheckBox simpleCheckBox = (CheckBox) findViewById(R.id.simpleCheckBox);
// set the current state of a check box
simpleCheckBox. setChecked(true) ;
gravity: The gravity attribute is an optional attribute which is used to control the alignment of the
text in CheckBox like left, right, center, top, bottom, center_vertical, center_horizontal etc. Below we
set the right and center_vertical gravity for the text of a check box.
<CheckBox
android: id="@+id/simpleCheckBox"
android: layout_width="f111_parent"
android: layout_height="wrap_content"
android: text="Simple CheckBox"
android: checked="true”
android: gravity="right|center_vertical"/><!-- gravity of the check box-->
text: The text attribute is used to set the text in a CheckBox. We can set the text in xmlas well as in
the java class. Below is the example code with explanation included in which we set the text “Text
Attribute Of Check Box” for a check box.
<CheckBox
android: id="@+id/simpleCheckBox”
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: checked="true"
android: text="Text Attribute Of Check Box"/><!--displayed text of the check box-->
Mobile Application Development 4,27 Designing User Interface with View

Setting text in CheckBox in Java Class: Below is the example code in which we set the text of a check
box programmatically means in java class.
/*Add in Oncreate() funtion after setContentView()*/
// initiate check box
CheckBox simpleCheckBox = (CheckBox) findViewById(R.id.simpleCheckBox);
// displayed text of the check box
simpleCheckBox.setText("Text Attribute Of Check Box");
5. textColor: The textColor attribute is used to set the text color of a check box. Color value is in form of
ow
“#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”. Below we set the red color for the displayed text of a
check box.
<CheckBox
android: id="@+id/simpleCheckBox"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android:text="Text is Red Color”
android: textColor="#f8e"
android: checked="true"/><!-- red color for the text of check box-->
Setting textColor in CheckBox in Java Class: Below we set the text color of a check box
programmatically.
/*Add in Oncreate() funtion after setContentView()*/
//initiate the checkbox
CheckBox simpleCheckBox = (CheckBox) findViewById(R.id.simpleCheckBox);
//red color for displayed text
simpleCheckBox. setTextColor(Color.RED);
6. textSize: The textSize attribute is used to set the size of text of a check box. We can set the text size in
sp (scale independent pixel) or dp (density pixel), Below is the example code in which we set the 20sp
size for the text of a check box.
<CheckBox
android: id="@+id/simpleCheckBox"
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android:text="Text size Attribute Of Check Box"
android: textColor="#00f"
android: checked="false"
android: textSize="2@sp"/><!--set Text Size of text in CheckBox-->
Setting Text Size in CheckBox In Java Class: Below we set the text size of a check box in java class.
/*Add in Oncreate() funtion after setContentView()*/
CheckBox simpleCheckBox = (CheckBox) findViewById(R.id.simpleCheckBox);
//set 2@sp displayed text size
simpleCheckBox. setTextSize(20);
7. textStyle: The textStyle attribute is used to set the text style of the text of a check box. The possible
text styles are bold, italic and normal. If we need to use two or more styles for a text view then “|”
operator is used for that. Below we set the bold and italic text styles for text of a check box.
<CheckBox
android: id="@+id/simpleCheckBox"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: text="Text Style Attribute Of Check Box"
Mobile Application Development 4.28 Designing User Interface with View
android: textColor="#44f"
android: textSize="2@sp"
android: checked="false"
background: The background attribute is used to set the background of a check box. We can set a
color or a drawable in the background of a check box. Below we set the black color for the
background, white color for the displayed text of a check box.
<CheckBox
android: id="@+id/simpleCheckBox"
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android:text="Text size Attribute Of Check Box”
android: textColor="#fff"
android: textSize="2@sp"
android: textStyle="bold|italic"
android: checked="true"
android: background="#0@6" /><!-- black background for the background of check box-->
android: textStyle="bold|italic"/>
Setting Background in CheckBox in Java Class: Below is the example code in which we set the
background color of a check box programmatically means in java class.
/*Add in Oncreate() funtion after setContentView()*/
CheckBox simpleCheckBox = (CheckBox) findViewById(R.id.simpleCheckBox) ;
// set background in CheckBox
simpleCheckBox. setBackgroundColor(Color.BLACK);
9. padding: The padding attribute is used to set the padding from left, right, top or bottom.
paddingRight: Set the padding from the right side of the check box.
0

paddingLeft: Set the padding from the left side of the check box.
Go

paddingTop: Set the padding from the top side of the check box.
0

paddingBottom: Set the padding from the bottom side of the check box.
o

Padding: Set the padding from the all side’s of the check box.
o

Below is the example code of padding where we set the 30dp padding from all the side's of the check
box.
<CheckBox
android: id="@+id/simpleCheckBox"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: text="Padding Attribute Of Check Box"
android: textColor="#44f"
android: textSize="2@sp"
android: textStyle="bold|italic"
android: checked="false”
android: padding="3@dp"/><!--3@dp padding from all side’s-->
In XML file add following code:
<?xml version="1.8" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android: layout_width="fill_parent"
android: layout_height="fill_parent”
android:orientation="vertical"” >
<CheckBox
android: id="@+id/chkIos"
Mobile Application Development 4.29 Designing User Interface with View

android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: text="@string/chk_ios” />
<CheckBox
android: id="@+id/chkAndroid”
android: layout_width="wrap_content”
android: layout_height="wrap_content”
android: text="@string/chk_android”
android: checked="true" />
<CheckBox
android: id="@+id/chkWindows”
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: text="@string/chk_windows" />
<Button
android: id="@+id/btnDisplay"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: text="@string/btn_display" />
</LinearLayout>
In java file add following
code:
import android.app.Activity;
import android.os.Bundle;
import android. view. View;
import android. view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MyAndroidAppActivity extends Activity{
private CheckBox chkIos, chkAndroid, chkWindows;
private Button btnDisplay;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.
layout .main);
addListenerOnChkIos();
addListenerOnButton();
}
public void addListenerOnChkIos(){
chkIos =(CheckBox)findViewById(R.id.chkIos);
chkIos .setOnClickListener(newOnClickListener(){
@Override
public void onClick(View v){
/fis chkIos checked?
if(((CheckBox) v).isChecked()){
Toast .makeText(MyAndroidAppActivity.this,
"Bro, try Android :)", Toast.LENGTH_LONG).show();

});
Mobile Application Development 430 Designing User Interface with View

}
public void addListenerOnButton(
){
chkIos =(CheckBox)findViewById(R.id.chkIos);
chkAndroid =(CheckBox)findViewById(R.id.chkAndroid);
chkWindows =(CheckBox)findViewById(R.id.chkWindows);
btnDisplay =(Button)findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(newOnClickListener(){
//Run when button is clicked
@Override
public void onClick(View v){
StringBuffer result =newStringBuffer(
);
result.append("IPhone check : “).append(chkIos.isChecked());
result.append("\nAndroid check : ").append(chkAndroid.isChecked());
result.append("\nWindows Mobile check :").append(chkWindows.isChecked());
Toast.makeText (MyAndroidAppActivity.this, result.toString(),
Toast. LENGTH_LONG) .show();

See
a
aaa
vile
Lae i)
Android
MA el esac)
Windows Mobile }

a ete ea
ens ge
ee Calon gg

Ex] ProgressBar
ProgressBar is used to show the progress of an operation. ProgressBar is a Visual indicator of
progress in a number of operation.
Display a bar to the user representing how far the operation has progressed; the application can
change the amount of progress as it move forward.
There is also secondary progress display on a progress bar which is useful for displaying
intermediate progress, such as the buffer level during a stream playback progress bar.
Progress bars are used to show progress of a task. For example, when we are uploading or
downloading something from the internet, it is better to show the progress of download/upload to
the user.
In android there is a class called ProgressDialog that allows us to create progress bar.
Propertiesof Progress Bar:
1. id: The id is an attribute used to uniquely identify a Progress bar.
<ProgressBar
android: id="@+id/simpleProgressBar”
Mobile Application Development 431 Designing User Interface with View

android: layout_width="fill_parent"
android: layout_height="wrap_content"
style="@style/Widget .AppCompat.ProgressBar.Horizontal"/>
2. max: The max is an attribute used in android to define maximum value of the progress can take. It
must be an integer value like 100, 200 etc. Below we set 100 maximum value for a progress bar.
<ProgressBar
android: id="@+id/simpleProgressBar"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
style="@style/Widget .AppCompat. ProgressBar .Horizontal”
android:max="100"/><!--set 10@ maximum value for the progress bar-->
progress: The progress is an attribute used in android to define the default progress value between 0
and max. It must be an integer value. Below we set the 100 max value and then set 50 default
progress.
<ProgressBar
android: id="@+id/simpleProgressBar"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: max="160"
style="@style/Widget .AppCompat .ProgressBar.Horizontal”
android: progress="50"/><!--// 5@ default progress value-->
4, progressDrawable: The progress Drawable is an attribute used in Android to set the custom
drawable for the progress mode. Below we set a custom gradient drawable for the progress mode of a
progress bar. Before we try below code make sure to download a progress icon from the web and add
in the drawable folder.
Step 1: Add this code in activity_main.Xml or main.xml inside layout.
<ProgressBar
android: id="@+id/simpleProgressBar"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android:max="100"
android: progress="60"
android: layout_marginTop="10@dp"
style="@style/Widget .AppCompat.ProgressBar.Horizontal"”
android: progressDrawable="@drawable/custom_progress"/><!--custom progress drawable
for progress mode-->
Step 2: Create a new drawable resource xml in drawable folder and name it custom_progress. Here add
the below code which creates gradient effect in ProgressBar.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape>
<gradient
android: endColor="#fff"
android: startColor="#1f1"
android:useLevel="true" />
</shape>
</item>
</layer-list>
Mobile Application Development 4,32 Designing User Interface with View

5. background: The background attribute is used to set the background of a Progress bar. We can set a
color or a drawable in the background of a Progress bar. Below we set the black color for the
background of a progress bar.
<ProgressBar
android: id="@+id/simpleProgressBar"
android: layout_width="fill_parent"
android: layout_height="wrap_content"™
android: max="100"
android: progress="50"
style="@style/Widget .AppCompat.ProgressBar.Horizontal”
android: background="#0@6"/><!-- black background color for progress bar-->
indeterminate: The indeterminate attribute is used in Android to enable the indeterminate mode. In
this mode a progress bar shows a cyclic animation without an indication of progress. This mode is
used in application when we don’t know the amount of work to be done. In this mode the actual
working will not be shown. In below code we set the indeterminate to true.
<ProgressBar
android: id="@+id/simpleProgressBar"
android: layout_width="fill_parent”
android: layout_height="wrap_content"
android: max="100"
android: progress="50"
android: background="#000"
android: padding="2@dp" style="@style/Widget .AppCompat .ProgressBar.Horizontal"
android: indeterminate="true"/><!--true value for indeterminate-->
7. padding: The padding attribute is used to set the padding from left, right, top or bottom of
ProgressBar.
o paddingRight: Set the padding from the right side of the Progress bar.
paddingLeft: Set the padding from the left side of the Progress bar.
0

paddingTop: Set the padding from the top side of the Progress bar.
0

paddingBottom: Set the padding from the bottom side of the Progress bar.
oo

Padding: Set the padding from the all side's of the Progress bar.
Below we set the 20dp padding from all the side’s of the Progress bar.
<ProgressBar
android: id="@+id/simpleProgressBar”
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: max="1@0"
android: progress="50"
android: background="#000"
style="@style/Widget .AppCompat.ProgressBar.Horizontal"
android: padding="2@dp"/><!--//2@dp padding from all the sides of the progress bar-->
In activity_main.xml (or) main.xml and add following code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android”
xmlns:tools="http://schemas.android.com/tools"
android: layout_width="match_parent"™
android: layout_height="match_parent"
android: background="#060"
android: paddingBottom="@dimen/activity_vertical_margin"
android: paddingLeft="@dimen/activity_horizontal_margin"
Mobile Application Development 4.33 Designing User Interface with View
android: paddingRight="@dimen/activity_horizontal_margin"
android: paddingTop="@dimen/activity_vertical_margin"
tools: context=".MainActivity">
<ProgressBar
android: id="@+id/simpleProgressBar"
style="@style/Widget .AppCompat.ProgressBar.Horizontal"
android: layout_width="fill_parent”
android: layout_height="wrap_content”
android: layout_centerHorizontal="true"
android: layout_marginTop="7@dp"
android :max="100"
android: progress="0"
android: progressDrawable="@drawable/custom_progress"/>
<Button
android: id="@+id/startButton"
android: layout_width="200dp"
android: layout_height="wrap_content"
android: layout_centerHorizontal="true”
android: layout_marginTop="120dp"
android: background="#0f6"
android: padding="1@dp"
android:text="Start"
android: textColor="#f ff"
android:textSize="2@sp"
android: textStyle="bold"/>
</RelativeLayout>
Create an xml file in drawable — custom_progress.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-listxmlns:android="http: //schemas.android.com/apk/res/android” >
<item>
<shape>
<gradient
android: endColor="#fff"
android: startColor="#1f1"
android: useLevel="true"/>
</shape>
</item>
</layer-list>
MainActivity.java
import android. app.Dialog;
import android. content.Dialoginterface;
import android. content.Intent;
import android. graphics.Color;
import android. provider.Settings;
import android. support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android. view.Menu;
import android. view.MenuItem;
import android. view.View;
Mobile Application Development 4.34 Designing User Intertace with View
import android.widget.ProgressBar;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
int progress =6;
ProgressBar simpleProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState){
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate progress bar and start button
simpleProgressBar =(ProgressBar) findViewById(R.id.simpleProgressBar);
Button startButton =(Button) findViewById(R.id.startButton);
// perform click event on button
startButton. setOnClickListener(newView.OnClickListener(){
@Override
public void onClick(View v){
// call a function
setProgressValue(progress);
}
})3
}
private void setProgressValue(finalint progress){
// set the progress
simpleProgressBar.setProgress(progress);
// thread is used to change the progress value
Thread thread =newThread(newRunnable(
){
@0verride
public void run(){
try{
Thread. sleep(1000) ;
}catch(InterruptedException e){
e.printStackTrace();
}
setProgressValue(progress +18);
}
})3
thread.start();
}
@0verride
public boolean onCreateOptionsMenu(Menu menu){
/{ Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;

}
@Override
public boolean onOptionsItemSelected(MenuItem item){
// Handle action bar item clicks here. The action bar will
/{ automatically handle clicks on the Home/Up button, so long
// as we specify a parent activity in AndroidManifest.xml.
Mobile Application Development 4,35 Designing User Interface with View

int id = item.getItemId();
//no inspection SimplifiableIfStatement
if(id == R.id.action_settings){
return true;

}
return super.onOptionsItemSelected(item);
}
}
Output:

EE] ustview
ListView displays a vertically-scrollable collection of views, where each view is positioned
immediately below the previous view in the list.
A View Group that creates and manages a vertical list of Views, display them as rows within the list.
The simplest List View displays to the String value of each object in an array, use a Text View for each
item.
Android ListView is a view which groups several items and display them in vertical scrollable list.
The list items are automatically inserted to the list using an Adapter that pulls content from a source
such as an array or database.
Android ListView is a view which groups several items and display them in vertical scrollable list.
The list items are automatically inserted to the list using an Adapter that pulls content from a source
such as an array or database.
Properties of ListView:
1. id: The id is used to uniquely identify a ListView. Below is the id attribute's example code with
explanation included.
<!-- id of a list view uniquely identify it-->
<ListView
android: id="@+id/simpleListView"
android: layout_width="fill_parent”
android: layout_height="wrap_content"/>
divider: This is a drawable or color to draw between different list items. Below is the divider example
code with explanation included, where we draw red color divider between different views.
<!--Divider code in ListView-->
<ListView
android: id="@+id/simpleListView"
Mobile Application Development 4.36 Designing User Interface with View

android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: divider="#f@0"
android: dividerHeight="1dp"/>
3. dividerHeight: This specify the height of the divider between list items. This could be in dp (density
pixel), sp (scale independent pixel) or px (pixel). In above example of divider we also set the divider
height 1dp between the list items. The height should be in dp, sp or px.
listSelector: The listSelector property is used to set the selector of the listView. It is generally orange
or Sky blue color mostly but we can also define our custom color or an image as a list selector as per
our design. Below is listSelector example code with explanation includes, where list selector color is
green, when we select any list item then that item's background color is green.
<l-- List Selector Code in ListView -->
<ListView
android: id="@+id/simpleListView"
android: layout_width="fill_parent”
android: layout_height="wrap_content"
android: divider="#f@0"
android: dividerHeight="1dp"
android: listSelector="#0f@"/><!--list selector in green color-->
Adapters Use in ListView:
Anadapteris a bridge between UI component and data source that helps us to fill data in UI
component.
It holds the data and send the data to adapter view then view can takes the data from the adapter
view and shows the data on different views like as list view, grid view, spinner etc.
ListView is a subclass of AdapterView and it can be populated by binding to an Adapter, which
retrieves the data from an external source and creates a View that represents each data entry.
In android commonly used adapters are ArrayAdapter and BaseAdapter.
ArrayAdapter:
Whenever we have a list of single items which is backed by an array, we can use ArrayAdapter. For
instance, list of phone contacts, countries or names.
By default, ArrayAdapter expects a Layout with a single TextView. If we want to use more complex
views means more customization in list items, please avoid ArrayAdapter and use custom adapters.
The ArrayAdapter code is:
ArrayAdapter adapter = new
ArrayAdapter<String>(this,R.layout.ListView,R.id.textView,
StringArray) ;
Example of list view using ArrayAdapter: activity_main.xml or content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android: layout_width="match_parent”
android: layout_height="match_parent"
android:orientation="vertical">
<ListView
android: id="@+id/simpleListView"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: divider="@color/material_blue_grey_800"
android: dividerHeight="1dp"/>
</LinearLayout>
Mobile Application Development 4,37 Designing User Interface with View

Create a new activity name Listview and below is the code of activity_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http: //schemas.android.com/apk/res/android"
android: layout_width="match_parent"
android: layout_height="match_parent"
android:orientation="vertical">
<TextView
android: id="@+id/textView"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: padding="@dimen/activity_horizontal_margin"
android:textColor="@color/black"/>
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;import android.widget.ListView;
public class MainActivity extends Activity
{
// Array of strings...
ListView simpleList;
String countryList[]={"India", "China", "australia", “Portugle", "America", "NewZealand"};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList =(ListView)findViewById(R.id.simpleListView);
ArrayAdapter<String> arrayAdapter =newArrayAdapter<String>(this,
R.layout.activity_listview, R.id.textView, countryList);
simpleList.setAdapter(arrayAdapter);

2. BaseAdapter:
BaseAdapter is a common base class of a general implementation of an Adapter that can be used in
ListView. Whenever, we need a customized list we create our own adapter and extend base adapter in
that.
¢ BaseAdapter can be extended to create a custom Adapter for displaying a custom list item.
ArrayAdapter is also an implementation of BaseAdapter.
Mobile Application Development 4.38 Designing User Interface with View
Example of list view using Custom adapter (BaseAdapter): Below is the code of activity_main.xml
or content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android: layout_width="match_parent”
android: layout_height="match_parent"
android:orientation="vertical”">
<ListView
android: id="@+id/simpleListView"
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: divider="@color/material_blue_grey_800"
android: dividerHeight="1dp"
android: footerDividersEnabled="false"/>
</LinearLayout>
Create a new activity name Listview and below is the code of activity_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http: //schemas.android.com/apk/res/android"
android: layout_width="match_parent”™
android: layout_height="match_parent”
android:orientation="horizontal">
<ImageView
android: id="@+id/icon"
android: layout_width="56dp"
android: layout_height="5édp"
android: src="@drawable/ic_launcher"/>
<TextView
android: id="@+id/textView"
android: layout_width="fill_parent”
android: layout_height="wrap_content"
android: layout_gravity="center"
android: padding="@dimen/activity_horizontal_margin"
android: textColor="@color/black"/>
</LinearLayout>
Below is the code of MainActivity.java:
import android. app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends Activity{
ListView simpleList;
String countryList[]={"India","China", "australia", "Portugle","America","NewZealand"};
int flags[]={R.drawable.india, R.drawable.china, R.drawable.australia,
R.drawable.portugle, R.drawable.america, R.drawable.new_zealand};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SimpleList =(ListView) findViewById(R.id.simpleListView);
CustomAdapter customAdapter=newCustomAdapter (getApplicationContext(),countryList, flags);
simpleList.setAdapter(customAdapter);
}
}
Mobile Application Development 4,39 Designing User Interface with View

Now create another class Custom Adapter which will extend BaseAdapter. Below is the code of
CustomAdapter.java:
import android. content.Context;
import android.media. Image;
import android. view. LayoutInflater;
import android. view. View;
import android. view. ViewGroup;
import android.widget.BaseAdapter;
import android.widget .ImageView;
import android.widget.TextView;
import java.util.zip.Inflater;
public class CustomAdapter extends BaseAdapter{
Context context;
String countryList[];
int flags[];
LayoutInflater inflter;
public CustomAdapter(Context applicationContext,String[] countryList,int[] flags){
this.context = context;
this.countryList = countryList;
this.flags = flags;
inflter =(LayoutInflater.from(applicationContext)
);
}
@Override
public int getCount(){
return countryList. length;
}
@Override
public object getItem(int i){
return null;
}
@Override
public long getItemId(int i){
return@;
}
@Override
public View getView(int i,View view,ViewGroup viewGroup){
view = inflter.inflate(R.layout.activity_listview,null);
TextView country =(TextView) view. findViewById(R.id.textView);
ImageView icon =(ImageView) view. findViewById(R.id.icon);
country.setText(countryList[i]);
icon.setImageResource(flags[i]);
return view;
}
Output:
Mobile Application Development 4.40 Designing User Interface with View

Cai GridView
Android GridView shows items in two-dimensional scrolling grid (rows and columns) and the grid
items are not necessarily predetermined but they automatically inserted to the layout using
a ListAdapter.
GridView will fill the entire screen. Android has a GridView control that can display data in the form
of a grid. Although we use the term data here, the content of the grid can be text, images, and so on.
GridView is default scrollable so we don't need to use ScrollView or anything else with GridView.
GridView is widely used in android applications. An example of GridView is our default Gallery,
where we have number of images displayed using grid.
Normal GridView example, display characters from A to Z in GridView layout. Quite simple, it should
be self-explanatory.
Example: Android Layout file - res/layout/main.xml.
<?xml version="1.6" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android: id="@+id/gridView1"
android: numColumns="auto_fit"
android: gravity="center"
android: columnWidth="5@dp"
android: stretchMode="columnWidth"
android: layout_width="fill_parent"
android: layout_height="fill_parent” >
</GridView>
Activity:
import android. app.Activity;
import android.os.Bundle;
import android.widget .AdapterView;
import android.widget .ArrayAdapter ;
import android.widget .GridView;
import android.widget.TextView;
import android.widget.Toast;
import android. view. View;
import android.widget .AdapterView.OnItemClickListener;
public class GridViewActivity extends Activity{
GridView gridView;
static final String[] numbers =newString[]{
"a" ,"B","C","D","E",
"FG", "H", "I", "3",
"Kn, "L""M","N", "0",
"P","Q","R","S","T",
"UN "VN "WS "X", MY", "Z"}5
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView =(GridView) findViewById(R.id.gridView1) ;
ArrayAdapter<String> adapter=newArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);
gridView. setOnItemClickListener(newOnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position,long id){
Toast.makeText (getApplicationContext(),
((TextView) v).getText(), Toast.LENGTH_SHORT) .show();
Mobile Application Development 441 Designing User Intertace with View
}

a gviee
In android, we can use “android.widget.ImageView” class to display an image file. Image file is
simple to use but hard to master, because of the various screens and dpi in Android devices. Android
will find the image automatically.
1. Add Image to Resources:
« Put our images into folder “res/drawable-ldpi",aoa “res/drawable-mdpi" or “res/drawable-hdpi“.
e In Fig. 4.5 no matter which folder we put, Android will find the image automatically. In this case,
both “android.png” and “android3d.png” images are used for demonstration.
\& MyAndroidApp .
Ss astats 3.Jin WVGA (Neuss One) + [Portrait ~|
& bin :
& gen [Generated Java ites] 4) Palette ¥ me) fi | fa & -|
} 3 Form Widgets
| Text Flelds

{@ Reterence Chooser
Choose
a resource

andro
android
it launcher

Fig. 4.5
2. Add ImageView:
* Open “res/layout/main.xml” file, just add anImageViewand Button for demonstration. By
default, imageView1 will display “android.png”.
<?xml version="1.6" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android: layout_width="fill_parent”
android: layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android: id="@+id/imageView1"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
Mobile Application Development 4.42 Designing User Interface with View
android:src="@drawable/android"/>
<Button
android: id="@+id/btnChangeImage"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android:text="Change Image"/>
</LinearLayout>
. Code:
* Simple, when button is clicked, change it to “android3d.png”.
MyAndroidAppActivity.
java
package com.mkyong.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android. view. View;
import android. view. View.OnClickListener;
public class MyAndroidAppActivity extends Activity {
Button button;
ImageView image;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R. layout.main) ;
addListenerOnButton(
);
}
public void addListenerOnButton(){
image =(ImageView)findViewById(R.id.imageView1);
button =(Button)findViewById(R.id.btnChangeImage);
button.setOnClickListener(new OnClickListener(){
@Override
publicvoidonClick(View arg@){
image . set ImageResource(R.drawable.android3d);
}
})3

}
Output:

Change Image
Mobile Application Development 443 Designing User Interface with View

2. Click on the button, image will changed to “android3d.png”.

‘evi ScrollView
A view group that allows the view hierarchy placed within it to be scrolled. ScrollView may have only
one direct child placed within it. ScrollView supports vertical scrolling only. For horizontal scrolling,
use HorizontalScrollView
A ScrollView is a FrameLayout which put one child in it containing the whole contents to scroll; this
child may itself be a layout manager with a composite hierarchy of object.
ScrollView is a control for development a View container with a vertical scrollbar. This is useful
when we have too much to fit onto a single screen.
Properties of ScrollView:
1. Add states from children: Sets whether this ViewGroup’s drawable states also include its children’s
drawable states.
2. Always drawn with cache: Defines whether the ViewGroup should always draw its children using
their drawing cache or not.
3. Animate layout changes: Defines whether changes in layout should cause a LayoutTransition to
run.
4. Animation cache: Defines whether layout animations should create a drawing cache for their
children.
5. Clipchildren: Defines whether a child is limited to draw inside of its bounds or not.
6. Id: Supplies an identifiers name of this view, to later retrieve it with View.findViewByld() or
Activity.findViewByld().
Example:
Step 1; Create a new project in Android Studio and name it scrollviewExample.
Select File - New — New Project — Android Application Project (or) Android Project. Fill the
forms and click “Finish” button.
Step 2: Open res > layout — activity_main.xml (or) main.xml and add below code. Here we are creating
a RelativeLayout having 10 buttons which are nested in LinearLayout and then in ScrollView.
Note: Remember ScrollView can hold only one direct child. So we have to jointly put 10 buttons
inside LinearLayout to make it one child. And then we put it inside ScrollView.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools”
android: layout_width="match_parent”
android: layout_height="match_parent"
tools: context=".MainActivity">
<ScrollView
android: layout_width="fill_parent"
android: layout_height="fill_parent"
android: scrollbars="vertical">
Mobile Application Development 444 Designing User Interface with View

<LinearLayout
android: layout_width="fill_parent"
android: layout_height="fill_parent"
android: layout_margin="2@dp"
android:orientation="vertical">
<Button
android: layout_width="fill_parent"
android: layout_height="wrap_content”
android: layout_gravity="center"
android: background="#f@0"
android:text="Button 1”
android:textColor="#fff"
android:textSize="2@sp" />
<Button
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_marginTop="20dp"
android: background="#0f8"
android:text="Button 2"
android: textColor="#fff"
android:textSize="20sp" />
<Button
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_marginTop="2@dp"
android: background="#00fT"
android:text="Button 3"
android: textColor="#fff"
android: textSize="20sp" />
<Button
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_marginTop="20dp"
android: background="#ff8"
android:text="Button 4"
android: textColor="#f ff"
android:textSize="20sp" />
<Button
android: layout_width="fill_parent"
android: layout_height="wrap_content”
android: layout_gravity="center"
android: layout_marginTop="2@dp"
android: background="#f@f"
android:text="Button 5"
android: textColor="#fff"
android:textSize="2@sp" />
<Button
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_marginTop="2@dp"
Mobile Application Development 445 Designing User Interface with View

android: background="#f96"
android:text="Button 6”
android:textColor="#fff"
android:textSize="20sp" />
<Button
android: layout_width="fill_parent"
android: layout_height="wrap_content”
android: layout_gravity="center"
android: layout_marginTop="2@dp"
android: background="#f@0"
android:text="Button 7"
android: textColor="#ff9"
android:textSize="20sp" />
<Button
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_marginTop="20dp"
android: background="#444"
android:text="Button 8"
android: textColor="#f ff"
android:textSize="2@sp" />
<Button
android: layout_width="fill_parent”
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_marginTop="2@dp"
android: background="#ff002211"
android:text="Button 9"
android: textColor="#fff"
android:textSize="20sp" />
<Button
android: layout_width="fill_parent"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_marginTop="20dp"
android: background="#0f6"
android:text="Button 10"
android: textColor="#fff"
android:textSize="20sp" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Step 3: Now Open src > package > MainActivity.java and paste the below code:
package com.example. gourav.scrollviewExample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R. layout.activity_main) ;
}
}
Mobile Application Development 4.46 Designing User Interface with View

Step 4: Now open manifest.xml and paste the below code:


<?xml version="1.6" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gourav.scrollviewExample">
<application
android: allowBackup="true"
android: icon="@mipmap/ic_launcher
android: label="@string/app_name"
android: theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android: label="@string/app_name”™>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.
intent. category.LAUNCHER"/>
</intent-filter>
<factivity>
<fapplication>
</manifest>
Step 5: Lastly open res > values — strings.xml and paste the below code:
<resources>
<stringname="app_name">ScrollViewExample</string>
<stringname="hello_world">Hello world!</string>
<stringname="action_settings">Settings</string>
</resources>
Output:

Pe)

Cate) 7

amie id

BUTTON 8

gt]

Example: In this example we will scroll the buttons in horizontal direction. Below is the complete
code and final output:
Step 1: Create a new project and name it HorizontalScrollViewExample.
Select File + New — New Project and Fill the forms and click “Finish” button.
Step 2: Now open res — layout — activity_mail.xml (or) main.xml and add below code. Here, we are
creating same buttons in HorizontalScrollView.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools”
android: layout_width="match_parent"
android: layout_height="match_parent"
tools: context=".MainActivity">
<HorizontalScrollView
android: layout_width="fi11l_parent”
Mobile Application Development 447 Designing User Interface with View

android: layout_height="fill_parent"
android:scrollbars="horizontal">
<LinearLayout
android: layout_width="fill_parent"
android: layout_height="fill_parent"
android: orientation="horizontal">
<Button
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_margin="20dp"
android: background="#f@0"
android: padding="1@dp"
android:text="Button 1”
android:textColor="#fff"
android: textSize="20sp"/>
<Button
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_margin="2@dp"
android: background="#ef8"
android: padding="1@dp"
android:text="Button 2"
android: textColor="#fff"
android:textSize="20sp"/>
<Button
android: layout_width="wrap_content"™
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_margin="20dp"
android: background="#00f"
android: padding="1@dp"
android:text="Button 3"
android: textColor="#fff"
android: textSize="2@sp"/>
<Button
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_margin="20dp"
android: background="#ff6"
android: padding="1@dp"
android:text="Button 4"
android: textColor="#f ff"
android: textSize="20sp"/>
<Button
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_margin="20dp"
android: background="#f@t"
android: padding="1@dp"
android:text="Button 5"
Mobile Application Development 4.48 Designing User Interface with View
android: textColor="#fff"
android:textSize="20sp"/>
<Button
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_gravity="center"
android: layout_margin="20dp"
android: background="#f96"
android: padding="1@dp"
android:text="Button 6"
android: textColor="#fff"
android: textSize="20sp"/>
<Button
android: layout_width="wrap_content”™
android: layout_height="wrap_content
android: layout_gravity="center"
android: layout_margin="20dp"
android: background="#f@0"
android: padding="1@dp"
android:text="Button 7"
android: textColor="#ff9"
android: textSize="20sp"/>
<Button
android: layout_width="wrap_content"
android: layout_height="wrap_content
android: layout_gravity="center"
android: layout_margin="26dp"
android: background="#444"
android: padding="1@dp"
android:text="Button 8”
android:textColor="#ffT"
android: textSize="2@sp"/>
<Button
android: layout_width="wrap_content”™
android: layout_height="wrap_content
android: layout_gravity="center”
android: layout_margin="20dp"
android: background="#f¥@02211"
android: padding="16@dp"
android:text="Button 9"
android: textColor="#fff"
android: textSize="20sp"/>
<Button
android: layout_width="wrap_content”
android: layout_height="wrap_content
android: layout_gravity="center"
android: layout_margin="2@dp"
android: background="#0f8"
android: padding="1@dp"
android:text="Button 10"
android:textColor="#fff"
android: textSize="2@sp"/>
</LinearLayout>
</fHorizontalScrollView>
</RelativeLayout>
Mobile Application Development 4.49 Designing User Interface with View

Step 3: Now open app — java > MainActivity.java in package and paste the below code:
package com.example.gourav.horizontalscrollviewExample;
import android. support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savediInstanceState);
setContentView(R.layout.activity_main);
}
}
Step 4: Now open AndroidManifest.xml inside manifests and paste the below code:
<?xml version="1.8" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example. gourav.horizontalscrollviewExample">
<application
android: allowBackup="true"
android: icon="@mipmap/ic_launcher"
android: label="@string/app_name"
android: theme="@style/AppTheme">
<activity
android: name="com.example.gourav.horizontalscrollviewExample.MainActivity”
android: label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android: name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Step 5: Open res > values > strings.xml and paste the below code:
<resources>
<stringname="app_name">ScrollViewExample</string>
<stringname="hello_world">Hello world!</string>
<stringname="action_settings" >Settings</string>
</resources>
Output:

preted
Mobile Application Development 4,50 Designing User Interface with View

‘ka CUSTOM TOAST ALERT


In Android, Toast is used to display information for a period of time. It contains a message to be
displayed quickly and disappears after specified period of time. It does not block the user
interaction.
Toast is a subclass of Object class. In this we use two constants for setting the duration for the Toast.
Toast notification in android always appears near the bottom of the screen. We can also create our
custom toast by using custom layout (xml file).
A toast provides simple feedback about an operation in a small popup. It only fills the amount of
space required for the message and the current activity remains visible and interactive. Toasts
automatically disappear after a timeout.
For example, clicking Send on an email triggers a "Sending message..." toast, as shown in Fig. 4.6.

Fig. 4.6: Exaple of Sending Message using Custom Toast


Toasts are not clickable. If user response to a status message is required, consider instead using
a Notification.
For creating a custom toast we firstly retrieve the layout inflater and then inflate the custom toast
layout from the xml file. After that we get the reference of TextView and ImageView from the
inflated layout and set the text and image in the TextView and ImageView.
Step 1: Create a new project and name it ToastExample.
Step 2: Open res > layout > activity_main.xml (or) main.xml and add following code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http: //schemas.android.com/tools"
android: layout_width="match_parent"
android: layout_height="match_parent"™
android: paddingBottom="@dimen/activity_vertical_margin"
android: paddingLeft="@dimen/activity_horizontal_margin"
android: paddingRight="@dimen/activity_horizontal_margin"
android: paddingTop="@dimen/activity_vertical_margin”
tools: context=".MainActivity">
<l-- Button's for simple and custom Toast -->
<Button
android: id="@+id/simpleToast"
android: layout_width="200dp"
android: layout_height="wrap_content"
android: layout_centerHorizontal="true"
android: layout_marginTop="15@dp"
android: background="#f@0"
android:text="Simple Toast”
android: textColor="#fff"
android:textSize="2@sp" />
<Button
android: id="@+id/customToast"
Mobile Application Development 4.51 Designing User Intertace with View

android: layout_width="20@dp"
android: layout_height="wrap_content”
android: layout_below="@+id/simpleToast"
android: layout_centerHorizontal="true"
android: layout_margin="50dp"
android :background="#6f6"
android:text="Custom Toast”
android: textColor="#fff"
android:textSize="20sp" />
</RelativeLayout>
Step 3: Now create a xml layouts by right clicking on res/layout - New — Layout Resource File and
name it custom_toast_layout.xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android: id="@+id/toast_layout_root”
android: layout_width="fill_parent”
android: layout_height="fill_parent”
android: background="#DAAA"
android:orientation="horizontal"
android: padding="8dp">
<l-- ImageVView and TextView for custom Toast -->
<ImageView
android: id="@+id/toastImageView"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: layout_marginRight="8dp" />
<TextView
android: id="@+id/toastTextView™
android: layout_width="wrap_content™
android: layout_height="wrap_content"
android:textColor="#FFF" />
</LinearLayout>
Step 4: Open src > package — MainActivity.java.
In this step we open MainActivity and add the code for initiate the Button’s and perform click event
on Button’s. Whenever a user click on simple Toast Button a Toast with message “Simple Toast In
Android” displayed on the screen and when a user clicks on custom toast Button a message “Custom
Toast In Android” with a image displayed on the screen.
For Creating a custom toast we firstly retrieve the layout inflater and then inflate the custom toast
layout from the xml file. After that we get the reference of TextView and ImageView from the
inflated layout and set the text and image in the TextView and ImageView.
Finally we create a new Toast and pass the inflated layout in the setView() method and then display
the Toast by using show() method of Toast.
package com. abhiandroid.toastexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget .ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;
import android.view.ViewGroup;
Mobile Application Development 4,52 Designing User Interface with View

public class MainActivity extends AppCompatActivity {


Button simpleToast, customToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of Button's
simpleToast = (Button) findViewById(R.id.simpleToast);
customToast = (Button) findViewById(R.id.customToast);
// perform setOnClickListener event on simple Toast Button
simpleToast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// initiate a Toast with message and duration
Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast In
Android", Toast.LENGTH_LONG); // initiate the Toast with context,
message and duration for the Toast
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, @, ®);
// set gravity for the Toast.
toast.show(); // display the Toast
}
})3
// perform setOnClickListener event on custom Toast Button
customToast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Retrieve the Layout Inflater and inflate the layout from xml
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
// get the reference of TextView and ImageVIew from inflated layout
TextView toastTextView = (TextView)
layout. findViewById(R.id.toastTextView);
ImageView toastImageView = (ImageView)
layout. findViewById(R.id.toastImageView);
// set the text in the TextView
toastTextView.setText("Custom Toast In Android");
// set the Image in the ImageView
toastImageView.setImageResource(R.drawable.ic_launcher);
// create a new Toast using context
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG); // set the duration for the Toast
toast.setView(layout); // set the inflated layout
toast.show(); // display the custom Toast
}
y)5

}
“aCe TimePicker
e In Android, TimePicker is a widget used for selecting the time of the day in either AM/PM mode or 24
hours mode. The displayed time consist of hours, minutes and clock format. If we need to show this
view as a Dialog then we have to use a TimePickerDialog class.
Mobile Application Development 4.53 Designing User Interface with View

Android Time Picker allows us to select the time of day in either 24 hour or AM/PM mode. The time
consists of hours, minutes and clock format. Android provides this functionality through TimePicker
class.
Methods of TimePicker:
Let's discuss some common methods of a time picker, which are used to configure a TimePicker in
our application.
setCurrentHour(Integer currentHour): This method is used to set the current hours in a TimePicker.
setHour(Integer hour): setCurrentHour() method was deprecated in API level 23. From API level 23
we have to use setHour(Integer hour). In this method there is only one parameter of integer type
which is used to set the value for hours. Below we set the 5 value for the current hours.
TimePicker simpleTimePicker=(TimePicker) findViewById(R.id.simpleTimePicker) ;
// initiate a time picker
// set the value for current hours
simpleTimePicker.setCurrentHour(5); // before API level 23
simpleTimePicker.setHour(S); // from API level 23
setCurrentMinute(Integer currentMinute): This method is used to set the current minutes in a
time.
picker.setMinute(Integer minute): setCurrentMinute() method was deprecated in API level 23. From
API level 23 we have to use setMinute(Integer minute). In this method there is only one parameter of
integer type which set the value for minutes. Below we set the 35 value for the current minutes.
TimePicker simpleTimePicker=(TimePicker) findViewById(R.id.simpleTimePicker) ;
// initiate a time picker
// set the value for current hours
simpleTimePicker. setCurrentMinute(35) ; // before API level 23
simpleTimePicker. setMinute(35); // from API level 23
getCurrentMinute(): This method is used to get the current minutes from a time picker.
getMinute(): getCurrentMinute() method was deprecated in API level 23. From api level 23 we have to
use getMinute(). This method returns an integer value.
Below we get the value of minutes from a time picker.
TimePicker simpleTimePicker = (TimePicker) findViewById(R.id.simpleTimePicker);
// initiate a time picker
int minutes = simpleTimePicker. getCurrentMinute() ; // before API level 23
int minutes = simpleTimePicker.getMinute(); // after API level 23
7. setIis24HourView(Boolean is24HourView): This method is used to set the mode of the Time picker
either 24 hour mode or AM/PM mode. In this method we set a Boolean value either true or false. True
value indicate 24 hour mode and false value indicate AM/PM mode. Below we set the current mode of
the time picker.
TimePicker simpleTimePicker =
(TimePicker)findViewById(R.id.simpleTimePicker);
// initiate a time picker
simpleTimePicker. setIs24HourView(true) ; // set 24 hours mode for the time picker
is24HourView(): This method is used to check the current mode of the time picker. This method
returns true if its 24 hour mode or false if AM/PM mode is set. Below we get the current mode of the
time picker:
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker);
// initiate a time picker
Boolean mode=simpleTimePicker.is24HourView();//check the current mode of the time picker
setOnTimeChangedListener(TimePicker.OnTimeChangedListener onTimeChangedListener): This
method is used to set the callback that indicates the time has been adjusted by the user.
onTimeChanged (TimePicker view, int hourOfDay, int minute) is an override function of this listener
Mobile Application Development 4.54 Designing User Intertace with View
in which we have three parameters first is for TimePicker, second for getting hour of the day and
last is for getting the minutes after changing the time of the time picker. Below we show the use of
on time changed listener of a time picker.
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker);
// initiate a time picker
simpleTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
}
})3
Attributes of TimePicker:
Now let us discuss about the attributes that helps us to configure a TimePicker in the xml file
(layout).
id: The id is an attribute used to uniquely identify a time picker.
<TimePicker
android: id="@+id/simpleTimePicker"
android: layout_width="wrap_content"
android: layout_height="wrap_content"/><!-- id of a time picker -->
timePickerMode: The time picker mode is an attribute of time picker used to set the mode
either spinner or clock. Default mode is clock but this mode is no longer used after API level 21, so
from API level 21 we have to set the mode to spinner. Below we set the mode to spinner.
<TimePicker
android: id="@+id/simpleTimePicker"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: timePickerMode="spinner" /><!-- time picker mode of a time picker -->
background: The background attribute is used to set the background of a TimePicker. We can set a
color or a drawable image in the background. We can also set the background color
programmatically means in Java class. Below we set the orange color for the background of a time
picker.
<TimePicker
android: id="@+id/simpleTimePicker”
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: timePickerMode="spinner"
android: background="#F88F00" /><!-- orange background color for the time picker -->
Setting TimePicker Background In Java Class:
TimePicker simpleTimePicker=(TimePicker) findViewById(R.id.simpleTimePicker) ;
// initiate a time picker
simpleTimePicker. setBackgroundColor(Color. YELLOW) ;
// Yellow background color for the background of a time picker
padding: The padding attribute is used to set the padding from left, right, top or bottom for a time
picker.
paddingRight: Set the padding from the right side of the TimePicker.
0 0

paddingLeft: Set the padding from the left side of the TimePicker.
oo

paddingTop: Set the padding from the top side of the TimePicker.
paddingBottom: Set the padding from the bottom side of the TimePicker.
Padding: Set the padding from the all side’s of the TimePicker.
o
Mobile Application Development 455 Designing User Interface with View

Below example we set the 20dp padding from all the side's of the TimePicker.
<TimePicker
android :id="@+id/simpleTimePicker"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: timePickerMode="spinner”
android : layout_centerHorizontal="true"
android : layout_marginTop="5@dp"
android :padding="20dp"/><!-- 2@dp padding from all the sides of a time picker -->
Example:
Step 1; Create a new project and name it TimePickerExample
Step 2: Open res > layout — activity_main.xml (or) main.xml and add following code. In this step we
open an xml file and add the code for displaying a time picker with spinner mode and textview for
displaying time of time picker.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools”
android: layout_width="match_parent”
android: layout_height="match_parent"
android: paddingBottom="@dimen/activity_vertical_margin"
android: paddingLeft="@dimen/activity_horizontal_margin"
android: paddingRight="@dimen/activity_horizontal_margin"
android: paddingTop="@dimen/activity_vertical_margin"
tools: context=".MainActivity">
<TimePicker
android: id="@+id/simpleTimePicker"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_centerHorizontal="true"
android: layout_marginTop="5@dp"
android: background="#090"
android: padding="2@dp"
android: timePickerMode="spinner" />
<TextView
android: id="@+id/time"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_centerHorizontal="true"
android:text="Time Is ::"
android: textColor="#896"
android: textSize="20sp"
android: textStyle="bold" />
</RelativeLayout>
Step 3: Open app > package > MainActivity.java.
In this step we open MainActivity where we add the code to initiate the TimePicker and a text view to
display time of time picker and then we perform setOnTimeChangedListener() event so whenever a
user adjust the time the current displayed time of time picker is displayed by using a Toast and also
displayed in the TextView.
package example. gb.timepickerexample;
import android. app.TimePickerDialog;
import android. graphics.Color;
import android. support.v7.app.AppCompatActivity;
import android.os.Bundle;
Mobile Application Development 4.56 Designing User Interface with View
import android. view.Menu;
import android. view.MenuItem;
import android.view. View;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
TextView time;
TimePicker simpleTimePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate the view's
time = (TextView) findViewById(R.id.time);
simpleTimePicker = (TimePicker) findViewById(R.id.simpleTimePicker);
simpleTimePicker.setIs24HourView(false); // used to display AM/PM mode
// perform set on time changed listener event
simpleTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener()

@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// display a toast with changed values of time picker
Toast .makeText(getApplicationContext(), hourOfDay + " " + minute,
Toast. LENGTH_SHORT) .show() ;
time.setText("Time is :: " + hourOfDay + " : " + minute); // set the
current time in text view

‘etm DatePicker
e In Android, DatePicker is a widget used to select a date. It allows to select date by day, month and
year in our custom UI (User Interface). If we need to show this view as a dialog then we have to use a
DatePickerDialog class. For selecting time Android also provides TimePicker to select time.
Mobile Application Development 4.57 Designing User Interface with View
Methods of DatePicker: Let us discuss some common methods of a DatePicker which are used to
configure a DatePicker in our application.
1. setSpinnersShown(boolean shown): This method is used to set whether thespinnerof
the TimePicker in shown or not. In this method we have to set a Boolean value either true or false.
True indicates spinner is shown, false value indicates spinner is not shown. Default value for this
function is true. Below we show the use of setSpinnerShown() function by setting false value.
DatePicker simpleDatePicker = (DatePicker)findViewBylId(R.id.simpleDatePicker);
// initiate a date picker
simpleDatePicker.setSpinnersShown(false); //set false value for the spinner shown function
2. getDayOfMonth(): This method is used to get the selected day of the month from a DatePicker. This
method returns an integer value. Below we show how to get the selected day of the month from
a DatePicker.
/*Add in Oncreate() funtion after setContentView()*/
DatePicker simpleDatePicker = (DatePicker) findViewById(R.id.simpleDatePicker);
// initiate a date picker
int day = simpleDatePicker.getDayOfMonth(); // get the selected day of the month
3. getMonth(): This method is used to get the selected month from a date picker. This method returns
an integer value. Below we get the selected month from a date picker.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker);
// initiate a date picker
int month = simpleDatePicker.getMonth(); // get the selected month
4. getYear(): This method is used to get the selected year from a date picker. This method returns an
integer value. Below code is used to get the selected year from a date picker.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker);
// initiate a date picker
int year = simpleDatePicker.getYear(); // get the selected year
5. getFirstDayOfWeek(): This method is used to get the first day of the week. This method returns an
integer value. Below code is used to get the first day of the week.
DatePicker simpleDatePicker = (DatePicker)findViewBylId(R.id.simpleDatePicker);
// initiate a date picker
int firstDay=simpleDatePicker.getFirstDayOfWeek(); // get the first day of the week
Attributes of DatePicker
* Now let us discuss some important attributes that helps us to configure a DatePicker in the XML file
(layout).
1, id: The id is an attribute used to uniquely identify a date picker.
<DatePicker
android: id="@+id/simpleDatePicker"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
{>
2. datePickerMode: This attribute is used to set the DatePicker in mode either spinner or calendar.
Default mode is calendar but this mode is not used after API level 21, so from API level 21 we have to
set the mode to spinner. Below is an example code in which we set the mode to spinner for a date
picker.
<DatePicker
android: id="@+id/simpleDatePicker"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: datePickerMode="spinner" /><!-- spinner mode of a date picker -->
Mobile Application Development 4.58 Designing User Interface with View

3. background: The background attribute is used to set the background of a DatePicker. We can set a
color or a drawable image in the background. Below we set the red color for the background of a date
picker.
<DatePicker
android: id="@+id/simpleDatePicker"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: datePickerMode="spinner™
android: background="#f00"/><!-- red color for the background of the date picker -->
Setting background of DatePicker In Java Class:
DatePicker simpleDatePicker=(DatePicker)findViewById(R.id.simpleDatePicker);
// initiate a date picker
simpleDatePicker. setBackgroundColor(Color.RED);
// red color for the background of a date picker
4, padding: The padding attribute is used to set the padding from left, right, top or bottom for a date
picker.
o paddingRight: Set the padding from the right side of the DatePicker.
o paddingLeft: Set the padding from the left side of the DatePicker.
o paddingTop: Set the padding from the top side of the DatePicker.
a paddingBottom: Set the padding from the bottom side of the DatePicker.
o Padding: Set the padding from the all side’s of the DatePicker.
Below code of padding attribute set the 40dp padding from all the side’s of the DatePicker.
<DatePicker
android: id="@+id/simpleDatePicker"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: datePickerMode="spinner”
android: padding="4@dp"/><!-- 4@dp padding from all the sides of a date picker -->
Example:
Step 1; Create a new project and name it DatePickerExample
Step 2: Open res > layout —> activity_main.xml (or) main.xml and add following code. In this step we
open an xml file and add the code for displaying A DatePicker with spinner mode and a button for
getting the date from the DatePicker.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android: layout_width="match_parent"
android: layout_height="match_parent"
android: paddingBottom="@dimen/activity_vertical_margin"
android: paddingLeft="@dimen/activity_horizontal_margin"
android: paddingRight="@dimen/activity_horizontal_margin"
android: paddingTop="@dimen/activity_vertical_margin”
tools:context=".MainActivity">
<DatePicker
android: id="@+id/simpleDatePicker"
android: layout_width="wrap_content”
android: layout_height="wrap_content"
android: background="#156"
android: datePickerMode="spinner"/>
Mobile Application Development 4.59 Designing User Interface with View
<Button
android: id="@+id/submitButton”
android: layout_width="20edp"
android: layout_height="wrap_content"
android: layout_below="@+id/simpleDatePicker"
android: layout_centerHorizontal="true"
android: layout_marginTop="S5dp"
android: background="#158"
android: text="SUBMIT"
android: textColor="#fff"
android: textSize="20sp"
android:textStyle="bold"/>
</RelativeLayout>
Step 3: Open app > package > MainActivity.java
In this step we open MainActivity where we add the code to initiate the DatePicker & a button and
then perform onClickListener() event on button so whenever a user clicks on the button the day of
the month, month and year will be displayed by using a Toast.
import android. support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android. view.Menu;
import android.view.Menultem;
import android. view. View;
import android.widget .DatePicker;
import android. widget .Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
DatePicker simpleDatePicker;
Button submit;
@0verride
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate the date picker and a button
simpleDatePicker =(DatePicker) findViewById(R.id.simpleDatePicker);
submit =(Button) findViewById(R.id.submitButton);
// perform click event on submit button
submit. setOnClickListener(newView.OnClickListener(){
@Override
public void onClick(View v){
// get the values for day of month , month and year from a date picker
String day ="Day = "+ simpleDatePicker.getDayOfMonth();
String month ="Month = "“+(simpleDatePicker.getMonth()+1);
String year ="Year = "+ simpleDatePicker.getYear();
// display the values by using a toast
Toast .makeText(getApplicationContext(), day +"\n"+ month +"\n"+
year, Toast. LENGTH_LONG) .show();

})3
}
}
Mobile Application Development 4.60 Designing User Interface with View
Output:

Practice Questions
1. Whatis UI?
Enlist elements of UI.
PWN

What is Text View? How to create it? Explain with example.


Explain the term Button with example.
What is ImageButton? How to create it? Explain with example.
AN

Describe the following UI elements with example.


(i) ListView
(ii) ScrollView
(iii) GridView
(iv) ImageView.
Explain RadioGroup with example.
a

With the help of example describe ToggleButton.


Describe ImageView with example.
How to custom toast alert?
Describe Date and Time picker with example.
What is progress bar? How to create it?
Explain GridView with example
Describe the following with example:
(i) RadioButton
(ii) CheckBox.
15. Draw the hierarchy of designing User Interface (UI) with View.
16. Describe the term “edit text” with example.
17. Develop an Android application using Image Button.
18. Develop an Android application using Toggle Button.
19. Develop an Android application using Checkbox.
20. Develop an Android application using Progress bar.
21, Develop an Android application using Time Picker.
22. Develop an Android application using Date Picker.
23. Explain RadioGroup with example.
24, Describe the concept of Custom Toast Alert with example.
ian

a
Activity and Multimedia
with Databases »
Chapter Outcomes...
Apply the given Intents and service in application development.
Use fragment to generate the given multiple activities.
Seen

Develop programs to play the given multimedia.


Write the query to perform the given database management operation.
Explain significance of the given component in Android architecture.

Learning Objectives...
To understand Concepts in Activity
ee of

To learn Database and with Multimedia Database with its Framework


To study Services in Android
To understand SQL Database with its Creation and Connection

[EQ3 inrropuction
e An activity is the single screen in android. It is like window or frame of Java. With the help of
activity, one can place all our UI components or widgets in a single screen.
e Adatabase is an organized collection of data. A database is a collection of schemas, tables, queries,
reports, views and other objects. A query language is a computer language used to make queries (or
questions about data) in databases and information systems.
e A Database Management System (DBMS) is a computer software application that interacts with the
user, other applications, and the database itself to capture and analyze data. A general-purpose
DBMS is designed to allow the definition, creation, querying, update, and administration of
databases.
* Multimedia database is the collection of interrelated multimedia data that includes text, graphics,
images, animations, video, audio etc. and have vast amounts of multisource multimedia data.
e The framework that manages different types of multimedia data which can be stored, delivered and
utilized in different ways is known as multimedia database management system.
e There are three classes of the multimedia database which includes static media, dynamic media and
dimensional media.
« A-combination of multiple forms of media and content is called Multimedia. This can be text,
graphics, audio, video etc. A MultiMedia DataBase (MMDB) is a collection of related multimedia data.
« Multimedia database systems are database systems where, besides text and other discrete data,
audio and video information will also be stored, manipulated and retrieved.
* Aservice is a component that runs in the background to perform long-running operations without
needing to interact with the user and it works even if application is destroyed.
[5.1]
Mobile Application Development 5.2 Activity and Multimedia with Databases

A service can essentially take two states namely, Started when an application component, such as an
activity, starts it by calling startService() and Bound when an application component binds to it by
calling bindService().
SQLite is a open-source SQL database that stores data to a text file on a device. Android comes in with
built in SQLite database implementation.
SQLite is an open-source relational database i.e. used to perform database operations on android
devices such as storing, manipulating or retrieving persistent data from the database.
Introduction to Activity in android:
The activity represents a single screen or interfaces that allows the user to interact with an
application. So, depending on the application on the application types, applications have single to
multiply activities.
For example, the Facebook application of our Android smart phone could have an activity to log into
the application.
All the activities of an application must work together to provide a comprehensive and cohesive user
experience. However, each of these activities could be independent of one another, thereby enabling
a different application to use those activities.
For example, the camera application of our smart phone can use the post a photograph activity of
the Facebook application to post a photograph in our Facebook account.

Fig. 5.1
A visual user interface for one directed attempt that the user can take is offered by an activity. For
instance, an activity may offer a list of menu items that the user could select from or exhibit
photographs besides with their captions.
A text messaging application may have one activity that shows a list of contacts to send messages to,
a second activity which is used for writing the messages to the selected contact, and other activities
to review old messages.
Each activity is independent of the others even though they work together. Each one is implemented
as a subclass of the Activity base class.
Typically, one of the activities is marked as the first one that should be presented to the user when
the application is launched. Moving from one activity to another is proficient by having the current
activity which start the next one.
Each activity is given a default window to draw in. Usually the window fills the screen, but it may be
smaller than the screen and float on top of other windows. An activity can also compose the use of
additional windows.
For example, a pop-up dialog that calls for a user comeback in the middle of the activity, or a
window to present users with vital information when they select a particular item on-screen.
Mobile Application Development 5.3 Activity and Multimedia with Databases

The visual content of the window is provided by a hierarchy of views-objects derived from the base
View class. Each view controls a rectangular space inside the window. Parent views hold and
organize the layout of their children.
Leaf views draw in the rectangles they control and respond to user actions directed at that space. The
activity’s interaction with the user takes place where there are views.
Android offers many build in views that we use; buttons, textfields, scrollbars, menu bar, cjeck box
etc.
A view hierarchy is placed with in an activity’s window by the Activity.setContentview() method,
o An activity is a single, focused thing that the user can easily do. All activities interact
with the user so the Activity class creates a window in which we can place the UI with
setContentView(View).
o While activities are often presented to the user as full-screen windows, it can also be used in
other ways: as floating windows or embedded inside another activity.
o There are two methods to implement activity:-
< onCreate(Bundle) is a method in which we initialize our activity. Here we usually call
setCotentView(int)with a layout resource defining the UI, and using findViewByld(int) to
retrieve the widgets in that UI which we need to interact with programmatically.
< onPause() is another method in which we deal with the user leaving the activity. Any changes
made by the user should at this point be committed.
The points are Activity Lifecycle, Starting activities and getting results, Saving persistent state,
Permission, Process Lifecycle.

INTENT
Have we ever wondered how a new Activity opens when we click on some button, suppose the
settings button to show the Settings screen in any app? How does the app opens up when we click on
its notification? How do we get Low battery alert in our mobile? All these things are possible because
of Intent in Android,
An Intent is a messaging object that we can use to request an action from an app component. An
Intent is basically an intention to do an action. It is a way to communicate between Android
components to request an action from a component, by different components.
It's like a message that Android listens for and then react accordingly by identifying and invoking
the app's appropriate component (like an Activity, Service, Content Provider, etc.). It can be within
that same app or some other app as well.
If multiple apps are capable of responding to the message then Android provides the user with a list
of those apps from which a choice can be made.
Uses of Intent in Android:
There are three fundamental uses of intents:
To Start an Activity:
An Activity represents a single screen in an app. We can start a new instance of an Activity by
passing an Intent tostartActivity(. The Intent describes the activity to start and carries any
necessary data along.
To Start a Service:
A Service is a component that performs operations in the background and does not have a user
interface. We can start a service to perform a one-time operation (such as downloading a file) by
passing an Intent tostartService(). The Intent describes which service to start and carries any
necessary data.
Mobile Application Development 5.4 Activity and Multimedia with Databases

3. To Deliver a Broadcast:
A broadcast is a message that any app can receive. The system delivers various broadcasts for system
events, such as when the system boots up or the device starts charging.
We can deliver a broadcast to other apps by passing an Intent to sendBroadcast() or
sendOrderedBroadcast().
In Android, there are two types of Intents namely, Explicit Intents and Implicit Intents
Explicit Intents
When we explicitly define which Android component should be opened on some user action, then we
use explicit intents. We generally use an explicit intent to start a new component in our own app,
because we know which exact activity or service you want to start.
For example, we can start a new activity in response to a user action or start a service to download a
file in the background.
Create an Explicit Intent: To create an explicit intent,
1. We need to make an Intent object. The constructor of the Explicit Intent's object needs two
parameters as follows:
Context c: This represents the object of the Activity from where we are calling the intent.
Java file name: This represents the name of the java file of the Activity we want to open.
Note: We need to mention the java file name with .class extension
Intent i = new Intent(this.MyJavaFile.class);
Call startActivity() method and pass the intent's object as the parameter. This method navigates to
the java file mentioned in the Intent's object.
startActivity(i);
If we need to pass some information or data to the new Activity we are calling, we can do this by
calling putExtra() method before the startActivity() method. This method accepts key-value pair as
its parameter.
i.putExtra(“key1”,”I am value1”);
i.putExtra(*key2”,”I am value2”);
startActivity(i);
Note:To receive the data in the new Activity and use it accordingly, we need to call
the getIntent() method and then getStringExtra() method in the Java class of the Activity we want to
open through explicit intent. getStringExtra() method takes the key as the parameter.
String a=getIntent().getStringExtar(“key1”);
OF this, stores the value stored at key1 into the string variable a.
| Implicit Intents
° When we just have to tell what action we want to perform without worrying which component will
perform it, then we can use implicit intent.
Implicit intents do not name a specific component to perform a particular action, but instead it
declares a general action to be performed, which allows any component, even from another app to
handle it.
For example, if we want to show a specific location of the user on a map, we can use an implicit
intent to pass the coordinates through the intent and then any other app, which is capable of
showing the coordinates on a map will accept that intent.
Create an Implicit Intent: To create an implicit intent,
1. We need to make an Intent object. The constructor of the Implicit Intent's object needs atype of
action we want to perform.
Mobile Application Development 5.5 Activity and Multimedia with Databases

An action is a string that specifies the generic action to be performed. The action largely determines
how the rest of the intent is structured, particularly the information that is contained as data and
extras in the intent object. For example,
ACTION_VIEW: This action is used when we have some information that an activity can show to the
user, such as a photo to view in a Gallery app, or an address to view in a Map app.
ACTION_SEND: This action is used when we have some data that the user can share through another
app, such as an Email app or some Social Networking app.
Note: We can specify the own actions for getting used by intents within the own app (or for getting
used by other apps to invoke components in our app), but we usually specify action constants
defined by the Intent class or other framework classes.
Intent i = new Intent(Intent.ACTION VIEW);
2. We need to provide some data for the action to be performed. Data is typically expressed as a URI
(Uniform Resource Identifier) which provides data to the other app so that any other app which is
capable of handling the URI data can perform the desired action. For example, if we want to open a
website through our app, we can pass the URI data using setData() method as follows:
i.setData(Uri.parse(http: //www.google.co.in));
3. CallstartActivity() method in the end with the intent object as the parameter.
startActivity(i);
Android Implicit Intent Example:
activity_main.xml
<?xml version="1.6" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
xmlns:app="http: //schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools”
android: layout_width="match_parent”
android: layout_height="match_parent"
tools: context=".MainActivity">
<EditText
android: id="@+tid/editText”
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_marginEnd="8dp"
android: layout_marginStart="8dp"
android: layout_marginTop="6@dp"
android: ems="16"
app: layout_constraintEnd_toEndOf="parent"
app: layout_constraintHorizontal_bias="@.575"
app: layout_constraintStart_toStartOf="parent"
app: layout_constraintTop_toTopOf="parent" />
<Button
android: id="@+id/button"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_marginRight="8dp"
android: layout_marginLeft="156dp"
android: layout_marginTop="172dp"
android: text="Visit”
app: layout_constraintEnd_toEndOf="parent"
Mobile Application Development 5.6 Activity and Multimedia with Databases
app: layout_constraintHorizontal_bias="0.0"
app: layout_constraintStart_toStartOf="parent"
app: layout_constraintTop_toBottom0f="@+id/editText" />
</android. support.constraint.ConstraintLayout>
MainActivity.java
import android. content.Intent;
import android.net.Uri;
import android. support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android. view. View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
Button button;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savediInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
editText = findViewById(R.id.editText);
button. setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url=editText.getText().toString();
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity (intent);
}
hs

}
Android Explicit Intent Example:
Android Explicit intent specifies the component to be invoked from activity. In other words, we can
call another activity in android by explicit intent.
We can also pass the information from one activity to another using explicit intent.
Here, we are going to see an example to call one activity from another and vice-versa. Android
calling one activity from another activity example
Let us see the simple example of android explicit example that calls one activity from another and
vice versa.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools”

android: layout_width="match_parent”
android: layout_height="match_parent"
tools: context=".FirstActivity">
Mobile Application Development 5.7 Activity and Multimedia with Databases

<TextView
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_marginEnd="8dp"
android: layout_marginStart="8dp"
android: layout_marginTop="8dp"
android: text="First Activity”
app: layout_constraintBottom_toBottom0f="parent"
app: layout_constraintEnd_toEndOf="parent”
app: layout_constraintHorizontal_bias="@.454"
app: layout_constraintLeft_toLeftOf="parent”™
app: layout_constraintRight_toRightOf="parent”
app: layout_constraintStart_toStartOf="parent”
app: layout_constraintTop_toTopOf="parent”
app: layout_constraintVertical_bias="8.06" />
<Button
android: id="@+id/button”

android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: Layout_marginEnd="8dp"
android: layout_marginStart="8dp"
android: layout_marginTop="392dp"
android: onClick="callSecondActivity"
android: text="Call second activity"
app: layout_constraintEnd_toEndOf="parent”
app: layout_constraintStart_toStartOf="parent"
app: layout_constraintTop_toTopOf="parent™ />
</android.support.constraint.ConstraintLayout>
ActivityOne class
File: MainActivityOne.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class FirstActivity extends AppCompataActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
public void callSecondActivity(View view){
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
i.putExtra("Value1", "Android By Javatpoint");
i.putExtra("Value2", "Simple Tutorial");
Mobile Application Development 5.8 Activity and Multimedia with Databases

// Set the request code to any code you like, you can identify the
// callback via this code
startActivity(i);

}
activitytwo_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmLns:tools="http://schemas.android.com/tools”
android: layout_width="match_parent"
android: layout_height="match_parent"
tools: context=".SecondActivity">
<TextView
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: layout_marginEnd="8dp"
android: layout_marginStart="8dp"
android: layout_marginTop="8dp"
android: text="Second Activity"
app: layout_constraintBottom_toBottom0f="parent”
app: layout_constraintEnd_toEndOf="parent”
app: layout_constraintHorizontal_bias="0.454"
app: layout_constraintLeft_toLeftOf="parent”
app: layout_constraintRight_toRightOf="parent”
app: layout_constraintStart_toStartOf="parent”
app: layout_constraintTop_toTopOf="parent"
app: layout_constraintVertical_bias="9.06" />
<Button
android: id="@+id/button"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_marginEnd="8dp"
android: layout_marginStart="8dp"
android: layout_marginTop="392dp"
android: onClick="callFirstActivity"
android:text="Call first activity"
app: layout_constraintEnd_toEndOf="parent"
app: layout_constraintStart_toStartOf="parent"
app: layout_constraintTop_toTopOf="parent” />
</android. support. constraint.ConstraintLayout>
ActivityTwo class:
MainActivityTwo.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
Mobile Application Development 5.9 Activity and Multimedia with Databases

import android.os.Bundle;
import android. view. View;
import android.widget.Toast;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle extras = getIntent().getExtras();
String valuel = extras.getString("Value1");
String value2 = extras.getString("Value2");
Toast.makeText(getApplicationContext(),"Values are:\n First value: "+valuel+
"\n Second Value: “+value2, Toast.LENGTH_LONG) .show();
}
public void callFirstActivity(View view){
Intent i = new Intent(getApplicationContext(), FirstActivity.class);
startActivity(i);
}
}
Intent_Filter
Intent_filters is a very powerful way to connect different applications together hence allowing
better user experience. They take care of intent resolution to match activities, services and broadcast
receiver. Intent filter are declared in the AndroidManifest.xml. an intent filters is an instance of the
IntentFilter class.
An intent filter declares the capability of its parent component.
Syntax:
<intent-filter
android: icon="drawable resource”
android: label="string resource”
android: priority="integer”>

</intent-filter>

Attributes:
1, ANDROID:ICON: An icon represents the parent activity, service, or broadcast receiver when that
component is existing to the user as having the potential described by the filter. This attribute must
set as a reference to z drawable resource containing the image definition. The defaulting value is the
icon set by the parent components icon attribute. If the parent do not specify an icon, the default is
the icon set by the <application> element.
android:label: A user readable label for the parent component. This label, rather than the single set
by the parent component, is used when the component is offered to the user as having the capability
described by the filter.
The label should be set as the reference to the string resource, so that it can be localized like other
strings in the user interface.
The default value is the label set by the parent component. If the parent do not specify a label, the
default is the label set by the <application> element's label attribute.
Mobile Application Development 5.10 Activity and Multimedia with Databases

wag ACTIVITY LIFE CYCLE


e Activities in the system are managed as an activity stack. When a new activity is happening, it is
placed on the top of the stack and becomes the running activity.
« The activity always remains below it in the stack, and will not come to the foreground again until the
new activity exits.

Activity
launched

> onCreate()

t
onStart() onRestart()

User navigates
t A

to the activity onResume()

= ki Ih led running

Another activity comes


into the foreground User returns
| to the activity
Apps with higher priority
need memory — onPause()

|
Another activity comes
into the foreground User navigates
| to the activity
|
|
The activity is finished or
being destroyed by the system

onDestroy()

Activity
shut down

Fig. 5.2: Activity Life Cycle


¢ Activities have a predefined life-cycle and which certain methods are called. Following table shows
important activity lifecycle methods:
Sr. No. Method Purpose
1, | onCreate() Called then the activity is created. Used to initialize the activity, for
example create the user interface.
2. | onResume() Called if the activity get visible again and the user starts interacting
with the activity again. Used to initialize fields, register listeners, bind
to services, etc.
Contd...
Mobile Application Development 5.11 Activity and Multimedia with Databases

3. onPause() Called once another activity gets into the foreground. Always called
before the activity is not visible anymore. Used to release resources or
save application data. For example, unregister listeners, intent
receivers, unbind from services or remove system service listeners.
4. onstop() Called once the activity is no longer visible. Time or CPU intensive shut-
down operations, such as writing information to a database should be
down in the onStop() method. This method is guaranteed to be called as
of API 11.
The flow of these methods is depicted in the Fig. 5.2.
Activity States:
The Android OS uses a priority queue to assist in managing activities running on the device. Based
on the state a particular Android activity is in, it will be assigned a certain priority within the OS,
This priority system helps Android identify activities that are no longer in use, allowing the OS to
reclaim memory and resources.
Fig. 5.2 illustrates the states an activity can go through, during its lifetime. These states are
often broken into three main teams as follows:
Active or Running:
Activities are thought of active or running if they are within the foreground, additionally referred to
as the top of the activity stack.
This can be thought of the highets priority activity within the Android Activity stack, andas such
only be killed by the OS in extreme things, like if the activity tries to use more memory thanis
available on the device as this might cause the UI to become unresponsive.
Paused:
When the device goes to sleep, or an activity continues to be visible but partially hidden bya new,
non-full-sized or clear activity, the activity is taken into account paused.
Paused activities are still alive, that is, they maintain all state and member information, and stay
attached to the window manager.
This can be thought of to be the second highest priority activity within the android Activity stack
and, as such, can solely be killed by the OS if killing this activity can satisfy the resource requirement
needed to keep the Active/Running Activity stable and responsive.
Stopped:
Activities that are utterly obscured by another activity are thought of stopped or within the
background.
Stopped activities still try and retain their state and member info for as long as possible but stopped
activities are thought of to be loweat priority of the three states and, as such, the OS can kill
activities during this state initial to satisfy the resource needs of higher priority activities.
Broadcast Life Cycle
Fig. 5.3 shows braodcast life cycle of activity.
A broadcast receiver is a component that does nothing but receives and reacts to broadcast
announcements. Many broadcasts originate in system code but any other applications can also
initiate broadcasts,
Broadcast receivers do not display a user interface. However they may perhaps start an activity in
response to the information they receive, or as service do they may possibly use the notification
manager to alert the user.
Mobile Application Development 5.12 Activity and Multimedia with Databases

Register the intent


to observe.

Android Braodcast
System Receiver

Gets notification
when intends occur

Fig. 5.3

Ea CONTENT PROVIDER
A Content Providercomponent supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class.
A content provider can use different ways to store its data and the data can be stored in files, in a
database or even over a network.
Content Providers support the four basic operations, normally called CRUD-operations. CRUD is the
acronym for Create, Read, Update and Delete.
With content providers those objects simply represent data as most often a record of a database, but
they could also be a photo on our SD-card or a video on the web.
Content URIs
The most important concept to understand when dealing with content providers is the content URI.
Whenever we want to access data from a content provider we have to specify a URI. URIs for content
providers look like this:
content: //authority/optionalPath/optionalId
Here, detailed explanation about Content URIs:
The scheme for content providers is always “content”. The colon and double-slash “://" are a fixed
part
This specifies the name of the content provider, for example browser , contacts etc. Authorities have
to be unique for every content provider. Android documentation recommends to use the fully
qualified class name of our ContentProvider-subclass.
The optional path, is used to distinguish the kinds of data our content provider offers. For example,
distinguishes between audio files, video files and images using different paths for each of these
types of media. This way a content provider can support different types of data that are nevertheless
related. For totally unrelated data though you should use different content providers, and thus
different authorities.
The last element is the optional id, which - if present - must be numeric. The id is used whenever we
want to access a single record (For example, a specific video file).
There are two types of URIs namely, directory-based URIs, id-based URIs.
If no id is specified a URI is automatically a directory-based URI.
If we use directory-based URIs to access multiple elements of the same type (for example, all songs of
a band). All CRUD operations are possible with directory-based URIs.
Mobile Application Development 5.19 Activity and Multimedia with Databases

* We use id-based URIs if we want to access a specific element. We cannot create objects using an id-
based URI: but reading, updating and deleting is possible.
Content Types:
* Acontent type consists of a two types such as media type and a subtype divided by a slash. A typical
example is “image/png”. The media type “image” describes the content as an image file which is
further specified to be of the Portable Network Graphic variety by the subtype “png”.
And guess what?
e vnd.android.cursor.item: Used for single records
e vnd.android.cursor.dir: Used for multiple records
¢ The subtype on the other hand is used for content provider specific details and should
differ for all types our content provider supports. The naming convention for subtypes is
vnd.companyname.contenttype. Most content providers support multiple subtypes.
Which standard Content Providers are available?
¢ Anumber of content providers are part of Android’s API. All these standard providers are defined in
the package android.provider. The below lists the standard providers and what they are used for
1. CalendarContract SDK 14: Manages the calendars on the user’s device.
2. Browser SDK 1: Manages our web-searches, bookmarks and browsing-history.
3. CallLog SDK 1: Keeps track of our call history.
4, MediaStore SDK 1; The content provider responsible for all our media files like music, video and
pictures.
5. Settings SDK 1: Manages all global settings of our device.
6, UserDictionary SDK 3: Keeps track of words we add to the default dictionary.
Create Content Provider
¢ This involves number of simple steps to create our own content provider.
e First of all we need to create a Content Provider class that extends the ContentProviderbaseclass.
* Second, we need to define our content provider URI address which will be used to access the content.
*« Next we will need to create our own database to keep the content. Usually, Android uses SQLite
database and framework needs to override onCreate() method which will use SQLite Open Helper
method to create or open the provider's database. When our application is launched, the onCreate()
handler of each of its Content Providers is called on the main application thread.
¢ Next we will have to implement Content Provider queries to perform different database specific
operations.
¢ Finally register our Content Provider in our activity file using <provider> tag.
* list of methods which we need to override in Content Provider class to have our Content Provider
working:
1. onCreate(): This method is called when the provider is started.
2. query(): This method receives a request from a client. The result is returned as a Cursor object.
3. insert(): This method inserts a new record into the content provider.
4. delete(): This method deletes an existing record from the content provider.
- update(): This method updates an existing record from the content provider.
getType(): This method returns the MIME type of the data at the given URI.

EI FRAGMENTS
¢ A fragment is a self-contained, modular section of an application's User Interface (UI) and
corresponding behavior that can be embedded within an activity.
¢ Fragments can be assembled to create an activity during the application design phase, and added to
or removed from an activity during application runtime to create a dynamically changing user
interface.
Mobile Application Development 5.14 Activity and Multimedia with Databases
Fragments may only be used as part of an activity and cannot be instantiated as standalone
application elements. That being said, however, a fragment can be thought of as a functional “sub-
activity” with its own lifecycle similar to that of a full activity.
Fragments are stored in the form of XML layout files and may be added to an activity either by
placing appropriate <fragment> elements in the activity's layout file, or directly through code
within the activity’s class implementation.
Creating a Fragment:
The two components that make up a fragment are an XML layout file and a corresponding Java class.
The XML layout file for a fragment takes the same format as a layout for any other activity layout
and can contain any combination and complexity of layout managers and views.
The following XML layout, for example, is for a fragment consisting simply of a RelativeLayout with
ared background containing a single TextView:
<?xml version="1.6" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android: layout_width="match_parent"
android: layout_height="match_parent"
android: background="@color/red" >
<TextView
android: id="@+id/textView1"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_centerHorizontal="true"
android: layout_centerVertical="true"
android: text="@string/fragone_label_text”
android: textAppearance="?android:attr/textAppearanceLarge™ />
</RelativeLayout>
The corresponding class to go with the layout must be a subclass of the Android Fragment class. This
class should, at a minimum, override the onCreateView() method which is responsible for loading
the fragment layout. For example:
package com.example.myfragmentdemo;
import android.os. Bundle;
import android. view.LayoutInflater;
import android. view. View;
import android.
view. ViewGroup;
import android. support.v4.app.Fragment;
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one_layout, container, false);
}
}
Adding a Fragment to an Activity using the Layout XML File:
Fragments may be incorporated into an activity either by writing Java code or by embedding the
fragment into the activity’s XML layout file.
Regardless of the approach used, a key point to be aware of is that when the support library is being
used for compatibility with older Android releases, any activities using fragments must be
implemented as a subclass of FragmentActivity instead of the AppCompatActivity class:
Mobile Application Development 5,15 Activity and Multimedia with Databases

package com.example.myfragmentdemo;
import android.os.Bundle;
import android. support. v4.app.FragmentActivity;
import android.view.Menu;
public class FragmentDemoActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_demo);
}
}
e Fragments are embedded into activity layout files using the <fragment> element. The following
example layout embeds the fragment created in the previous section of this chapter into an activity
layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools”
android: layout_width="match_parent”
android: layout_height="match_parent"
tools: context=".FragmentDemoActivity" >
<fragment
android: id="@+id/fragment_one"
android: name="com.example.myfragmentdemo.myfragmentdemo.FragmentOne"
android: layout_width="match_parent"
android: layout_height="wrap_content”
android: layout_alignParentLeft="true”
android: layout_centerVertical="true"
tools: layout="@layout/fragment_one_layout" />
</RelativeLayout>
* The key properties within the <fragment> element are android:name, which must reference the
class associated with the fragment, and tools:layout, which must reference the XML resource file
containing the layout of the fragment.
* Once added to the layout of an activity, fragments may be viewed and manipulated within the
Android Studio Layout Editor tool.
e Fig. 5.4, for example, shows the above layout with the embedded fragment within the Android Studio
Layout Editor:

cuets

Fig. 5.4
Mobile Application Development 5.16 Activity and Multimedia with Databases

Adding and Managing Fragments in Code:


The ease of adding a fragment to an activity via the activity’s XML layout file comes at the cost of the
activity not being able to remove the fragment at runtime.
In order to achieve full dynamic control of fragments during runtime, those activities must be added
via code. This has the advantage that the fragments can be added, removed and even made to replace
one another dynamically while the application is running.
When using code to manage fragments, the fragment itself will still consist of an XML layout file and
a corresponding class. The difference comes when working with the fragment within the hosting
activity. There is a standard sequence of steps when adding a fragment to an activity using code:
1. Create an instance of the fragment's class.
2. Pass any additional intent arguments through to the class instance.
3. Obtain a reference to the fragment manager instance.
4, Call the beginTransaction( method on the fragment manager instance. This returns a fragment
transaction instance.
5. Call the add() method of the fragment transaction instance, passing through as arguments the
resource ID of the view that is to contain the fragment and the fragment class instance.
6. Call the commit() method of the fragment transaction.
The following code, for example, adds a fragment defined by the FragmentOne class so that it
appears in the container view with an ID of LinearLayout1:
FragmentOne firstFragment = new FragmentOne();
firstFragment.setArguments(getIntent().getExtras());
FragmentManager fragManager = getSupportFragmentManager({
);
FragmentTransaction transaction = fragManager.beginTransaction();
transaction.add(R.id.LinearLayout1, firstFragment);
transaction. commit();
The above code breaks down each step into a separate statement for the purposes of clarity. The last
four lines can, however, be abbreviated into a single line of code as follows:
getSupportFragmentManager( ).beginTransaction()
-add(R.id.LinearLayout1, firstFragment).commit();
Once added to a container, a fragment may subsequently be removed via a call to the remove()
method of the fragment transaction instance, passing through a reference to the fragment instance
that is to be removed:
transaction.remove(firstFragment);
Similarly, one fragment may be replaced with another by a call to the replace() method of the
fragment transaction instance. This takes as arguments the ID of the view containing the fragment
and an instance of the new fragment.
The replaced fragment may also be placed on what is referred to as the back stack so that it can be
quickly restored in the event that the user navigates back to it. This is achieved by making a call to
the addToBackStack() method of the fragment transaction object before making the commit()
method call:
FragmentTwo secondFragment = new FragmentTwo();
transaction.replace(R.id.LinearLayout1, secondFragment);
transaction. addToBackStack(null);
transaction. commit();
Mobile Application Development 5.17 Activity and Multimedia with Databases

Ei SERVICE
A service is an application component which runs without direst interaction with the user in the
background. Services are used for repetitive and potentially long running operations, i.e., Internet
downloads, checking for new data, data processing, updating content providers and the like.
Services run with a higher priority than inactive or invisible activities and therefore it is less likely
that the Android system terminates them. Services can also be configured to be restarted if they get
terminated by the Android system once sufficient system resources are available again.
Services are started with two methods namely, Context.startService(), Context.bindService().
Services are the faceless components of Android as they have their individual interfaces. They
typically run in the background to perform long-running operations or work for remote processes.
Services are communicate with other Android components and use the Android's notification
framework to notify the users.
Services are job-specific and they are unaffected by the switching activity. They will continue to run
in the background even if we switch to the interface of a different application.
[Ee-ee Features of Service
A feature for the application where the user is not directly interacting with the application
corresponds to calls to startService() method, which ask the system to agenda work for the service ,
to be run until the service or someone stops it forcefully.
A feature for an application to expose some of its functionality to other applications. This
correspond to calls to bindService() which allows a established connection to be made to the service
in order to interact with it.
[3-94 Android Platform Service
The Android platform provides pre-defined services, generally showing by a particular Manager
class. The getSystemService() method is used to access them.
Defining New Services
All android application can define and start new services. If we use asynchronous processing in
activites, the corresponding threads are still connected to the life cycle of the corresponding activity.
The android system may choose to terminate them at the time.
Services run with higher priority than inactive or invisible activities or invisible activities and the
Android system terminate them. Defining our own services allows us to design very approachable
applications.
We can obtain the application via a service and once the application is started by the user, it can
current fresh data to the user.
Declaring services: A service wants to be declared in the AndroidManifest.xml and the implementing
class should extend the Service class or one of its subclasses.
Service perform long running operation in the background.
PWN RP

It does not contain the user interface.


It is useful for things like playing music, network, network operations etc.
Services are run independently of the component that created it.
5. It can be bound to by other application components if allowed.
Service Life Cycle
As+ explnined above service can either be started or bound. We just need to call either startService()
or bindService() from any of our android components. Based on how our service was started it will
either be “started” or “bound”
Mobile Application Development 5.18 Activity and Multimedia with Databases

1, Started
A service isstarted when an application component, such as an activity, starts it by calling
startService().
Now the service can run in the background indefinitely, even if the component that started it is
destroyed.
Bound
A service is bound when an application component binds to it by calling bindService().
A bound service offers a client-server interface that allows components to interact with the service,
send requests, get results, and even do so across processes with InterProcess Communication (IPC).
Service is Service is
started by created by
startService() bindService()

onCreate() onCreate()

onStart() onBind()

Service is Cine ieerects


running the service
onRebind()

The service
is stopped "
(no callback) onUnbind()

i
onDestroy() onDestroy()

Service is Service is
shut down shut down

Fig. 5.5: Lifecycle of Service


Like any other components service also has callback methods. These will be invoked while the service
is running to inform the application of its state. Implementing these in our custom service would
help us in performing the right operation in the right state.
There is always only a single instance of service running in the app. If we are calling startService()
for a single service multiple times in our application it just invokes the onStartCommand() on that
service. Neither is the service restarted multiple times nor are its multiple instances created
onCreate():
This is the first callback which will be invoked when any component starts the service. If the same
service is called again while it is still running this method wont be invoked. Ideally one time setup
and intializing should be done in this callback.
onStartCommand():
This callback is invoked when service is started by any component by calling startService(). It
basically indicates that the service has started and can nowrun indefinetly.
Now its our responsibilty to stop the service. This callback also has aint return type. This return type
describes what happens to the service once it is destroyed by the system.
Mobile Application Development 5.19 Activity and Multimedia with Databases

e There are following three possible return types:


(i) START_STICKY: Returning this indicates that once the service is killed by the system it will be
recreated and onStartCommand method will be invoked again.But the previous intent is not
redelivered, Instead onStartCommand is called with a null intent
(ii) START_NOT_STICKY: Returning this indicates that the service wont be recreated if it is killed by
the system
(iii) START_REDELIVER_INTENT: Returning this indicates that once the service is killed by the
system it will be recreated and onStartCommand method will be invoked again.But here the
original intent is redelivered again.
3. onBind(
¢ This is invoked when any component starts the service by calling onBind. Basically the component
has now binded with the service. This method needs to return the implementation of IBinder which
will be used for Interprocess Communication. If we dont want our service to bind with any
component you should just return null nevertheless this method needs to be implemented
4, onUnbind(
e This is invoked when all the clients are disconnected from the service.
5. onRebind()
e This is invoked when new clients are connected to the service. It is called after onUnbind
6. onDestroy()
e This is a final clean up call from the system. This is invoked just before the service is being destroyed.
*® Could be very useful to cleanup any resources such as threads, registered listeners, or receivers. But
very rarely it happens that the service is destroyed with onDestroy not being invoked
Permission
* Global access to a service can be required when it is declared when it is declared in its manifest’s
<service> tag. By doing so, other applications will require to declare a corresponding <uses-
permission> element in their own manifest to be capable to start, stop or bind to the service.
e In addition a service can guard individual IPC calls into it with permissions, by calling the
checkCallingPermission (string) before executing the implementation of that call.
e Services which run in the procedure of the application are occasionally called local services.
Example of Service
* Inthis example we will create a service with runs in background and prints logs until we stop it.
Step 1: Create a Custom Service: As we have already discussed Service doesn’t have a its own layout
hence no xml file is required.
e Right click on our package and select New — Java Class. Name our class as MyService. This should
extend the Android's Service class.
¢ We will be using a Handler and Runnable implemenation to print the logs every 5 seconds as long as
the service is running
e Then implement all the callbacks as shown in the code snippet below
public class MyService extends Service {
//Declaring the handler
private Handler handler;
//Declaring our implementation of Runnable
private Runner runner;
/*

Regardless of whether you want our service to be binded


or not you should always implement onBind. You should return null if you
dont want it to bind
Mobile Application Development 5.20 Activity and Multimedia with Databases

*/
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*

Initialization of Handler and Runner


*/
public void onCreate() {
super.onCreate();
Toast.makeText(this, “Service Started", Toast.LENGTH_LONG).show();
handler = newHandler();
runner = newRunner();
}
// Starting the Runnable with handler
public int onStartCommand(Intent intent, int id, int startID) {
handler.post(runner);
return START_STICKY;
}
//Removing the callbacks from handler once the service is destroyed
@Override
public void onDestroy() {
super.onDestroy();
handler .removeCallbacks(runner);
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG) .show();
}
/*

A runnable class designed in such a way that it is runs every 5 seconds


*/
public class Runner implements Runnable {
@Override
public void run() {
Log.d("AndroidClarified", "Running");
handler.postDelayed(this, 1000 * 5);
}
}
}
Step 2: Declaring the service in Manifest: As for every android component we first need to declare our
service inside the AndroidManifest.xml For this we just need to add the below code snippet
under the <application> tag
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns :android="http://schemas.
android. com/apk/res/android"
package="com.example. androidclarified. serviceapp">
<application
android: allowBackup="true"
android: icon="@mipmap/ic_launcher"
android: label="@string/app_name"
android: roundIcon="@mipmap/ic_launcher_round"
android: supportsRtl="true"
Mobile Application Development 5.21 Activity and Multimedia with Databases

android: theme="@style/AppTheme">
<activityandroid:name=".MainActivity">
<intent-filter>
<actionandroid: name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
<factivity>
<serviceandroid:name=".MyService"/>
</application>
</manifest>
Step 3: Starting the service: Since every service needs to be started from some other Android
component. We will first create a Android Activity. We can just right click on our package and
select New — Activity — Empty Activity. This will automatically create an Activity class and a
layout file. We add two buttons to the layout file as shown in the snippet below:
<?xml version="1.0" encoding="utf-8"
?>
<RelativeLayout
xmlns:android="http: //schemas.android.com/apk/res/android"
xmlns: app="http://schemas,android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android: layout_width="match_parent"
android: layout_height="match_parent”
tools: context="com.example.androidclarified.serviceapp.MainActivity">
<LinearLayout
android: layout_width="wrap_content"
android: layout_centerInParent="true"
android: layout_height="wrap
content"
android: orientation="horizontal">
<Button
android: id="@+id/start_button”
android: layout_margin="2@dp"
android:text="Start Service"
android: layout_width="wrap_content"
android: layout_height="wrap_content"/>
<Button
android: layout_width="wrap_content"
android: text="Stop Service"
android: layout_margin="2@dp"
android: id="@+id/stop_button”
android: layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
¢ Now we have to initialize both the buttons and add click listeners. This is how our activity class will
look now
* Starting the service is similar to starting any other activity. We just need to create an Intent object
specifying the service and then call startService() .
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button startButton, stopButton;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Mobile Application Development 5.22 Activity and Multimedia with Databases
setContentView(R.layout.activity_main);
startButton = (Button)findViewById(R.id.start_button);
stopButton = (Button)findViewById(R.id.stop_button);
startButton.setOnClickListener(this);
stopButton. setOnClickListener (this);
}
@Override
public void onClick(View v){
Intent intent = newIntent(this, MyService.class);
switch(v.getId()){
case R.id.start_button:
startService(intent);
break;
case R.id.stop_button:
stopService(intent);
break;

en) ANDROID SYSTEM ARCHITECTURE


The Android operating system follows a layered architecture approach. All these layers are
responsible for different roles and features that we have discussed below.
Linux Kernel:
This layer is the foundation of the Android Platform.
It contains all low level drivers for various hardware components support.
Android Runtime relies on Linux Kernel for core system services like, Memory, process management,
threading etc., Network stack, Driver model, Security and more.
Hardware Abstraction Layer (HAL)
Provides Abstraction between hardware and rest of the software stack.
HAL can make Android port on different platforms more simply.
Android Runtime (ART):
Designed to run apps in a constrained environment that has limited muscle power in terms of
battery, processing and memory.
Mobile Application Development 5.23 Activity and Multimedia with Databases

Since Android 5.0, each app runs in its own process within its own instance of ART virtual machine,
which makes process management more crucial.
ART uses DEX files, which is a type of bytecode, specially designed for Android, which helps ART to
manage memory more efficiently. It contains set of core libraries that enables developers to write
Android Apps using Java Programming. Prior to Android 5.0, Dalvik was used as Android runtime.
ART is capable of both Ahead-Of-Time (AOT) and Just-In-Time (JIT) compilation. It also has a very
efficient garbage collection.
4. Libraries
It exposed to developers through Android Application Framework. It contains C/C++ libraries used
by components of Android Systems.
Few features include,
(i) SQLite Library used for data storage and light in terms of mobile memory footprints and task
execution.
(ii) WebKit Library mainly provides Web Browsing engine and a lot more related features.
(iii) The surface manager library is responsible for rendering windows and drawing surfaces of
various apps on the screen.
(iv) The media framework library provides media codecs for audio and video,
(v) The OpenGL (Open Graphics Library) and SGL (Scalable Graphics Library) are the graphics
libraries for 3D and 2D rendering, respectively.
(vi) The FreeType Library is used for rendering fonts.
Application Framework:
It is a collection of APIs written in Java, which gives developers access to the complete feature set of
Android OS.
Developers have full access to the same framework APIs used by the core applications, so that they
can enhance more in terms of functionalities of their application.
Enables and simplify the reuse of core components and services, like:
(i) Activity Manager: Manages the Lifecycle of apps and provide common navigation back stack.
(ii) Window Manager: Manages windows and drawing surfaces, and is an abstraction of the
surface manager library.
(iii) Content Providers: Enables application to access data from other applications or to share their
own data i.e it provides mechanism to exchange data among apps.
(iv) View System: Contains User Interface building blocks used to build an application's UI,
including lists, grids, texts, boxes, buttons, etc. and also performs the event management of UI
elements(explained in later tutorials).
(v) Package Manager: Manages various kinds of information related to the application packages
that are currently installed on the device.
(vi) Telephony Manager: Enables app to use phone capabilities of the device.
(vii) Resource Manager: Provides access to non-code resources (localized Strings, bitmaps, Graphics
and Layouts).
(viii) Location Manager: Deals with location awareness capabilities.
(ix) Notification Manager: Enable apps to display custom alerts in the status bar.
6. Applications:
Top of the Android Application Stack, is occupied by the System apps and tonnes of other Apps that
users can download from Android's Official Play Store, also known as Google Play Store.
A set of Core applications are pre-packed in the handset like Email Client, SMS Program, Calendar,
Maps, Browser, Contacts and few more.
This layer uses all the layers below it for proper functioning of these mobile apps.
So as we can see and understand, Android holds layered or we can say grouped functionalities as
software stack that makes Android work very fluently in any device.
Mobile Application Development 5.24 Activity and Multimedia with Databases

wi) MULTIMEDIA FRAMEWORK


« The android multimedia system includes multimedia applications, multimedia frameworks,
OpenCore engine and hardware abstract for audio/video input/output devices, And the goal of the
android multimedia framework is to provide a reliable interface for Java services.
e The multimedia framework consists of several core dynamic libraries such as libmediajni, libmedia,
libmediaplayservice and so on. A general multimedia framework architecture is shown in the below
figure.

Java Class of Media

Media JNI

Native C Library

Media Server
Media Media
Player Recorder ———_

| Media | Media PV PV
Player Recorder Player Author

Fig. 5.6: Android Multimedia Framework Architecture


« From the figure, Java classes call the Native C library Libmedia through Java JNI(Java Native
Interface). Libmedia library communications with Media Server guard process through Android's
Binder IPc (inter process communication) mechanism.
Android.widget. VideoView

! '
Android. media.MediaPlayer Android. View.Surface

,
Libmedia_jni

:
Libmedia

|
MediaPlayer Service Surface Flinger Audio Flinger

re Overlay
Vorbis Midi PV
Player Player Player

|
Packet Video Framework (OpenCore)

Ror re Video Plane Audio Driver

Fig. 5.7: Android hierarchy inheritance of multimedia


Mobile Application Development 5,25 Activity and Multimedia with Databases
e Media Server process creates the corresponding multimedia service according to the Java
multimedia applications.
« The whole communication between Libmedia and Media Server forms a Client/Server model.
¢ The hierarchy inheritance of multimedia is shown in Fig. 5.7.
e From the above Fig. 5.7, we can see that the typical video/audio data stream works in Android as
follows. Particularly, Java applications first set the URI of the media (from file or network) to
PVPlayer through Java framework, JNI and Native C. In this process, there are no data stream flows.
e Then PVPlayer processes the media data stream with the steps: demux the media data to separate
video/audio data stream, decode video/audio data, sync video.audio time, send the decoded data out.
* The below is the description of media codec/format, container and network protocol supported by
the Android platform.
1, Container: The audio file format is a file for storing digital audio data on a system. This data can
be manipulated to reduce the size or change the quality of the audio. It is a kind of container to
store audio information.
2. Audio Format: Any format or codec can be used including the ones provided by Android or those
which are specific devices. However it is recommended to use the specified file formats as per
devices.
3. Network Protocol: The following protocols are supported in audio and video playback:
e RTSP(RTP,SDP)
e HTTP/HTTPS progressive streaming
* HTTP/HTTPS live streaming draft protocol
MPEG-2 TS media files only.
86

Protocol version 3 (Android 4.0 and above)


0

Protocol version 2(Android 3.x)


oo

Not supported before Android 3.0


[EGF pray aupio AND vIDEo
« The Android multimedia framework includes support for playing variety of common media types, so
that we can easily integrate audio, video and images into our applications.
Play Audio
¢ The following classes are used to play sound and video in the Android framework:
1. MediaPlayer: This class is the primary API for playing sound and video.
2. AudioManager: This class manages audio sources and audio output on a device.
Manifest Declarations:
* Before starting development on our application using MediaPlayer, make sure our manifest has the
appropriate declarations to allow use of related features.
e Internet Permission: If we are using MediaPlayer to stream network-based content, our application
must request network access.
<uses-permissionandroid: name="android. permission. INTERNET"/>
¢ Wake Lock Permission: If our player application needs to keep the screen from dimming
or the processor from sleeping, or uses the MediaPlayer.setScreenOnWhilePlaying() or
MediaPlayer.setWakeMode() methods, you must request this permission.
<uses-permissionandroid:name="android.permission.WAKE_LOCK"/>
Basic MediaPlayer Tasks:
e® Here, are the basic tasks that MediaPlayer needs to handle:
1. Load a media file for playback: This is done with the methods setDataSource(), prepare(),
and prepareAsync().
2. Start playback / Play audio: This is handled by start(.
Mobile Application Development 5.26 Activity and Multimedia with Databases

3. Pause playback (once playback has started): This is handled by pause().


4. Stop playback and reset the MediaPlayer, so that you can load another media file into it: This
is handled by reset().
5. Find the length of a song (in ms): This is handled by getDuration(.
6. Find what part of the song is playing: This is handled by getCurrentPosition().
7. Jump to a specific time position (in ms) in the song and play from there: This is handled
by seekTo(position).
8. Check to see if audio is being played back right now: This is handled by isPlaying().
9. Find out when a song is done playing: This is handled by attaching a MediaPlayer.
OnCompletionListener. Our code will get an onCompletion() callback from the listener.
10. Deallocate resources used by the player: This is handled by release(), which releases all the
resources attached to the player. After being released the player is no longer usable.
Example:
XML File:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http: //schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools”
android: id="@+id/activity_main"
android: layout_width="match_parent”
android: layout_height="match_parent"
android: paddingBottom="@dimen/activity_vertical_margin"
android: paddingLeft="@dimen/activity_horizontal_margin"
android: paddingRight="@dimen/activity_horizontal_margin"
android: paddingTop="@dimen/activity_vertical_margin"
tools: context="com,.aasemjs.audioplayer.MainActivity">
<LinearLayout
android: orientation="vertical"
android: layout_width="match_parent"
android: layout_height="match_parent”
android: layout_centerHorizontal="true"
android: layout_alignParentTop="true">
<Button
android:text="Play"
android: layout_width="match_parent”
android: layout_height="wrap_content™
android: id="@+id/btnPlay”
android: onClick="playSong” />
<Button
android: text="Pause"
android: layout_width="match_parent"
android: layout_height="wrap_content”
android: id="@+id/btnPause"
android: onClick="pauseSong" />
<Button
android: text="Stop”
android: layout_width="match_parent”
android: layout_height="wrap_content”
android: id="@+id/btnStop"
android:onClick="stopSong" />
</LinearLayout>
</RelativeLayout>
Mobile Application Development 5.27 Activity and Multimedia with Databases

Adding the demo sound file to our app


Once, we are done with our interface, we have to add the audio file to our project.
We have to add the files to the raw folder. We can find it here app > res > raw. If there is no raw
folder then create it by right-clicking on res + new - directory. Give the directory the name raw,
and nothing else.
Inside this directory, all our audio files will be present. We can not simply drag and drop files here,
we have to copy our source file, then right-click on the raw directory and click paste. The following
popup will appear.
eoe Copy
Copy file /Users/aasem)s /Dow—-_Far_from_Home_DFA_remix[(www.MP3Fiber.com]-2.mp3

New name: | abcd|mp3 ]


To directory: sers/aasemjs /AndroidStudioProjects /AudioPlayer/app/src/main/res/ raw We
Use “Space for path completion

. GT
_Conc et
We have to make sure that the new name you are giving contains all small alphabets. The only valid
characters for the name in any file will be [a-z; 0-9; _].
If another popup comes asking you to verify the file type, then select the option text. As long as we
have given the correct file type in the name, Android will compile it as the file type we specified, mp3
in this case.
Why are special characters not allowed in Android File Names?
Special characters are not allowed, except the underscore symbol. This is because each file inside the
folder is translated into java field name inside R.java class:
drawable/icon.png -> R.drawable.icon
And since special characters are not allowed in Java names, they can’t be used. As for the capital
letters, theories suggest that it is made so because of Linux and Windows.
Linux treats icon.png and Icon.png as two different files and Windows treats it as one file. So to
avoid any compile time error, we aren't allowed to use capital letters either in file names.
Add at least two audio files to our project, once we are done with that, we can start writing the code
in MainActivity.java file.
Coding the Functionality:
As with all apps, we begin our coding in Java. First, we need to instantiate the MediaPlayer class. This
will create an object of the class:
MediaPlayer mp;
What is basically happening here is that we have created an object mp of the class MediaPlayer. This
means that all the properties of the class MediaPlayer are stored in this object.
Once we instantiate the MediaPlayer class, the package android.media.MediaPlayer will get
automatically added to our code. If it doesn’t then do it anywhere near the other imports like this:
import android.media.MediaPlayer;
Adding the Audio File to this Object:
We want this code to run as soon as the app launches. So we'll place it in the onCreate function:
mp = MediaPlayer.create(this, R.raw.abc);
Just make sure that instead of ‘abc’ we mention the name we had given to our file. We don't need to
add ‘.mp3’ or ‘.wav’ or whatever filetype we are using.
Playing the Sound:
Now we have to define the function we are calling when we hit the play button. MediaPlayer has an
inbuilt function called start(). We will use that to our advantage.
Mobile Application Development 5.28 Activity and Multimedia with Databases

public void playSong(View v){


mp.start();
}
Now, if everything is in order then the audio file would start playing.
Pausing the Sound:
If instead of some sound effect, we added a full-length song then we have to add a way to pause the
song.
Fortunately, MediaPlayer has an inbuilt function called pause( ) which we will run when we hit the
pause button.
public void pauseSong(View v) {
mp.pause();
}
Now, if everything is in order then the audio file would pause. Hitting up the Play button will start
the file from where it was paused.
Stopping the Sound:
Stopping the file will completely stop the file and we won't be able to run it again.
MediaPlayer has an inbuilt function called stop(),
public void stopSong(View v) {
mp.stop();
}
Now when we hit the Play button again, nothing happens. This is because the MediaPlayer object has
been cleared. There is no file present in the object anymore. So in the same function, add another
line of code.
mp = MediaPlayer.create(this, R.raw.abcd);
This time, add the second file name to avoid confusion.
Run our app to test it. If we have forgotten how to set up our virtual device, then refresh our memory
by going through the post again.
Note: The files are stored in the app, so if we add audio files of size larger than 100mb, then our app
size would be larger than 100mb.
Java File:
package com.aasemjs.audioplayer;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android. view. View;
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp=MediaPlayer.create(this, R.raw.abc);
}
public void playSong(View v){
mp.start();
}
public void pauseSong(View v) {
mp.pause();
}
Mobile Application Development 5.29 Activity and Multimedia with Databases
public void stopSong(View v) {
mp.stop();
mp=MediaPlayer.create(this, R.raw.abcd);

}
Example of Video:
File Structure:

@ @ comandroic_AndroidVideoPiayer
» @ AndroidVideoPtayer
java
» B® gen (Generated Java Files]
© mk Android Dependencies

Java File:
packagecom.
android. AndroidVideoPlayer ;
import android.app.Activity;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.
view. SurfaceView;
import android.view. View;
import android.widget .Button;
import android.widget .VideoView;
//Implement SurfaceHolder interface to Play video
//Implement this interface to receive information about changes to the surface
public class AndroidVideoPlayer extends Activity implementsSurfaceHolder.Callback{
MediaPlayer mediaPlayer;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean pausing = false;;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonPlayVideo = (Button)findViewById(R.id.playvideoplayer);
getWindow( ).setFormat(PixelFormat.UNKNOWN);
//Displays a video file.
VideoView mVideoView = (VideoView) findViewById(R.id.videoview) ;
Mobile Application Development 5.30 Activity and Multimedia with Databases

String uriPath = "android.resource://com.android.AndroidVideoPlayer/"+R.raw.k;


Uri uri = Uri.parse(uriPath);
mVideoView.setVideoURI
(uri);
mVideoView.requestFocus();
mVideoView.start();
buttonPlayVideo. setOnClickListener(newButton.OnClickListener(){
@Override
public void onClick(View v) {
// VideoView refference see main.xml
VideoView mVideoView = (VideoView)findViewById(R.id.videoview);
String uriPath = “android.resource:
//com.android.AndroidVideoPlayer/"+R.raw.k;
Uri uri = Uri.parse(uriPath);
mVideoView. setVideoURI (uri);
mVideoView.requestFocus();
mVideoView.start();
}})3
}
@Override
public void surfaceChanged(SurfaceHolder holder, intformat, intwidth,
int height) { // TODO Auto-generated method stub

}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub

}
XML File : main.xml
e Define VideoView as xml element to play video on activity.
<?xml version="1.6"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android”
android:orientation="vertical"
android: layout_width="fill_parent”
android: layout_height="fill_parent”
>

<TextView
android: layout_width="fill_parent”
android: layout_height="wrap_content"
android: text="@string/hello"
>
<Button
android: id="@+id/playvideoplayer"
android: layout_width="fill_parent”
android: layout_height="wrap_content"
android:text="- PLAY Video -"
/>
Mobile Application Development 5.31 Activity and Multimedia with Databases
<VideoView
android: id="@+id/videoview"
android: layout_width="fill_parent”
android: layout_height="wrap_content”
/>
</LinearLayout>
XML File: AndroidManifest.xml
<?xml version="1.6"encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.AndroidVideoPlayer"
android: versionCode="1"
android: versionName="1.0">
<uses-sdk android:minSdkVersion="16"/>
<application android: icon="@drawable/icon"android: label="@string/app_name">
<activityandroid:name=".AndroidVideoPlayer"
android: label="@string/app_name">
<intent-filter>
<action android: name="android.intent.action.MAIN"/>
<category android:name="android.
intent. category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
“a TEXT TO SPEECH
* Text to speech (TTS) makes an android device read the text and convert it to audio out via the
speaker. Android TTS supports multiple languages.
e TTS is a simple but powerful feature. It can also be effectively used in mobile APPs dedicated to
visually impaired people or in educational app for kids or can be used in pronunciation learning app,
etc.
e These are some of the ways wecan use TTS. Using TextToSpeech enhances interaction between the
user and the mobile application.
e Android TTS was available from version 1.6. It has features to control speed, pitch of speech as well as
type of language.
Example:
activity_main.aml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http: //schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android: layout_width="match_parent"
android: layout_height="match_parent"
android: gravity="center"
android: orientation="vertical”
android: paddingLeft="20dp"
android: paddingRight="2@dp"
tools: context=".MainActivity">
<TextView
android:id="@+id/textView"
Mobile Application Development 5.32 Activity and Multimedia with Databases

android: layout_width="match_parent"
android: layout_height="wrap_
content”
android: layout_marginBottom="5@dp"
android: gravity="center_horizontal"
android:text="Android Text to Speech (TTS) Demo"
android: textAppearance="@style/TextAppearance.AppCompat -Headline"/>
<EditText
android:id="@+id/et"
android: layout_width="match_parent"
android: layout_height="wrap_content”
android: background="@drawable/edit_text_style"
android:hint="Enter the text here"
android: paddingBottom="18dp"
android: paddingLeft="10dp"
android: paddingRight="1@dp"
android: paddingTop="16dp"/>
<Button

android:id="@+id/btn"
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: layout_marginVertical="16dp"
android:elevation="@dp"
android: paddingHorizontal="3@dp"
android:text="Click to convert text to speech"/>
</LinearLayout>
MainActivity.java
import android.speech.tts.TextToSpeech;
import android. support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android. view.View;
import android.widget .Button;
import android.widget .EditText;
import android.widget.Toast;
import java.util.Locale;
public class MainActivity extends AppCompatActivity{
private TextToSpeech textToSpeech;
private Button btn;
private EditText editText;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate({savedInstanceState);
setContentView(R.layout.activity_main);
btn =(Button) findViewById(R.id.btn);
editText =(EditText) findViewById({R.id.et);
textToSpeech
=newTextToSpeech(getApplicationContext(),newTextToSpeech.OnInitListener(){
@0verride
public void onInit(int status){
Mobile Application Development 5.33 Activity and Multimedia with Databases
if(status ==TextToSpeech.SUCCESS){
int ttsLang = textToSpeech.setLanguage(Locale.US);
if(ttsLang ==TextToSpeech.LANG_MISSING DATA
|| ttsLang ==TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("TTS","The Language is not supported!");
Jelse{
Log.i("TTS", "Language Supported.");
}
Log.i("TTS", "Initialization success.");
yelse{
Toast.makeText(getApplicationContext(),"TTS Initialization
failed!",Toast.LENGTH_SHORT).show();
}
}
})3
btn. setOnClickListener(newView.OnClickListener(){
@Override
public void onClick(View arg9){
String data = editText.getText().toString();
Log.i("TTS", "button clicked: "+ data);
int speechStatus = textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH,null1);
if(speechStatus ==TextToSpeech.ERROR){
Log.e("TTS","Error in converting Text to Speech!");
}
}
Hs
}
@Override
public void onDestroy(){
super.onDestroy();
if(textToSpeech !|=null){
textToSpeech.stop();
textToSpeech. shutdown();
}
}
}
Output:
Lad 7 aes

TextToSpeechDemo

Android Text to Speech (TTS)


Demo
Mobile Application Development 5.34 Activity and Multimedia with Databases

[mC SENSOR
e Most Android-powered devices have built-in sensors that measure motion, orientation, and various
environmental conditions.
* These sensors are capable of providing raw data with high precision and accuracy, and are useful if
we want to monitor three-dimensional device movement or positioning, or we want to monitor
changes in the ambient environment near a device.
e The Android platform supports following three broad categories of sensors:
1. Motion Sensors: These sensors measure acceleration forces and rotational forces along three
axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector
sensors.
Environmental sensors: These sensors measure various environmental parameters, such as
ambient air temperature and pressure, illumination, and humidity. This category includes
barometers, photometers, and thermometers.
3. Position sensors: These sensors measure the physical position of a device. This category includes
orientation sensors and magnetometers.
e Following table lists Sensor types supported by the Android platform.
Sr. Common
nsor Type Description
No. fants Uses
1. | TYPE_ACCELEROMETER Hardware | Measures the acceleration force in | Motion
m/s2 that is applied to a device on all | detection
three physical axes (x, y, and 2), | (shake, _ tilt,
including the force of gravity. etc.).

2. | TYPE_AMBIENT_TEMPERATURE | Hardware | Measures the ambient room | Monitoring air


temperature in degrees Celsius (°C). | temperatures.

3, | TYPE_GRAVITY Software | Measures the force of gravity in | Motion


or m/s2 that is applied to a device on all | detection
Hardware | three physical axes (x, y, 2). (shake, tilt,
etc.).

4, | TYPE_GYROSCOPE Hardware | Measures a device's rate of rotation | Rotation


in rad/s around each of the three | detection
physical axes (x, y, and 2). (spin, turn,
etc.).

5. | TYPE_LIGHT Hardware | Measures the ambient light level | Controlling


(illumination) in lx. screen
brightness,

6. | TYPE_LINEAR_ACCELERATION | Software | Measures the acceleration force in | Monitoring


or m/s2 that is applied to a device on all | acceleration
Hardware | three physical axes (x, y, and 2), | along a single
excluding the force of gravity. axis.
7. | TYPE_MAGNETIC_ FIELD Hardware | Measures the ambient geomagnetic | Creating a
field for all three physical axes | compass.
(x, y, z) in pT.
Contd_.
Mobile Application Development 5.35 Activity and Multimedia with Databases

8. TYPE_ORIENTATION Software Measures degrees of rotation that a Determining


device makes around all three device
physical axes (x, y, z). As of API level position.
three we can obtain the inclination
matrix and rotation matrix for a
device by using the gravity
sensor and the geomagnetic field
sensor in conjunction with the
getRotationMatrix() method.

TYPE_PRESSURE Hardware Measures the ambient air pressure in Monitoring air


hPa or mbar. pressure
changes.

10. TYPE_PROXIMITY Hardware Measures the proximity of an object Phone


in cm relative to the view screen of a position
device. This sensor is typically used during a call.
to determine whether a handset is
being held up to a person's ear.

11, TYPE_RELATIVE_HUMIDITY Hardware Measures the relative ambient Monitoring


humidity in percent (%). dewpoint,
absolute, and
relative
humidity.

12. TYPE_ROTATION_VECTOR Software Measures the orientation of a device Motion


or by providing the three elements of detection and
Hardware the device's rotation vector. rotation
detection.

13. TYPE_TEMPERATURE Hardware Measures the temperature of the Monitoring


device in degrees Celsius (°C). temperatures.
This sensor implementation varies
across devices and this sensor
was replaced with the
TYPE_AMBIENT_TEMPERATURE
sensor in API Level 14.

EsCs8 Sensor Framework


We can access these sensors and acquire raw sensor data by using the Android sensor framework.
The sensor framework is part of the android. hardware package and includes the following classes
and interfaces:
SensorManager:
We can use this class to create an instance of the sensor service. This class provides various methods
for accessing and listing sensors, registering and unregistering sensor event listeners, and acquiring
orientation information. This class also provides several sensor constants that are used to report
sensor accuracy, set data acquisition rates, and calibrate sensors.
Mobile Application Development 5.36 Activity and Multimedia with Databases

2. Sensor:
* Wecan use this class to create an instance of a specific sensor. This class provides various methods
that let determine a sensor's capabilities.
3. SensorEvent:
« The system uses this class to create a sensor event object, which provides information about a sensor
event. A sensor event object includes the information: the raw sensor data, the type of sensor that
generated the event, the accuracy of the data and the timestamp for the event.
4, SensorEventListener:
e Wecan use this interface to create two callback methods that receive notifications, (sensor events)
when sensor values change or when sensor accuracy changes.
AsyncTask
Android AsyncTask isan abstract category provided by android which provides United States the
freedom to perform significant tasks within the background and keep the UI thread lightweight thus
making the application more responsive.
e Android application runs on one thread once launched. because ofthis single thread model tasks
that take longer time to fetch the response can make the application non-responsive.
¢ To avoid thiswe have a tendency touse Android AsyncTask to perform the significant tasks in
background ona dedicatedthread and passing the results back to the UI thread. Hence use of
AsyncTask in android application keeps the UI thread responsive at all times.
e The basic methods used in an android AsyncTask class are defined below :
1. doInBackground(): This method contains the code which needs to be executed in background. In
this method we can send results multiple times to the UI thread by publishProgress() method. To
notify that the background processing has been completed we just need to use the return
statements
2, onPreExecute(): This method contains the code which is executed before the background
processing starts
3. onPostExecute(): This method is called after dolnBackground method completes processing.
Result from doInBackground is passed to this method
4, onProgressUpdate(): This method receives progress updates from doInBackground method,
which is published via publishProgress method, and this method can use this progress update to
update the UI thread
e The three generic types used in an android AsyncTask class are given below:
1. Params: The type of the parameters sent to the task upon execution
2. Progress: The type of the progress units published during the background computation
3. Result: The type of the result of the background computation
Example:
Activity_main.x.ml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android: layout_width="match_parent”
android: layout_height="match_parent”
tools:context=".MainActivity" >
<TextView
android: id="@+id/tv_time"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: textSize="1@pt"
Mobile Application Development 5.37 Activity and Multimedia with Databases

android: textColor="#444444"
android: layout_alignParentLeft="true"
android: layout_marginRight="9dip"
android: layout_marginTop="2@dip"
android: layout_marginLeft="1@dip"
android:text="Sleep time in Seconds:"/>
<EditText
android: id="@+id/in_time"
android: layout_width="15@dip"
android: layout_height="wrap_content"
android: background="@android:drawable/editbox_background"
android: layout_toRightOf="@id/tv_time"
android: layout_alignTop="@id/tv_time”
android: inputType="number”
/>
<Button
android: id="@+id/btn_run”
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android:text="Run Async task"
android: layout_below="@+id/in_time"
android: layout_centerHorizontal="true"
android: layout_marginTop="64dp" />
<TextView
android: id="@+id/tv_result"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: textSize="7pt"
android: layout_below="@+id/btn_run"
android: layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android. view. View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText time;
private TextView finalResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savediInstanceState);
setContentView(R.layout.activity_main);
time = (EditText) findViewById(R.id.in_time);
Mobile Application Development 5.38 Activity and Multimedia with Databases

button = (Button) findViewById(R.id.btn_run);


finalResult = (TextView) findViewById(R.id.tv_result);
button. setOnClickListener(new View.OnClickListener() {
@0verride
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String sleepTime = time.getText().toString();
runner.execute(sleepTime);
}
})3
}
private class AsyncTaskRunner extends AsyncTask<String, String, String>{
private String resp;
ProgressDialog progressDialog;
@Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[@])*1080;
Thread. sleep(time) ;
resp = "Slept for " + params[@] + seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
“Wait for “+time.getText().toString()+ seconds”);
}
@0verride
protected void onProgressUpdate(String... text) {
finalResult.setText(text[@]);
Mobile Application Development 5.39 Activity and Multimedia with Databases

Output:

ProgressDiaiog

PREe AUDIO CAPTURE


e The Android multimedia system framework includes support for capturing and encoding variety of
common audio formats, so we will simply integrate audio into our applications. We can record
audio using the MediaRecorder APIs if supported by the device hardware.
Performing Audio Capture:
1. Create a new instance of android.media.MediaRecorder.
Set the audio source using MediaRecorder.setAudioSource(). We will probably want to
N

use MediaRecorder.AudioSource.MIC.
Set output file format using MediaRecorder.setOutputFormat().
Ww OI nnaw

Set output file name using MediaRecorder.setOutputFile().


Set the audio encoder using MediaRecorder.setAudioEncoder().
Call MediaRecorder.prepare() on the MediaRecorder instance.
To start audio capture, call MediaRecorder.start().
To stop audio capture, call MediaRecorder.stop().
When we are done with the MediaRecorder instance, call MediaRecorder-release() on it.
Calling MediaRecorder.release() is always recommended to free the resource immediately.
Example: Record audio and play the recorded audio: The example class below illustrates how to set up,
start and stop audio capture, and to play the recorded audio file.
*
/
*
The application needs to have the permission to write to external storage
a
if the output file is written to the external storage, and also the
* permission to record audio. These permissions must be set in the
* application's AndroidManifest.xml file, with something like:
*

* <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


*
<uses-permission android:name="android.permission.RECORD_AUDIO" />
*

*/
package com.android.audiorecordtest;
import android.app.Activity;
import android.widget.LinearLayout;
import android.os.Bundle;
import android.os. Environment;
import android. view. ViewGroup;
import android.widget.Button;
import android. view. View;
import android. view. View.OnClickListener;
import android. content.Context;
Mobile Application Development 5.40 Activity and Multimedia with Databases
import android.util.Log;
import android.media.MediaRecorder;
import android.media.MediaPlayer;
import java.io. IOException;
public class AudioRecordTest extendsActivity
{
private static finalString LOG_TAG ="AudioRecordTest";
private static String mFileName =null;
private RecordButton mRecordButton =null;
private MediaRecorder mRecorder =null;
private PlayButton mPlayButton =null;
private MediaPlayer mPlayer =null;
private void onRecord(boolean start){
if(start){
startRecording();
felse{
stopRecording();
}
}
private void onPlay(boolean start){
if(start){
startPlaying();
jelse{
stopPlaying();
}
}
private void startPlaying(){
mPlayer =newMediaPlayer();
try{
mP layer. setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
}catch(IOException e){
Log.e(LOG_TAG,"prepare() failed");
}
}
private void stopPlaying(){
mPlayer.release();
mPlayer =null;
}
private void startRecording(){
mRecorder =newMediaRecorder();
mRecorder. setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder. setOutputFormat (MediaRecorder.OutputFormat.THREE_GPP);
mRecorder. setOutputFile(mFileName) ;
mRecorder. setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try{
mRecorder.prepare();
}eatch( IOException e){
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
Mobile Application Development 5.41 Activity and Multimedia with Databases
private void stopRecording(){
mRecorder.stop();
mRecorder.release();
mRecorder =null;
}
class RecordButtonextendsButton{
boolean mStartRecording =true;
OnClickListener clicker =newOnClickListener(){
public void onClick(View v){
onRecord(mStartRecording);
if (mStartRecording){
setText ("Stop recording");
}else{
setText ("Start recording");
}
mStartRecording =!mStartRecording;
}
};
public RecordButton(Context ctx){
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButtonextendsButton{
boolean mStartPlaying =true;
OnClickListener clicker =newOnClickListener(){
public void onClick(View v){
onPlay(mStartPlaying);
if (mStartPlaying){
setText("Stop playing");
yelse{
setText("Start playing");
}
mStartPlaying =!mStartPlaying;
}
};
public PlayButton(Context ctx){
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public AudioRecordTest(){
mFileName =Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName +="/audiorecordtest.3gp";
}
@Override
public void onCreate(Bundle icicle){
super.onCreate(icicle);
LinearLayout 11 =newLinearLayout (this);
mRecordButton =newRecordButton(this);
11.addView(mRecordButton,
Mobile Application Development 5.42 Activity and Multimedia with Databases

newLinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams .WRAP_CONTENT,
@));
mPlayButton =newPlayButton(this);
11.addView(mPlayButton,
newLinearLayout.LayoutParams(
ViewGroup. LayoutParams.WRAP_CONTENT,
ViewGroup. LayoutParams.WRAP_CONTENT,
@));
setContentView(11);
}
@Override
public void onPause(){
super. onPause();
if(mRecorder !=null1){
mRecorder.release();
mRecorder =null;
}
if(mPlayer !=null){
mPlayer.release();
mPlayer =null;

}
}
[ERS] camera
There are two ways to integrate the camera module.
Using In-built Camera App:
The easiest way tointegrate camera feature is, use the in-built camera app that comes with the
device. To launch the camera app, we simply need to pass the acceptable intent with necessary flags.
Rest are taken care by the camera app andit'llcome back the information (image or video) to our
app. The disadvantage of this methodology is, we can not customize the camera interface as we
would be launching third party camera app.
Writing Custom Camera App:
Building our own camera module takes some effort as we would like to create everything from
scratch starting with user interface to integrating camera API (rending camera preview, toggling
front and back cameras, flash, focus etc.).
However the advantage up here is, we will be able to build the uniform camera UI which is able to be
same for all the users. We will be able to see custom camera in apps like Instagram, Facebook etc.,
Basics for Camera:
The Android framework supports capturing images and video through theCamera API or
camera Intent. Here are the relevant classes:
1. Camera: This class is the primary API for controlling device cameras. This class is used to take
pictures or videos when we are building a camera application.
2. SurfaceView: This class is used to present a live camera preview to the user.
3. MediaRecorder: This class is used to record video from the camera.
4. Intent: An intent action type of MediaStore. ACTION_IMAGE CAPTURE or MediaStore.
ACTION_VIDEO_CAPTURE can be used to capture images or videos without directly using
the Camera object.
Mobile Application Development 5.43 Activity and Multimedia with Databases

Before starting development on our application with the Camera API, we should make sure our
manifest has the appropriate declarations to allow use of camera hardware and other related
features.
1. Camera Permission: Our application must request permission to use a device camera.
<uses-permission android: name="android.permission.CAMERA” />
2, Camera Features: Our application must also declare use of camera features, for example:
<uses-feature android:name="android.hardware.camera" />
For a list of camera features, see the manifest Features Reference. Adding camera features to our
manifest causes Google Play to prevent our application from being installed to devices that do not
include a camera or do not support the camera features we specify. For more information about
using feature-based filtering with Google Play.
If our application can use a camera or camera feature for proper operation, but does not require it,
we should specify this in the manifest by including the android:required attribute, and setting it
to false:
<uses-feature android:name="android.hardware.camera" android:required="false" />
3. Storage Permission: If our application saves images or videos to the device's external storage (SD
Card), we must also specify this in the manifest.
<uses-permission android: name="android.permission.WRITE_EXTERNAL_STORAGE” />
4, Audio Recording Permission: For recording audio with video capture, our application must request
the audio capture permission.
<uses-permission android:name="android.permission.RECORD_AUDIO” />
5. Location Permission: If our application tags images with GPS location information, we must request
location permission:
<uses-permission android:name="android.permission.ACCESS
FINE LOCATION" />
Using Existing Camera Apps:
* A quick way to enable taking pictures or videos in our application without a lot of extra code is to use
an Intent to invoke an existing Android camera application.
* Acamera intent makes a request to capture a picture or video clip through an existing camera app
and then returns control back to our application. This section shows we how to capture an image or
video using this technique.
e The procedure for invoking a camera intent follows these general steps:
1. Compose a Camera Intent - Create an Intent that requests an image or video, using one of these
intent types:
(i) MediaStore.ACTION_IMAGE_CAPTURE: Intent action type for requesting an image from an
existing camera application.
(ii) MediaStore.ACTION_VIDEO_CAPTURE: Intent action type for requesting a video from an
existing camera application,
2. Start the Camera Intent: Use the startActivityForResult() method to execute the camera intent.
After we start the intent, the Camera application user interface appears on the device screen and the
user can take a picture or video.
3. Receive the Intent Result: Set up an onActivityResult() method in our application to receive the
callback and data from the camera intent. When the user finishes taking a picture or video (or
cancels the operation), the system calls this method.
Creating New Project:
1. Create a new project in Android Studio from File —- New Project and select Basic Activity from
templates.
Mobile Application Development 5.44 Activity and Multimedia with Databases

2. Open app/build.gradle and add Dexter dependency to request the runtime permissions.
app/build.gradle
dependencies {
implementation fileTree(dir: ‘libs', include: [**.jar'])
[Tf ves
// dexter runtime permissions
implementation 'com.karumi:dexter:4.2.0'
}
Add the below resources to respective strings.xml, colors.xml and dimens.xml
strings.xml
<resources>
<string name="app_name">Android Camera</string>
<string name="action_settings”>Settings</string>
<string name="preview_description">Image and Video preview will appear here</string>
<string name="btn_take_picture">Take Picture</string>
<string name="btn_record_video">Record Video</string>
</resources>
colors.xml
<?xml version="1.6" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#1fb49c</color>
<color name="colorPrimaryDark">#1fb49c< /color>
<color name="colorAccent" >#FF4081</color>
</resources>
dimens.xml
<resources>
<dimen name="activity_margin">16dp</dimen>
<dimen name="dimen_8">8dp</dimen>
</resources>
Underres, create a new folder namedxml. Inside xml folder, create a new xml file
name file_paths.xml
file_paths.xml
<?xml version="1.8" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
Open AndroidManifestxmland add CAMERA, WRITE_EXTERNAL_STORAGE and RECORD_AUDIO
permissions.
Here we also added camera feature that defines the rules to list the app on Playstore. If we
keep android:required="true”", Google Playstore won't let the users to install the app on the devices
that doesn’t have camera feature. Incase of false, the app will be listed but camera feature is
optional.
We also need <provider> tag to prepare the file paths properly across all the android platforms.
<uses-feature
android: name="android.hardware.camera"
android:required="false" />

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info. androidhive.androidcamera">
<uses-permission android: name="android.permission.CAMERA" />
Mobile Application Development 5.45 Activity and Multimedia with Databases
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android: name="android.permission.RECORD_AUDIO" />
<uses-feature
android: name="android.hardware.camera"
android: required="false" />
<application
android :allowBackup="true”
android: icon="@mipmap/ic_launcher"
android: label="@string/app_name"
android: roundIcon="@mipmap/ic_launcher_round"
android: supportsRtl="true"
android i theme="@style/AppTheme”>
<activity
android: name=".MainActivity"
android: label="@string/app_name"
android: theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android: name="android.intent.category.LAUNCHER"” />
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android: authorities="${applicationId}.provider"
android: exported="false”
android: grantUriPermissions="true">
<meta-data
android: name="android.support. FILE_PROVIDER_PATHS”
android: resource="@xml/file_paths” />
</provider>
</application>
</manifest>
6. Create a class named CameraUtils.javaand add the below methods. This is a helper class that
provides necessary methods that we need in our camera module.
(i) refreshGallery(): Refreshes the image gallery after taking a new picture or video so that they
will be instantly available in the gallery. In older android devices, gallery won't be refreshed
until the device is rebooted.
(ii) checkPermissions(): Checks whether all the permissions are granted or not. This would be
called before requesting the camera.
(iii) getOutputMediaFile(): Create a new file in gallery and returns the file. This reference will be
passed to camera intent so that newly taken image / video will be stored in this location.
(iv) optimizeBitmap(): Compresses the bitmap before displaying it on UI to avoid the OutOfMemory
exceptions.
CameraUtils.java
package info.androidhive.androidcamera;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android. content.pm.PackageManager;
import android. graphics .Bitmap;
Mobile Application Development 5.46 Activity and Multimedia with Databases

import android. graphics.BitmapFactory;


import android.media.MediaScannerConnection;
import android. net.Uri;
import android.os. Environment;
import android. provider .Settings;
import android. support.v4.app.ActivityCompat;
import android. support. v4. content. FileProvider;
import android. util.Log;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class CameraUtils {
/**

* Refreshes gallery on adding new image/video. Gallery won't be refreshed


* on older devices until device is rebooted
*/
public static void refreshGallery(Context context, String filePath) {
// ScanFile so it will be appeared on Gallery
MediaScannerConnection.scanFile(context,
new String[]{filePath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
})3
}
public static boolean checkPermissions(Context context) {
return ActivityCompat.checkSelfPermission(context, Manifest.permission. CAMERA)
== PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context,
Manifest. permission.WRITE_EXTERNAL_STORAGE) == PackageManager .PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO)
== PackageManager .PERMISSION_GRANTED;

/**

* Downsizing the bitmap to avoid OutOfMemory exceptions


*/
public static Bitmap optimizeBitmap(int sampleSize, String filePath) {
// bitmap factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = sampleSize;
return BitmapFactory.decodeFile(filePath, options);
}
/[**

* Checks whether device has camera or not. This method not necessary if
* android:required="true" is used in manifest file
*/
public static boolean isDeviceSupportCamera(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;

}
jt
Mobile Application Development 5.47 Activity and Multimedia with Databases

* Open device app settings to allow user to enable permissions

public static void openSettings(Context context) {


Intent intent = new Intent();
intent. setAction(Settings .ACTION_APPLICATION_DETAILS_SETTINGS) ;
intent.setData(Uri.fromParts("package", BuildConfig.APPLICATION_ID, null));
intent. setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public static Uri getOutputMediaFileUri(Context context, File file) {
return FileProvider.getUriForFile(context, context.getPackageName() +
“ provider", file);

* Creates and returns the image or video file before opening the camera

public static File getOutputMediaFile(int type) {


// External sdcard location
File mediaStorageDir = new File(
Environment. getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
MainActivity.GALLERY_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e(MainActivity.GALLERY_DIRECTORY_NAME, "Oops! Failed create "
+ MainActivity.GALLERY_DIRECTORY_NAME + " directory");
return null;
}
}
// Preparing media file naming convention
// adds timestamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale. getDefault()).format(new Date());
File mediaFile;
if (type == MainActivity.MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ “IMG_" + timeStamp + "." + MainActivity. IMAGE_EXTENSION) ;
} else if (type == MainActivity.MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + "." + MainActivity.VIDEO_EXTENSION);
} else {
return null;

return mediaFile;

}
7. Now open the layout files of main activity i.e activity_main.xml and content_main.xml and add the
below layout code. Here we are defining couple of Buttons, ImageView and VideoView to preview the
captured media.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android. support.design.widget.CoordinatorLayout
xmlns:android="http: //schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns: tools="http://schemas.android.com/tools”
android: layout_width="match_parent"
android: layout_height="match_parent"
tools: context=".MainActivity">
Mobile Application Development 5.48 Activity and Multimedia with Databases

<android.support.design.widget.AppBarLayout
android: layout_width="match_parent"
android: layout_height="wrap_content"
android: theme="@style/AppTheme. AppBarOverlay">
<android. support.v7.widget. Toolbar
android: id="@+id/toolbar"
android: layout_width="match_parent”™
android: layout_height="?attr/actionBarSize"
android: background="?attr/colorPrimary”
app: popupTheme="@style/AppTheme.PopupOverlay" />
</android. support .design.widget.AppBarLayout>
<include layout="@layout/content_main" />
</android.support.design.widget .CoordinatorLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools”
android: layout_width="match_parent"
android: layout_height="match_parent”
android: orientation="vertical"
android: padding="@dimen/activity_margin"
app: layout_behavior="@string/appbar_scrolling_view_behavior”
tools: context=".MainActivity"
tools: showIn="@layout/activity_main">
<LinearLayout
android: layout_width="match_parent"
android: layout_height="match_parent"
android: layout_marginBottom="@dimen/activity_margin"
android: layout_weight="1"
android: orientation="vertical">
<TextView
android: id="@+id/txt_desc”
android: layout_width="fill_parent"
android: layout_height="match_parent"
android: gravity="center"
android: padding="16dp"
android: text="@string/preview_description'
android: textSize="15dp" />
<!-- To display picture taken -->
<ImageView
android: id="@+id/imgPreview"
android: layout_width="match_parent”
android: layout_height="match_parent”
android: scaleType="centerCrop"
android: visibility="gone" />
<!-- To preview video recorded -->
<VideoView
android: id="@+id/videoPreview"
android: layout_width="match_parent"
android: layout_height="match_parent”
android: layout_gravity="center_horizontal"
android: visibility="gone" />
</LinearLayout>
<LinearLayout
android: layout_width="match_parent"
android: layout_height="wrap_content"
android: orientation="horizontal"
android: weightSum="2">
Mobile Application Development 5.49 Activity and Multimedia with Databases

<!-- Capture picture button -->


<Button
android: id="@+id/btnCapturePicture”
android: layout_width="@dp"
android: layout_height="wrap_content”
android: layout_marginRight="@dimen/dimen_8"
android: layout_weight="1"
android: background="@color/colorPrimary"
android: foreground="?attr/selectableItemBackground”
android: text="@string/btn_take_picture"
android: textColor="@android:color/white" />
<!-- Record video button -->
<Button
android: id="@+id/btnRecordVideo"
android: layout_width="@dp"
android: layout_height="wrap_content”
android: layout_marginLeft="@dimen/dimen_8"
android: layout_weight="1"
android: background="@color/colorPrimary"
android: foreground="?attr/selectableItemBackground"
android: text="@string/btn_record_video”
android: textColor="@android:color/white" />
</LinearLayout>
</LinearLayout>
8. Finally, open MainActivity.java and modify the code as shown below.
In onCreate(), the availability of the camera is checked using isDeviceSupportCamera() method and
activity is closed if the camera is absent on the device. On button click, checkPermissions() method is
used the check whether required permissions are granted or not. If not granted,
requestCameraPermission() method shows the permissions dialog to user. capturelmage() open the
camera app to capture the image. captureVideo() opens the camera app to record the video. Once the
media is captured, the image or video will be saved to gallery. previewCapturedImage()
and previewVideo() renders the captured image / video on the screen. showPermissionsAlert() shows
an alert dialog propting user to enable the permissions in app settings incase they are denied
permanently.
MainActivity.java
import android.Manifest;
import android. content.DialogInterface;
import android. content. Intent;
import android. graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android. provider .MediaStore;
import android. support.v7.app.AlertDialog;
import android. support.v7.app.AppCompatActivity;
import android. support.v7.widget.
Toolbar;
import android.
text. TextUtils;
import android. view. View;
import android.widget .Button;
import android. widget . ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android. widget .VideoView;
import com. karumi.dexter.Dexter;
Mobile Application Development 5.50 Activity and Multimedia with Databases
import com. karumi.dexter.MultiplePermissionsReport;
import com. karumi.dexter.PermissionToken;
import com. karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import java.io.File;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ff Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE 200;
/f key to store image path in savedInstance state
public static final String KEY_IMAGE_STORAGE
PATH = “image path";
public static final int MEDIA_TYPE_IMAGE 1;
public static final int MEDIA_TYPE_VIDEO =

hm
t
/f Bitmap sampling size
public static final int BITMAP_SAMPLE SIZE = 8;
‘f Gallery directory name to store the images or videos
public static final String GALLERY_DIRECTORY_NAME = "Hello Camera";
// Image and Video file extensions
public static final String IMAGE_EXTENSION = "jpg";
public static final String VIDEO_EXTENSION = “mp4";
private static String imageStoragePath;
private TextView txtDescription;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id. toolbar);
setSupportActionBar (toolbar) ;
// Checking availability of the camera
if (!CameraUtils.isDeviceSupportCamera(getApplicationContext())) {
Toast .makeText (getApplicationContext(),
“Sorry! our device doesn't support camera",
Toast. LENGTH_LONG) .show();
// will close the app if the device doesn't have camera
finish();
}
txtDescription = findViewById(R.id.txt_desc);
imgPreview = findViewById(R.id.imgPreview);
videoPreview = findViewById(R.id.videoPreview);
btnCapturePicture = findViewById(R.id.btnCapturePicture);
btnRecordVideo = findViewById(R.id.btnRecordVideo);
[**

* Capture image on button click


*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
@Override
Mobile Application Development 5.51 Activity and Multimedia with Databases

public void onClick(View v) {


if (CameraUtils.checkPermissions(getApplicationContext())) {
captureImage();
} else {
requestCameraPermission(MEDIA_TYPE_IMAGE);

}
})s

j**

* Record video on button click


*/
btnRecordVideo. setOnClickListener({new View.OnClickListener() {
@Override
public void onClick(View v) {
if (CameraUtils.checkPermissions(getApplicationContext())) {
captureVideo();
} else {
requestCameraPermission(MEDIA_TYPE_VIDEQ);

}
})s
// restoring storage image path from saved instance state
// otherwise the path will be null on device rotation
restoreFromBundle(savedInstanceState);
}
/**

* Restoring store image path from saved instance state


*/
private void restoreFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_IMAGE_STORAGE_PATH)) {
imageStoragePath = savedInstanceState.getString(KEY_IMAGE_STORAGE_PATH);
if (!TextUtils.isEmpty(imageStoragePath)) {
if
(imageStoragePath.substring(imageStoragePath. lastIndexOf(".")).equals("." +
IMAGE_EXTENSION)) {
previewCapturedImage();
} else if
(imageStoragePath. substring(imageStoragePath. lastIndexOf(".")).equals("." +
VIDEO_EXTENSION)) {
previewVideo();

}
/**

* Requesting permissions using Dexter library


*/
Mobile Application Development 5.52 Activity and Multimedia with Databases

private void requestCameraPermission(final int type) {


Dexter.withActivity(this)
-withPermissions(Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD
AUDIO)
-withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
if (type == MEDIA_TYPE_IMAGE) {
// capture picture
captureImage();
} else {
captureVideo();
}
} else if (report.isAnyPermissionPermanentlyDenied()) {
showPermissionsAlert();

}
@Override
public void onPermissionRationaleShouldBeShown
(List<PermissionRequest> permissions, PermissionToken token) {
token. continuePermissionRequest();
}
}) .check();
}
/**

* Capturing Camera Image will launch camera app requested image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = CameraUtils.getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (file != null) {
imageStoragePath = file.getAbsolutePath();
}
Uri fileUri = CameraUtils.getOutputMediaFileUri{getApplicationContext(), file);
intent. putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**

* Saving stored image path to saved instance state


*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super. onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState. putString(KEY_IMAGE_STORAGE_PATH, imageStoragePath);
Mobile Application Development 5.53 Activity and Multimedia with Databases
/**

* Restoring image path from saved instance state


*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super. onRestoreInstanceState(savediInstanceState);
// get the file url
imageStoragePath = savedInstanceState.getString(KEY_IMAGE_STORAGE_PATH);
}
/**

* Launching camera app to record video


*/
private void captureVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File file = CameraUtils.getOutputMediaFile(MEDIA_TYPE_VIDEO);
if (file != null) {
imageStoragePath = file.getAbsolutePath();
}
Uri fileUri = CameraUtils.getOutputMediaFileUri(getApplicationContext(), file);
// set video quality
intent. putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent. putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**

* Activity result method will be called after closing the camera


*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Refreshing the gallery
CameraUtils.refreshGallery(getApplicationContext(), imageStoragePath);
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast .makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
«show();
} else {
// failed to capture image
Toast .makeText (getApplicationContext(),
“Sorry! Failed to capture image", Toast.LENGTH_ SHORT)
-show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
Mobile Application Development 5.54 Activity and Multimedia with Databases
if (resultCode == RESULT_OK) {
// Refreshing the gallery
CameraUtils.refreshGallery(getApplicationContext(), imageStoragePath);
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast .makeText(getApplicationContext(),
“User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
-show();
}
}
}
/**

* Display image from gallery


*/
private void previewCapturedImage() {
try {
// hide video preview
txtDescription. setVisibility (View. GONE);
videoPreview. setVisibility (View. GONE) ;
imgPreview. setVisibility(View. VISIBLE);
Bitmap bitmap = CameraUtils .optimizeBitmap(BITMAP_SAMPLE_SIZE,
imageStoragePath);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**

* Displaying video in VideoView


*/
private void previewVideo() {
try {
// hide image preview
txtDescription. setVisibility(View.GONE) ;
imgPreview.setVisibility(View.
GONE);
videoPreview.setVisibility(View.
VISIBLE);
videoPreview. setVideoPath(imageStoragePath) ;
// start playing
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
Mobile Application Development 5.55 Activity and Multimedia with Databases
}
[**

* Alert dialog to navigate to app settings


* to enable necessary permissions
*/
private void showPermissionsAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Permissions required!")
.setMessage("Camera needs few permissions to work properly. Grant them
in settings.")
-setPositiveButton("GOTO SETTINGS", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Cameraltils.openSettings(MainActivity.this);
}
})
. setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();

}
« Runandtest the app on a real device. We can see the app working as shown in the demo screenshots.
we BLUETOOTH
* Android platform includes support for the Bluetooth framework that allows a device to wirelessly
exchange data with other Bluetooth devices.
* In android, Bluetoothis a communication network protocol, which allow a devices to connect
wirelessly to exchange the data with other Bluetooth devices.
« By using android Bluetooth API's in android applications, we can perform following functionalities.
Scan for the available Bluetooth devices within the range
Use local Bluetooth adapter for paired Bluetooth devices
WN

Connect to other devices through service discovery


Transfer data to and from other devices
We

Manage multiple connections


° To transfer the data between two Bluetooth devices, first they must establish a communication
channel using pairing process. The devices which we are going to pair must be discoverable and
should accept the incoming connection requests. Generally, the devices will find the discoverable
devices using aservice discovery process. Once the device accepts the pairing request, the two
devices will exchange a security keys to complete the bonding process and the devices will cache
these security keys for later use.
* Once the pairing and bonding process completes, the devices are ready to exchange the required
information. When the session is complete, the device that initiated the pairing request will release
the channel that linked to the discoverable device. The two devices remain bonded, so they can
reconnect automatically during a future session as long as they are in the range of each other.
Example:
activity_main.xml:
<RelativeLayoutxmlns: android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools”
Mobile Application Development 5.56 Activity and Multimedia with Databases

android: layout_width="match_parent"
android: layout_height="match_parent"
tools: context=".MainActivity”>
<TextView
android: id="@+id/text"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: textAppearance="?android: attr/textAppearanceLarge
android: text="@string/Text"/>
<LinearLayout
android: layout_width="match_parent"
android: layout_height="wrap_content”
android: orientation="horizontal"
android: layout_marginTop="3@dp">
<Button
android: id="@+id/turnOn"
android: layout_width="wrap_content"™
android: layout_height="wrap_content”
android: text="@string/on"/>
<Button
android: id="@+id/turnOff"
android: layout_width="wrap_content"
android: layout_height="wrap_content”
android: text="@string/off"/>
</LinearLayout>
<LinearLayout
android: layout_width="match_parent"
android: layout_height="wrap_content"
android: orientation="vertical"
android: layout_marginTop="8@dp">
<Button
android: id="@+id/paired"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: text="@string/List"/>
<Button
android: id="@+id/search”
android: layout_width="wrap_content"
android: layout_height="wrap_content”™
android: text="@string/Find"/>
<ListView
android: id="@+id/listView1"
android: layout_width="fill_parent"
android: layout_height="200@dp">
</ListView>
</LinearLayout>
</RelativeLayout>
strings.xml::
<?xml version="1.6" encoding="utf-8"?>
Mobile Application Development 5.57 Activity and Multimedia with Databases

<resou rces>

<s tring name="app_name" >BluetoothTest</string>


<s tring name="action_settings">Settings</string>
<s tring name="Text">Status: -</string>
<s tring name="on">Turn On</string>
<s tring name="off">Turn Off</string>
<s tring name="List">List paired Devices</string>
<s tring name="Find">Search new Devices / Cancel</string>
</reso urces>

MainActivity.java:
import android.os.Bundle;
import android.app.Activity;
import android. bluetooth.BluetoothAdapter;
import android. bluetooth.BluetoothDevice;
import android. content. BroadcastReceiver;
import android. content.Context;
import java.util.Set;
import android. content. Intent;
import android. content.IntentFilter;
import android. view. View;
import android. view.View.OnClickListener;
import android.widget .ArrayAdapter ;
import android. widget .Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
pri vate static final int REQUEST_ENABLE_BT = 1;
pri vate Button onBtn;
pri vate Button offBtn;
pri vate Button listBtn;
pri vate Button findBtn;
pri vate TextView text;
pri vate BluetoothAdapter myBluetoothAdapter;
pri vate Set<BluetoothDevice> pairedDevices;
pri vate ListView myListView;
pri vate ArrayAdapter<String> BTArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState);
setContentView(R. layout.activity_main);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
onBtn, setEnabled( false);
offBtn.setEnabled(false);
listBtn. setEnabled( false) ;
findBtn. setEnabled(false);
text.setText("Status: not supported");
Mobile Application Development 5.58 Activity and Multimedia with Databases
Toast .makeText (getApplicationContext(),"Our device does not support Bluetooth",
Toast. LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
onBtn = (Button) findViewById(R.id.turnOn);
onBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
y)3
offBtn = (Button)findViewById(R.id.turnOfFf);
offBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
of f(v);
}
})3
listBtn = (Button)findViewById(R.id.
paired);
listBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
})3
findBtn = (Button) findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
})3
myListView = (ListView) findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the
ListView
BTArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
myListView. setAdapter(BTArrayAdapter ) ;

}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast .makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG) .show();
Mobile Application Development 5.59 Activity and Multimedia with Databases

}
else{
Toast .makeText (getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");

}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast .makeText(getApplicationContext(),"Show Paired Devices",
Toast. LENGTH_SHORT) .show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device =
intent. getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device. getAddress());
BTArrayAdapter.notifyDataSetChanged(
);

hs
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver,new IntentFilter (BluetoothDevice.ACTION_FOUND));
Mobile Application Development 5.60 Activity and Multimedia with Databases

}
public void off(View view){
myBluetoothAdapter .disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG) .show() ;
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super .onDestroy();
unregisterReceiver(bReceiver);

}
® We have to declare the permissions in the AndroidManifest.xml file of our project. For this reason we
add BLUETOOTH permissionif we want to use any of the Bluetooth features. Also we should
add BLUETOOTH_ADMIN permission, in order to discover other devices.
e Open AndroidManifest.xml file and go to the respective xml tab.
AndroidManifest.xml
<?xml version="1.6"encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com. javacodegeeks.android.bluetoothtest"
android: versionCode="1"
android: versionName="1,.6">
<uses-sdk
android: minSdkVersion="8"
android: targetSdkVersion="19"/>
<uses-permissionandroid:name="android.
permission. BLUETOOTH"/>
<uses-permissionandroid:name="android.
permission. BLUETOOTH_ADMIN"/ >
<application
android: allowBackup="true"
android: icon="@drawable/ic_launcher"
android: label="@string/app_name"
android: theme="@style/AppTheme”>
<activity
android: name="com. javacodegeeks. android. bluetoothtest .MainActivity"
android: label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

</application>
</manifest>
Mobile Application Development 5.61 Activity and Multimedia with Databases

« Lets press “Turn On” button in order to activate Bluetooth. A popup window will be shown as we can
see below.
tate

An app wants to turn on


feof Gere ela

No Yes

al

« Ifwechoose “No” option the status will be “Disabled” as the Bluetooth will not be activated.
UR ee

Select “Yes” option and Bluetooth will be turned on.

i
gece eee
Mobile Application Development 5.62 Activity and Multimedia with Databases
Now click “List paired Devices”, in order to see the paired Bluetooth devices that we had been
connected in the past. We can see the list in the next picture. Also notice that the status is now
“Enabled” and a appropriate icon is appeared, because Bluetooth is active.
eer ie
Status: Enabled
TumOn Tum Off

List paired Devices


Search new Devices / Cancel
X10 mini
8C:64:22:17-45:44

ea we ile oy

If we click the “Search new Devices/Cancel” button, the list of the enabled Bluetooth devices will be
shown. If we press again the button, the discovery of these devices will be canceled.
Tee ee

Btatus: Enabled
TumOn Tum Off

List paired Devices

Search new Devices / Cancel


E2550
3C:88:FE:E9:D6:2D

Finally, press “Turn off” button. The Bluetooth is disabled and the default icon for Bluetooth is
disappeared, as we can see in the next image.
Te er ens
Status: Disconnected
Tum On Turn Off

List paired Devices

Search new Devices / Cancel

Bluetooth turned off

wim ANIMATION
Animation is the process of creating motion and shape change. Animation in android is possible
from many ways. In this section we will discuss one easy and widely used way of making animation
called tweened animation. Animations are useful when the screen changes state, ie when the
content loads or new actions become available.
Animation is the process of creating motion and shape change. In this Tutorial we will show how
simple animations encourage you to use them more freely and confidently.
Animations notify users about what's going on in our app and improve the mental model of our
app’s interface.
Mobile Application Development 5.63 Activity and Multimedia with Databases
Android defines following three types of animations:
1. View Animation:
This is the simplest animation used in Android. It define the properties of our Views that should be
animated using a technique called Tween Animation.
It take the following parameters i.e. size, time duration , rotation angle, start value , end value, and
perform the required animation on that object. We can execute the animation by specifying
transformations on our View. This can be done in XML resource files or programmatically.
Android View animation can make animation on any View objects, such as ImageView, TextView or
Button objects. View animation can only animate simple properties like position, size, rotation, and
the alpha property that allows us animate the transparency of a View.
The drawback of this mechanism is that it can only be applied to Views.
Property Animation:
This animation was introduced in Android 3.0 (API level 11). It allows the user to animate anything.
Property animations are highly customizable, we can specify the duration, the number of repeats,
the type of interpolation, and the frame rate of the animation. The Property Animation system is
always preferred for more complex animations.
Property animations allow us to animate any property of any object from one value to another over a
specified duration.
Let us take an example, imagine we wanted to animate the 3d rotation using the rotationX or
rotationY properties that were introduced in API 11. Or maybe you want to animate a color change or
animate the change of a drawable. This is not possible by using View Animations. For this purpose
Property Animation is used.
We are not limited by predefined animation types or by the type of object that we want to animate.
At first the usage of the Property Animation System might seem a little complicated.
However, in most cases we can use the very versatile ObjectAnimator that uses reflection. The
ObjectAnimator makes creating Property Animations almost as easy as creating View Animations.
Common properties commonly animated on views include:
Sr. No. Property Description
1 alpha Fade in or out.

2 rotation, rotationX, rotationY Spin or flip.


3. scaleX ,scaleY Grow or shrink.
4 %,Y,Z Position.
5. translation, translationY, translationZ (API 21+) Offset from Position.
Drawable Animation:
This animation allows the user to load drawable resources and display them one frame after
another. This method of animation is useful when user wants to animate things that are easier to
represent with Drawable resources.
To use Animations in Android, Android has provided us a class called Animation.
The Animation class has many methods given below:
1. start(): This method will start the animation.
2, setDuration(long duration): This method sets the duration of an animation.
3. getDuration(): This method gets the duration.
4. end(): This method ends the animation.
5. cancel(): This method cancels the animation.
Mobile Application Development 5.64 Activity and Multimedia with Databases

Example: Animation example in Android Studio showing 14 types of animation:


activity_main.xml code:
<?xml version="1.6" encoding="utf-8"?>
<android.support.v4.widget .DrawerLayoutxmlns:android="http: //schemas.android.com/apk/res
/android”
xmlns:app="http:
//schemas. android. com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android: id="@+id/drawer_layout"
android: layout_width="match_parent"
android: layout_height="match_parent"
android: fitsSystemWindows="true”"
tools: openDrawer="start”">
<include
layout="@layout/app_bar_main"
android: layout_width="match_parent”
android: layout_height="match_parent"/>
<android. support.design.widget.NavigationView
android: id="@+id/nav_view"
android: layout_width="wrap_content”
android: layout_height="match_parent"
android: layout_gravity="start"
android: fitsSystemWindows="true”
app :headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer"/>
</android. support. v4.widget.DrawerLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget .DrawerLayoutxmlns:android="http: //schemas.android.com/apk/res
/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android: id="@+id/drawer_layout"
android: layout_width="match_parent”
android: layout_height="match_parent"
android: fitsSystemWindows="true”
tools: openDrawer="start”">
<include
layout="@layout/app_bar_main"
android: layout_width="match_parent"
android: layout_height="match_parent"/>
<android. support.design.widget .NavigationView
android: id="@+id/nav_view"
android: layout_width="wrap_content"
android: layout_height="match_parent"
android: layout_gravity="start"
android: fitsSystemWindows="true”
app :headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer"/>
</android.support.v4.widget .DrawerLayout>
<?xml version="1.0" encoding="utf-8"?>
<android. support.v4.widget .DrawerLayoutxmlns:android="http: //schemas.android.com/apk/res
/android”
Mobile Application Development 5.65 Activity and Multimedia with Databases

xmlns:app="http://schemas.
android. com/apk/res-auto”
xmlns:tools="http://schemas.android.com/tools"
android: id="@+id/drawer_layout”™
android: layout_width="match_parent”
android: layout_height="match_parent"
android: fitsSystemWindows="true”
tools: openDrawer="start">
<include
layout="@layout/app_bar_main"
android: layout_width="match_parent"™
android: layout_height="match_parent"/>
<android. support.design.widget .NavigationView
android: id="@+id/nav_view"
android: layout_width="wrap_content"
android: layout_height="match_parent"
android: layout_gravity="start”
android: fitsSystemWindows="true"
app: headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer"/>
</android.support.v4.widget .DrawerLayout>
content_main.xml code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto”
xmlns:tools="http://schemas.android.com/tools"
android: layout_width="match_parent"
android: layout_height="match_parent"
android: paddingBottom="@dimen/activity_vertical_margin"
android: paddingLeft="@dimen/activity_horizontal_margin"
android: paddingRight="@dimen/activity_horizontal_margin"
android: paddingTop="@dimen/activity_vertical_margin”
app: layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools: showIn="@layout/app_bar_main">
<FrameLayout
android: id="@+id/content_frame"
android: layout_width="match_parent"
android: layout_height="match_parent"/>
</RelativeLayout>
nav_header.xml code:
<?xml version="1.6" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http:
//schemas. android. com/apk/res-auto"
android: layout_width="match_parent”™
android: layout_height="@dimen/nav_header_height"
android: background="@drawable/side_nav_bar"
android: gravity="bottom”
android:orientation="vertical”
android: paddingBottom="@dimen/activity_vertical_margin"
Mobile Application Development 5.66 Activity and Multimedia with Databases

android: paddingLeft="@dimen/activity_horizontal_margin"”
android: paddingRight="@dimen/activity_horizontal_margin"
android: paddingTop="@dimen/activity_vertical_margin"
android: theme="@style/ThemeOverlay.AppCompat.Dark"
android: weightSum="1">
<ImageView
android: id="@+id/imageView"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: src="@drawable/animation"
android: layout_alignParentTop="true"
android: layout_alignRight="@+id/textView"
android: layout_alignEnd="@+id/textView"
android: layout_marginRight="172dp"
android: layout_marginEnd="172dp"/>
<TextView
android: id="@+id/textView"
android: layout_width="14@dp"
android: layout_height="55dp"
android: text="ANIMATION EXAMPLE”
android: textColor="#8606ea"
android: textSize="11dp"
android: textStyle="bold”
android: layout_alignParentBottom="true"
android: layout_alignParentRight="true"
android: layout_alignParentEnd="true"
android: layout_marginBottom="17dp"/>
</RelativeLayout>
activity_main_drawer.xml file available in res + menu folder:
<?xml version="1.8" encoding="utf-8"?>
<menu xmins:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http: //schemas.android.com/apk/res/android">
<groupandroid: checkableBehavior="single">
<item
android: id="@+id/nav_zoomin"
android:title="Zoom In"/>
<item
android: id="@+id/nav_zoomout"
android:title="Zoom Out" />
<item
android: id="@+id/nav_rotate"
android: title="Rotate"/>
<item
android: id="@+id/nav_move"
android:title="Move"/>
<item
android: id="@+id/nav_bounce"
android:title="Bounce"/>
<item
android: id="@+id/nav_Blink"
android:title="Blink"/>
Mobile Application Development 5.67 Activity and Multimedia with Databases

<item
android :id="@+id/nav_slideup"
android: title="Slide Up"/>
<item
android :id="@+id/nav_slidedown"
android: title="Slide Down"/>
<item
android: id="@+id/nav_fade”
android: title="Fade Animation"/>
<item
android: id="@+id/nav_sequentialanimation”
android: title="Sequential Animation"/>
<item
android: id="@+id/nav_togetheranimation"
android: title="Together Animation"/>
<item
android: id="@+id/nav_flip"
android :title="Flip Animation"/>
<item
android: id="@+id/nav_drawable"
android :title="Drawable Animation"/>
<item
android: id="@+id/nav_swap"
android ititle="Swap Animation"/>
</group>
</menu>
MainActivity.java
import android. support.v4.app. Fragment;
import android.os.Bundle;
import android. support.v4.app.FragmentTransaction;
import android.support.design.widget .NavigationView;
import android. support.v4.view.GravityCompat;
import android. support.v4.widget .DrawerLayout;
import android. support.v7.app.ActionBarDrawerToggle;
import android. support.v7.app.AppCompatActivity;
import android. support.v7.widget.Toolbar;
import android. view.Menu;
import android. view.Menultem;
import com. example. abhishek. animationexample. fragment -blinkfragment;
import com -example. abhishek .animationexample. fragment -bouncefragment;
import com. example. abhishek .animationexample. fragment -drawableanimationfragment;
import com -example. abhishek -animationexample. fragment .fadefragment;
import com. example. abhishek -animationexample. fragment .Flipfragment;
import com -example. abhishek .animationexample. fragment -movefragment;
import com. example. abhishek .animationexample. fragment .Potatefragment;
import com -example. abhishek .animationexample. fragment .sequentialanimationfragment;
import com. example. abhishek. animationexample. fragment -Slidedownfragment;
import com example. abhishek .animationexample. fragment .Slideupfragment;
import com. example. abhishek. animationexample. fragment . Swapanimationfragment;
import com -example. abhishek. animationexample. fragment . togetheranimationfragment;
import com. example. abhishek. animationexample. fragment. zoominfragment;
import com. example. abhishek. animationexample. fragment .zoomout fragment ;
public class MainActivity extends AppCompatActivity
Mobile Application Development 5.68 Activity and Multimedia with Databases
implements NavigationView.OnNavigationItemSelectedListener{
@Override
protected void onCreate(Bundle savedInstanceState){
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar =(Toolbar) findViewById(R.id.toolbar);
DrawerLayout drawer =(DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle =newActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer. setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView =(NavigationView) findViewById(R.id.nav_view);
navigationView. setNavigationItemSelectedListener(this) ;
}
@Override
public void onBackPressed(){
DrawerLayout drawer =(DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer .isDrawerOpen(GravityCompat
.START) ){
drawer.closeDrawer(GravityCompat
.START) ;
jelse{
super.onBackPressed();
}
}
private void displaySelectedScreen(int itemId){
Fragment fragment =null;
switch(itemId){
case R.id.nav_bounce:
fragment =new bouncefragment();
break;
case R.id.nav_Blink:
fragment =new blinkfragment();
break;
case R.id.nav_zoomin:
fragment =new zoominfragment();
break;
case R.id.nav_zoomout:
fragment =new zoomoutfragment();
break;
case R.id.nav_rotate:
fragment =new rotatefragment();
break;
case R.id.nav_move:
fragment =new movefragment();
break;
case R.id.nav_slideup:
fragment =new
slideupfragment();
break;
case R.id.nav_slidedown:
fragment =new slidedownfragment();
break;
case R.id.nav_sequentialanimation:
fragment =new sequentialanimationfragment();
break;
Mobile Application Development 5.69 Activity and Multimedia with Databases

case R.id.nav_togetheranimation:
fragment =new togetheranimationfragment();
break;
case R.id.nav_flip:
fragment =new flipfragment();
break;
case R.id.nav_fade:
fragment=new fadefragment();
break;
case R.id.nav_drawable:
fragment =new drawableanimationfragment();
break;
case R.id.nav_swap:
fragment =new swapanimationfragment();
break;
}
if(fragment !=null1){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer =(DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat
.START);
}
@Override
public boolean onNavigationItemSelected(MenuItem item){
displaySelectedScreen(item.getItemId());
return true;

SQLITE DATABASE
Android SQLite is a very lightweight database which comes with Android OS. Android SQLite
combines a clean SQL interface with a very small memory footprint and decent speed.
For Android, SQLite is “baked into” the Android runtime, so every Android application can create its
own SQLite databases.
SQLite is a typical relational database, containing tables (which consists of rows and columns),
indexes etc. SQLite Database has methods to create, delete, execute SQL commands, and perform
other common relational database management tasks.
What is SQLite Database?
SQLite is an embedded, Relational Database Management System (RDBMS).
Most relational databases (Oracle and MySQL being prime examples) are standalone server processes
that run independently, and in cooperation with, applications that require database access.
SQLite is referred to as embedded because it is provided in the form of a library that is linked into
applications. As such, there is no standalone database server running in the background.
All database operations are handled internally within the application through calls to functions
contained in the SQLite library.
The developers of SQLite have placed the technology into the public domain with the result that it is
now a widely deployed database solution.
Mobile Application Development 5.70 Activity and Multimedia with Databases

e SQLite is written in the C programming language and as such, the Android SDK provides a Java based
“wrapper” around the underlying database interface. This essentially consists of a set of classes that
may be utilized within the Java code of an application to create and manage SQLite based databases.
Why SQLite/Necessity of SQLite
e Reasons for why we use SQLite is given below:
1. Serverless: SQLite is serverless which does not need a detach server process or system to operate.
2. Zero Configurations: SQLite does not require any setup or administration.
3. Cross-platform: A complete SQLite database is stored in a single cross-platform disk file.
4, Less Memory: SQLite is very small and light weight, less than 400 KiB completely configured or
less than 250 KiB with optional featues omitted.
5. Self-Contained: SQLite has no external dependencies.
6. Transaction: SQLite transactions are supported ACID properties to allow safe access from
multiple processes or threads.
7. Languages and operating system: SQLite supports most of the query language featueres found
in SQL92 (SQL2) standared.
ES(-e% Creation and Connetion of Database
e The package imported into the application is android.database.sqlite.SQLiteDatabase. Here the class
used is SQLiteDatabase.
e The method used to create the database or connect to the database is openOrCreateDatabse() method.
Example: Create a new project in Eclipse called Database and select the API version. Use the package
name com.db.DataBase with an activity Database and click finish.
package com.db.DataBase;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabse;
public class Databse extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R. layout.main);
SQLiteDatabase.CRETE_IF_NECESSARY,null);
}
}
« Import the package android.database.sqlite.SQLLiteDatabse to the new android project. Then after
the standard layout setup it initializes a SQLiteDatabse variable to hold the database instance. Next
we use the openOrCreateDatabase() method to open the database. The openOrCreateDatabse()
method to open the databse.
Properties to Setting the Database:
e There are some databse properties that must be set after connecting to the database. Some methods
are used to set these properties. These are:
1. setVersion(): It sets the databse version.
2. setLocale(): It sets the default locale for the database.
3. setLockingEnabled(): It enables locking on the databse.
e How wecreate a table:
1. After executing the statements the table is created on the databse.
2. The queries are executed by the execSQL() statements.
Mobile Application Development 5.71 Activity and Multimedia with Databases

DataBase.java
package com.db.DataBase;
import java.util.Locale;
import android.app.activity;
import android.os.Bundle;
import android.database.sqlite.SQLiteDatabase;
public class DataBase extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super. onCreate(savedInstanceState);
setContentView(R. layout.main);
SQLiteDatabase sdb;
sdb = openOrCreateDatabase(“Database.db”, SQLiteDatabase.CREATE_IF_NECESSARY, null);
sdb.setVersion(1);
sdb.setLocale(Locale.getDefault());
sdb. setLockingEnabled(true);
AUTOINCREMENT,” + “country_name_TEXT);” ;
final String CREATE_TABLE_COUNTRIES = “CREATE TABLE tbl_countries (‘+” id INTEGER
PRIMARY KEY
final String CREATE_TABLE_STATES = “CREATE TABLE tbl_states (“
+ “id INTEGER PRIMARY KEY AUTOINCREMENT,”
+ “state_name TEXT,”
+ “country_id INTEGER NOT NULL CONSTRAINT “
+ “country_id REFERENCES tbl_contries(id) “
+ “ON DELETE CASCADE);”;
sdb.execSQL(CREATE_TABLE_COUNTRIES);
sdb. execSQL(CREATE_TABLE_STATES);
final String CREATE_TRIGGER_STATES =
“CREATE TRIGGER fk_insert_state BEFORE “
“INSERT on tbl_states”
te t+

“FOR EACH ROW “


“BEGIN “
eet

“ SELECT RAISE(ROLLBACK, ‘° insert on table “


““tbl_ states” violets foreign key constraint “
““fk insert_state”’) WHERE (SELECT id FROM “
+e

*” tbl_countries WHERE id = NEW.country_id) IS NULL; “ + “END;”;


sdb. execSQL(CREATE_TRIGGER_STATES) ;
}
}
After opening the databse by openOrCreateDatabase(), we configure the database connection
with setVersion() to set the database version.
The setLocale(}) method sets the default locale for the database and setLockingEnabled() enables
locking on the databse.
Then we setup final string variables to hold the SQLite table creation statements and execute
them with execSQL().
6. We should create triggers to handle the foreign key relationships between the tables.
7 In the application, there also require foreign key triggers to handle row updates and deletes.
How to insert the records?
1 Android contains a series of classes that make simpler database handling.
2. We use a contentValues instance to create a series of table filed to data matchings that will be
passed into an insert() method.
Mobile Application Development 5.72 Activity and Multimedia with Databases

3, Android has created alike methods for updating and deleting records.
ContentValues values = new ContentValues();
values.put(“country_name”, “US”);
long countryId = sdb.insert(“tbl_countries”, null, values);
ContentValues statevalues = new ContentValues();
stateValues.put(“state_name”, “Texas”);
stateValues.put(“contry_id”, Long. tostring(countryId));
try
{
db. insertOrThrow(“tbl_states”, null, statevalues);
}catch(Exception e)
{
}
Add this code to previous example.
First we creae a contentValues object to store the data to insert and use the put() method to load
the data.
Then we use the insert() method to insert records into SQLite. The insert() method contains three
parameters: (a) Table name, (b) Null, (c) ContentValues pairs
The insert() function returns long which holds the primary key of the inserted row.
Then we create a new ContentValues pair for thr state and execute a second insert using the
insertOrThrow/() method.
Using insertOrThrow() will through an exception if the insert isn’t successful and should ne
enclosed by a try/catch block.
We observe that presently the application terminates with an unhandled exception because the
tables we are trying to create previously exist.
10. Then we have to go back into the adb shell and attach to the SQLite database for the application
and drop the tables.
How we can update the data in database:
1. The update() method is used to update the records in databse.
2. The update() function supports WHERE clause with the replacement passed as an array in
parameter 4 to update.
ContentValues updateCountry = new ContentValues();
updateCountry.put(“country_name”, “United States”);
db.update(“tbl_countries”,updateCountry,”id=?”,new String[]
{Long.toString(countryId)});
First we remove the table the create statements from the code. Here there is no requirement of
creating and droping tables.
Here updateCountry is an instance of ContentValues which is created to hold tha data to be
updated. Then use the update() method to update the table. The where clause in parameter 3 uses
substitute of the ? with the values stored in parameter 4.
If multiple ? existed in the where statement they would be replaced in order by the values of the
array.
How we can delete the data from the databse?
1, If data is no more longer required, then we can be removed from the databse with the delete()
method.
The delete() method excepts 3 parameters.
a. the database name,
b. aWHERE clause and
c. anargument array for the WHERE clause
Mobile Application Development 5.73 Activity and Multimedia with Databases

3. To delete all records from the table pass null for the WHERE clause and WHERE clause argument
array.
sdb.delete(“tbl_states”, “id=?”, new String[] {Long.toString(contryID)});
4, Only we call the delete() method to remove records from the SQLite databse.
5. The delete method contains, the table name, and optionally a where clause and anywhere clause
argument replacement arrays as parameters.
6. The where clause and argument replacement array work just as with update where? Is replaced
by the values in the array.
Extracting Values from a Cursors
* Cursor store query result records in rows and grant many methods to access and interact through
the records.
e Cursors should be closed when no longer used, and can be deactivated with a call to Cursor.
decactivate() statement when the application pauses or exists.
* On resume the Cursor.requery() statement is executed to re-enable the cursor with fresh data. These
functions can be manage by the parent Activity by calling startManagingCursor().
DataBase.java
package com.db.DataBase;
import java.util.locale;
import android.app.Activity;
import java.os.Bundle;
import android. content.ContentValues;
import android. database.Cursor;
import android. database. sqlite.SQLiteDatabase;
public class DataBase extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstancestate);
setContentView(R. layout.main) ;
SQLiteDatabase sdb;
sdb = openOrCreateDatabase(“TestingData.db”, SQLiteDatabase.CREATE_IF_NECESSARY, null);
sdb.setVersion(1);
sdb. setLocale(Locale.getDefault());
sdb. setLockingEnabled(true);
Cursor cur = sdb.query(“tbl_countries”, null, null, null, null, null, null);
cur.close();
}
}
e The query performed will return all records from the table tbl_countries.
Iterating through records:
¢ The Cursor class provides a couple of simple methods to allow iterating through Cursor data easily.
« Use moveToFirst() to position the Cursor pointer at the first record then use the moveToNext()
function to iterate the records.
e The isAfterLast() method performs a check to see if the cursor is pointed after the last record. When
looping throughout the records break the loop when this become false
e First add the following attribute to the TextView element in the main layout which is the xml file
located at res/layouts/main.xml.
Mobile Application Development 5.74 Activity and Multimedia with Databases

We require giving this TextView element an ID that we can reference to update the view.
android: id="@+id/hello”
Java code to ierate through entries in a cursor-.:
DataBase.java
package com.db.DataBase;
import java.util.locale;
import android.app.Activity;
import java.os.Bundle;
import android.widget.Textview;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DataBase extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savediInstancestate);
setContentView(R. layout.main) ;
TextView view = (TextView) findViewById(R.id.hello);
SQLiteDatabase sdb;
sdb = openOrCreateDatabase(“Databse.db”, SQLiteDatabase.CREATE_IF_NECESSARY, null);
sdb.setVersion(1);
sdb.setLocale(Locale.getDefault());
sdb. setLockingEnabled(true);
Cursor cur = sdb.query(“tbl_countries”, null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfetrLast() = = false)

view.append(“n” + cur.getString(1));
cur.moveToNext();

}
cur.close();

}
}
The moveTofirst() method is used to location the cursor pointer at the beginning of the data set. The
loop throughout the records in the cursor.
The method is AfterLast() returns a Boolean if the pointer is past the last record in the cursor. Here
we use the moveToNext() method to traverse through the records in the cursor.
Retriving a specific record. The cursor also allows direct access to particular records:
Cursor cur = sdb.query(“tbl_countries, null, null, null, null, null, null);
cur.moveToPosition(@);
view.append(“n” + cur.getstring(1));
cur.close();
cur.close();

}
}
Mobile Application Development 5.75 Activity and Multimedia with Databases

ESCs Transactions
All of the previously discussed insert, update, and delete operations manipulate tables and rows ina
database. While each operation is atomic (will either succeed or fail on its own), it is sometimes
necessary to group a set of operations together and have the set of operations be atomic.
There are times when a set of related operations should be allowed to manipulate the database only
if all operations succeed to maintain database integrity. For these cases, a database transaction is
usually used to ensure that the set of operations is atomic.
A transaction is a unit of work that is performed against a database. Transactions are units or
sequences of work accomplished in a logical order, whether in a manual fashion by a user or
automatically by some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example, if we are
creating, updating, or deleting a record from the table, then we are performing transaction on the
table. It is important to control transactions to ensure data integrity and to handle database errors.
Transactions have the following four standard properties, usually referred to by the acronym ACID,
1, Atomicity: Ensures that all operations within the work unit are completed successfully;
otherwise, the transaction is aborted at the point of failure and previous operations are rolled
back to their former state.
2. Consistency: Ensures that the database properly changes states upon a successfully committed
transaction.
3. Isolation: Enables transactions to operate independently of and transparent to each other.
4, Durability: Ensures that the result or effect of a committed transaction persists in case of a
system failure.
In Android, the SQLiteDatabase class contains the following methods to support transaction
processing:
1, void beginTransaction(): Begins a transaction
2. void setTransactionSuccessful(): Indicates that the transaction should be committed
3. void endTransaction(): Ends the transaction causing a commit if setTransactionSuccessful() has
been called
Using a Transaction:
A transaction is started with the SQLiteDatabase.beginTransaction() method. Once a transaction is
started, calls to any of the data manipulation method calls (insert(), update(), delete) may be
made.
Once all of the manipulation calls have been made, the transaction is ended with
SQLiteDatabase.endTransaction().
To mark the transaction as successful, allowing all the operations to be committed, SQLiteDatabase.
setTransactionSuccessful() must be called before the call to SQLiteDatabase.endTransaction() is
made. If endTransaction() is called without a call to setTransactionSuccessful(), the transaction will
be rolled back, undoing all of the operations in the transaction.
Because the call to setTransactionSuccessful() affects what happens during the endTransaction(}
call, it is considered a best practice to limit the number of non-database operations between a call
to setTransactionSuccessful() and endTransaction().
Additionally, do not perform any additional database manipulation operations between the call to
setTransactionSuccessful() and endTransaction(). Once the call tosetTransactionSuccessful() is
made, the transaction is marked as clean and is committed in the call to endTransaction() even if
errors have occurred after the call to setTransactionSuccessful().
Mobile Application Development 5.76 Activity and Multimedia with Databases

Transaction Example:
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
// insert/update/delete
// insert/update/delete
// insert/update/delete
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
e Database operations that happen in a transaction as well as the call to setTransaction() should take
place in atry block with the call to endTransaction() happening in a finally block. This ensures that
the transaction will be ended even if an unhandled exception is thrown while modifying the
database.
| peat elie tepals
What is activity?
What is multimedia database?
PNAMPYNE

What is service?
What is intent?
What is SQLite?
Enlist features of service.
Describe the term Indent Filter with example.
What is sensor? Enlist its types in Android.
Explain activity life cycle diagramatically.
EY

What is fragment ? Describe with example.


Explain content provider in detai.
n° hREBRB

With the help of diagram explain activity broadcast life cycle.


What is meant by content provider?
Enlist various permission for servcies.
What is animation? Enlist its types.
Describe the term audio capture in detail.
ee

How to play audio and video in Android?


& & 5
PPR

How to create and connect SQLite ? Explain with example.


With the help of diagram describe following frame works:
(i) Multimedia
(ii) Android system architecture
20. Describe the term text to speech in detail.
21, How to extracting values from cursors in Android?
22, What is transaction? Describe with example.
23. Explain service life cycle diagrammatically.

You might also like