Professional Documents
Culture Documents
+, +,
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
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
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.
Software Commercializaton
Companies Companies
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
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.
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
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
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,
External storage
Storage
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
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
« 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,
‘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
‘Completing
Android Studio Sotup
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.
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
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
Applications Framework
[ Package Manager ] (Telephony Manager] [Resource Manager | ( Location Manager ] [Netification Manager]
Linux Kernel
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
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).
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)
* 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
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)
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
| 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
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
Android Studia
="
_ ; i
cl i all
Bee *
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
Consists of
tests
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
Vesion of Class Cr
file format SHA-1
Signature other Strings
mstant Pool Heterogeneous Constant Pool
Sone Constant Pool
Access Flags
class Interfaces
Method
Methods Method Constant Pool
Attributes: Attributes
Field List
——
F
Local Variables
Java Compiler
Kowee
Dalvik Executable
by DVM
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
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
(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
-
Android Studio
oF import an Android
code sample
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
¢ 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
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
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
#05
BD eterno
a amin
04
[aree +4 none sees wouncrwe |
& ne val
Project Files
Problems
Production
Tests
Local Unit Tests
Android Instrumented Tests
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
¢ 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
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
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
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
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
| Practice Questions
What is meant by control flow?
wp wenawpwner
4...
Designing User
Interface with View |,
Chapter Outcomes...
Develop rich user interfaces for the given Android application.
Seee
Learning Objectives...
To learn Designing User Interface with View in Android
ID)
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
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.
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-->
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
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)
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
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
‘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
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
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
}
“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
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
Learning Objectives...
To understand Concepts in Activity
ee of
[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
Activity
launched
> onCreate()
t
onStart() onRestart()
User navigates
t A
= ki Ih led running
|
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
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
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
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
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()
The service
is stopped "
(no callback) onUnbind()
i
onDestroy() onDestroy()
Service is Service is
shut down shut down
*/
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*
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;
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
Media JNI
Native C Library
Media Server
Media Media
Player Recorder ———_
| Media | Media PV PV
Player Recorder Player Author
! '
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)
. 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
}
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
}
@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
[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. 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
Output:
ProgressDiaiog
use MediaRecorder.AudioSource.MIC.
Set output file format using MediaRecorder.setOutputFormat().
Ww OI nnaw
*/
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
/**
* 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
* Creates and returns the image or video file before opening the camera
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
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);
[**
}
})s
j**
}
})s
// restoring storage image path from saved instance state
// otherwise the path will be null on device rotation
restoreFromBundle(savedInstanceState);
}
/**
}
/**
}
@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);
}
/**
}
« 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
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>
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
No Yes
al
« Ifwechoose “No” option the status will be “Disabled” as the Bluetooth will not be activated.
UR ee
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
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
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
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.
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+
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