MAD
MAD
MSBTE - I Scheme
T.Y. Diploma Semester - VI
Computer Engineering Program Group
(CO / CM / IF / CW)
Mobile Application
Development
Vrushali R. Sonar
M.E. (IT), B.E. (Computer),
Lecturer, AISSMS’s Polytechnic,
Pune.
Narendra S. Joshi
Ph.D. (Pursuing), M.E. (CSE),
SOCSE Department
Assistant Professor,
Sandip University, Nashik.
Aniruddha D. Talole
M.E. (Computer Engg.), B.E. (Computer),
Lecturer(Computer Technology Department),
K. K. Wagh Polytechnic, Nashik.
® ®
TECHNICAL
PUBLICATIONS
SINCE 1993 An Up-Thrust for Knowledge
(i)
Mobile Application Development
Subject Code : 22617
Published by :
® ®
Amit Residency, Office No.1, 412, Shaniwar Peth, Pune - 411030, M.S. INDIA
TECHNICAL P h . : + 9 1 - 0 2 0 - 2 4 4 9 5 4 9 6 / 9 7 , Te l e f a x : + 9 1 - 0 2 0 - 2 4 4 9 5 4 9 7
PUBLICATIONS
SINCE 1993 An Up-Thrust for Knowledge Email : [email protected] Website : www.technicalpublications.org
ISBN 978-93-89750-07-2
(iv)
Unit-III 3a. Explain with relevant analogy the 3.1 Control flow, Directory Structure.
UI given Directory Structure. 3.2 Components of a screen, Fundamental
Components and 3b. Describe the steps to use the UI design.
Layouts given Android rich UI componet. 3.3. Linear Layout ; Absolute Layout, Frame
3c. Describe the steps to use the Layout, Table Layout ; Relative Layout.
given type of Layout.
3d. Develop the given basic Android
application.
Unit-IV 4a. Develop rich user Interfaces for 4.1 Text view, Edit Text; Button Image
Designing User the given Android application. Button; Toggle Button; Radio Button and
Interface with 4b. Develop Android application Radio Grop; Checkbox; Progress Bar
View using the given view. 4.2 List view ; Grid view ; Image view ;
4c. Explain the significance of the Scroll view ; Custom Toast Alert.
given display Alert. 4.3 Time and Date Picker.
4d. Develop the given application
using time and date picker.
Unit-V 5a. Apply the given Intents and 5.1 Intent, Intent_Filter
Activity And service in Application 5.2 Activity, Lifecycle; Broadcast Lifecycle.
Multimedia with development.
databases 5.3 Content Provider ; Fragments.
5b. Use Fragment to generate the
given multiple activities. 5.4 Service : Features of Service, Android
platform service, Defining new service,
5c. Develop programs to play the Service Lifecycle, Permission, example of
given multimedia. service.
5d. Write the query to perform the 5.5 Android System Architecture,
given database management Multimedia framework, Play Audio and
operation. Video, Text to speech, Sensors, Async
tasks.
5.6 Audio capture, Camera.
5.7 Bluetooth, Animation.
5.8 SQLite Database, necessity of SQLite,
Creation and connection of the database,
extracting value from cursors,
Transactions.
(v)
Unit-VI 6a. Explain the given location based 6.1 SMS Telephony
Security and service. 6.2 Location Based Sevices : Creating the
Application 6b. Write the steps to customize the project, Getting the maps API key,
Deployment given permissions for users. Displaying the map, Displaying the
6c. Explain features of the given zoom control, Navigating to a specific
android scecurity service. location, Adding markers, Getting
location, Geocoding and reverse
6d. Write the steps to publish the Geocoding, Getting Location data,
given android App. Monitoring Location.
6.3 Android Security Model, Declaring and
Using Permissions, Using Custom
Permission.
6.4 Application Deployment : Creating
Small Application, Signing of
application, Deploying app on Google
Play Store, Become a Publisher,
Developer Console.
(vi)
Table of Contents
2.6.5 Installation of Emulators. . . . . . . . . . . . . . 2 - 18
Unit - I
Unit - III
Chapter - 1 Android and its Tools
(1 - 1) to (1 - 12)
Chapter - 3 Components and Layouts
(3 - 1) to (3 - 66)
1.1 Introduction to Android . . . . . . . . . . . . . . . . . . 1 - 1
1.1.1 What is Android ? . . . . . . . . . . . . . . . . . . . 1 - 1
3.1 The Development Process. . . . . . . . . . . . . . . . . 3 - 1
1.1.2 Key Platform Components. . . . . . . . . . . . . 1 - 1 3.1.1 Creating the Project . . . . . . . . . . . . . . . . . . . 3 - 2
1.1.3 Android Versions . . . . . . . . . . . . . . . . . . . . 1 - 2 3.1.2 Directory and File Structure of an
Android Studio Project. . . . . . . . . . . . . . . 3 - 12
1.1.4 Open Handset Alliance (OHA) . . . . . . . . . 1 - 3
3.2 Components of Android Application . . . . . . . 3 - 16
1.1.5 Android Ecosystem . . . . . . . . . . . . . . . . . . 1 - 4
3.2.1 Creating the user Interface . . . . . . . . . . . . 3 - 18
1.1.6 Need of Android. . . . . . . . . . . . . . . . . . . . . 1 - 5 3.3 Layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 19
1.2 Android Features. . . . . . . . . . . . . . . . . . . . . . . . 1 - 6 3.3.1 Android Linear Layout . . . . . . . . . . . . . . . 3 - 21
1.3 Tools and Software Required for 3.3.2 Android Absolute Layout. . . . . . . . . . . . . . 3 - 33
Developing an Android Application . . . . . . . . 1 - 7
3.3.3 Android Frame Layout . . . . . . . . . . . . . . . 3 - 36
1.4 Android Architecture . . . . . . . . . . . . . . . . . . . . 1 - 8 3.3.4 Android Table Layout . . . . . . . . . . . . . . . . 3 - 43
Unit - IV
Chapter - 2 Installation and Configuration
of Android (2 - 1) to (2 - 20)
Chapter - 4 Designing User Interface with
2.1 The Android Operating System . . . . . . . . . . . . . 2 - 1 View (4 - 1) to (4 - 34)
2.1.1 How do Android Apps Work ? . . . . . . . . . . 2 - 1
4.1 The Android View . . . . . . . . . . . . . . . . . . . . . . 4 - 1
2.1.2 Java Development Kit (JDK) . . . . . . . . . . . 2 - 3
4.1.1 Basic Views . . . . . . . . . . . . . . . . . . . . . . . . 4 - 1
2.1.3 Android SDK . . . . . . . . . . . . . . . . . . . . . . . 2 - 4 4.1.1.1 Text View . . . . . . . . . . . . . . . . . . . . . 4 - 2
2.2 Android - Developer Tools . . . . . . . . . . . . . . . . 2 - 4
4.1.1.2 Declare UI Elements in XML . . . . . . 4 - 2
2.3 Android Virtual Device (AVD) . . . . . . . . . . . . . 2 - 5 4.1.2 Edit Text. . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 2
2.4 Android Emulator . . . . . . . . . . . . . . . . . . . . . . . 2 - 7 4.1.3 Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 6
2.6.2 Installing the Java Development Kit (JDK) 2 - 9 4.1.6 Radio Button . . . . . . . . . . . . . . . . . . . . . 4 - 13
(vii)
(viii)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
(x)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - I
1
1.1 Introduction to Android
Android and its Tools
Handset Alliance (OHA) is consortium of multiple Fig. 1.1.2 The major components of the Android
companies like Samsung, Sony, Intel and many platform
more to provide a service and deploy handsets The architectural diagram in Fig. 1.1.2 shows that the
using android platform. Android platform can be broken down into five
· Android gives a chance to reuse the application sections :
components and the replacement of native · Applications
applications.
· Application framework
· The most distinguished feature of Android is that it
· Middleware libraries
gives equal opportunities to native apps and third
· Operating system
party apps to use its resources.
· SDK and developer tools
Applications are pretty obvious. But several different
Linux kemel Operating system (Linux kernel)
types of applications are available on most Android
Dalvik virtual machine Middleware
devices and the distinction is subtle. Core open
Native and third Apps (Third party and native apps)
party application source applications are included as part of Android
itself, such as the Browser, Camera, Gallery, Music,
Phone and more. These are typically included with
every Android device. There are also non-open
Fig. 1.1.1 Android environment source Google apps that are included with most
official builds, including Market, Gmail, Maps,
YouTube and more. Many carrier or handset
manufacturer specific Applications are included on specific builds (such as AT and T's own music
player, Verizon's own Navigator, or Sprint's TV). And, third-party applications are available in the
Android Market, which can be either open source or proprietary. These include independent Google
applications such as Goggles and Listen, official apps from popular services like Twitter and Facebook,
and thousands of other choices.
Android
4.0 Android Android Android Android
4.1 4.4 5.0 6.0
Ice Cream
Sandwich Jelly Bean KitKat Lolipop Marshmallow
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-4 Android and its Tools
· The Open Handset Alliance is made up of (Audience, Broadcom, Intel, Marvell, NVidia
telecom-related entities, including wireless carriers, Qualcomm, SiRF, Synaptics), software companies
semiconductor companies, handset manufacturers (Ascender, eBay, esmertec, Google, LivingImage,
and software companies. However, several major LiveWire, Nuance, Packet Video, SkyPop,
wireless companies and manufacturers are absent SONiVOX), and commercialization companies
from the coalition, including Nokia, Symbian, (Aplix, Noser, TAT, Wind River). The Alliance
Apple, RIM, Microsoft, Verizon and Cingular. includes the major partners needed to deliver a
· Google and 33 other companies announced the platform for mobile phone applications in all of the
formation of the Open Handset Alliance on major geographies.
November 5, 2007. According to the joint press · The Alliance releases software through Google's
release from that day : developer website (http://developer .android.com).
This alliance shares a common goal of fostering The Android SDK for use by application software
innovation on mobile devices and giving consumers a developers can be downloaded directly from that
far better user experience than much of what is website.
available on today's mobile platforms. · The OHA introduced a mobile device operating
· By providing developers a new level of openness system called Android Symbian operating system.
that enables them to work more collaboratively,
Android will accelerate the pace at which new and 1.1.5 Android Ecosystem
compelling mobile services are made available to Ecosystem in Market terminology refers to the
consumers. inter-dependence between demand and supply.
· For us as mobile application developers, that means In the Android ecosystem this translates to
we are free to develop whatever creative mobile inter-dependence between users, developers and
applications we can think of, free to market them equipment makers. One cannot exist without the
(or give them, at our option) to Android mobile other :
phone owners, and free to profit from that effort · Users buy devices and applications
any way we can. Each member of the Open
· Equipment makers sell devices, sometimes bundled
Handset Alliance has its own reasons for
with applications
participating and contributing its intellectual
property, and we are free to benefit. · Developers buy devices, then make and sell
applications.
· The Open Handset Alliance integrates contributed
software and other intellectual property from its · An open source platform for mobile, embedded and
member companies and makes it available to wearable devices .
developers through the open source community. · Google is the principle maintainer
· Software is licensed through the Apache V2 license, · Other companies contribute to the system.
which you can see at · Each device manufacturer can customize Android to
http://www.apache.org/licenses/LICENSE-2.0.txt. Use suit their needs
of the Apache license is critical, because it allows This new ecosystem is built and developed in order
handset manufacturers to take Android code, to drive the usage of apps. The end-users gain access
modify it as necessary and then either keep it to several mobile apps just because of their
proprietary or release it back to the open source popularity. Thus, the ecosystem of mobile
community, at their option. applications enables the enterprises and the
· The original Alliance members include handset independent developers to develop attractive,
manufacturers (HTC, LG, Motorola, Samsung), feature-rich and unique mobile applications which
mobile operators (China Mobile Communications, will perform rapidly and can essentially garner the
KDDI, DoCoMo, Sprint/Nextel, T-Mobile, Telecom attention of the market.
talia, Telefonica), semiconductor companies
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-5 Android and its Tools
More
devices
OEM's
1. Open source
Right development
2. Large developer and community reach environment
3. Increased marketing
1. Reduced cost of development : The development
4. Inter App integration
tools like Android studio, Android SDK, JDK,
5. Reduced cost of development and Eclipse IDE etc. are free to download for the
6. Higher success ratio android mobile application development.
7. Rich development environment
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-6 Android and its Tools
2. Open Source : The Android OS is an 9. Google Integration : Google, the current owners
open-source platform based on the Linux kernel of Android, are highly smart in business.
and multiple open-source libraries. In this way Android devices work seamlessly with all of
developers are free to contribute or extend the Google's products; Google Docs, Gmail, YouTube,
platform as necessary for building mobile apps Google Music, Google Maps, Google Chrome,
which run on Android devices. Google+ etc. Google is regarded as the king of
3. Multi-Platform Support : In market, there are a the web. This is a major attraction for most
wide range of hardware devices powered by the people, as having an android device gives them
Android OS, including many different phones instant access to all of this important software.
and tablet. Even development of android mobile
apps can occur on Windows, Mac OS or Linux. 1.2 Android Features
4. Multi-Carrier Support : World wide a large Android is a powerful open source operating system
number of telecom carriers like Airtel, Vodafone, which provides a lot of great features like :
Idea Cellular, AT and T Mobility, BSNL etc. are · It's an open source and we can customize the OS
supporting Android powered phones. based on our requirements.
5. Open Distribution Model : Android Market · It supports a multi-tasking, we can move from one
place (Google Play store) has very few
task window to another and multiple applications
restrictions on the content or functionality of an
can run simultaneously.
android app. So the developer can distribute
theirs app through Google Play store and as well · It will give a chance to reuse the application
other distribution channels like Amazon's app components and the replacement of native
store. applications.
6. Multi-tasking : Multi-tasking is available on · It has an extensive support for multimedia
virtually all smartphone platforms but hardly hardware control to perform playback or recording
does any operating system do it better than using camera and microphone.
android. Some manufacturers, e.g. Samsung · By using WIFI technology we can pair with other
allows for multi-window tasking. This allows
devices using apps.
users to view multiple apps at the same time.
· It support a connectivity for GSM, CDMA, WIFI,
7. Variety : Android has provided a medium that
NFC, Bluetooth, etc. for telephony or data transfer.
has allowed smartphone manufacturers like
It will allow us to make or receive a calls / SMS
Samsung, HTC, ZTE, Sony and Motorola to allow
messages and we can send or retrieve a data across
their imagination run wild. On Android platform,
there is something for everyone regardless of mobile networks.
taste or budget. Android offers flexibility that is · Android have a multiple APIs to support a
not obtainable with other platforms. location-based services such as GPS.
8. Widgets : Widget is another thing that is · We can perform all data storage related activities by
working absolutely well on Android devices. It using light weight database SQLite.
has worked so excellently, other operating
· It have a wide range of media supports like AVI,
systems and mobile app development are starting
MKV, FLV, MPEG4 etc. to play or record variety of
to adopt something similar, e.g. the Live Tile
audio / video and having a different image formats
System in Windows phone. Widget allows users
like JPEG, PNG, GIF, BMP, MP3, etc.
to access all the necessary information they want
right from the screen, at a glance, without having · It has an integrated open source webkit layout
to launch an app. based web browser to support HTML5, CSS3.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-7 Android and its Tools
· We can access the hardware components like · 2 GB of available disk space minimum, 4 GB
Camera, GPS and Accelerometer. Recommended (500 MB for IDE + 1.5 GB for
· It has a support for 2D/3D Graphics. Android SDK and emulator system image)
· 1280 ´ 800 minimum screen resolution
1.3 Tools and Software Required for
Developing an Android Application Linux
Following are Tools and software required to begin · GNOME or KDE desktop Tested on Ubuntu®
with Android development : 14.04 LTS, Trusty Tahr (64-bit distribution capable
1. Windows (XP or later), Linux (any recent Linux of running 32-bit applications)
distribution) and Mac OS X (10.4.9 or later) · 64-bit distribution capable of running 32-bit
2. Android Studio or Eclipse applications
Recommended Processor
Windows
· Microsoft® Windows® 7/8/10 (32 or 64-bit) More than i3, i5 or i7 developers should be
concerned about the speed of the processor and
· 3 GB RAM minimum, 8 GB RAM recommended;
number of cores. 2 GHz Quad core Intel i3 processor
plus 1 GB for the Android Emulator
would be enough to develop on Android. I have
· 2 GB of available disk space minimum, 4 GB personally used it and did not face any difficulty.
Recommended (500 MB for IDE + 1.5 GB for
Android SDK and emulator system image) 2. IDE (Eclipse or Android Studio)
· 1280 ´ 800 minimum screen resolution Although the SDK can be used to write Android
programs in the command prompt, the most common
· For accelerated emulator : Intel® processor with
method is by using an Integrated Development
support for Intel® VT-x, Intel® EM64T (Intel® 64),
Environment (IDE). Eclipse is quite reputed and
and Execute Disable (XD) Bit functionality trusted IDE. And a lot of people use it for Android
Mac development too. But now a days Android Studio is
preferable, especially for a beginner.
· Mac® OS X® 10.10 (Yosemite) or higher, up to
10.12 (macOS Sierra) Because
· 3 GB RAM minimum, 8 GB RAM recommended; i) Android Studio is a Google product - these are
plus 1 GB for the Android Emulator the same guys who develop Android.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-8 Android and its Tools
ii) Android Studio uses Grade Build system. Which 1) Linux kernel
is quite faster than Eclipse's Apache Ant It is the heart of android architecture that exists at
iii) Android Studio's Autocomplete feature quite the root of android architecture. Linux kernel is
better than that of Eclipse responsible for device drivers, power management,
memory management, device management and
iv) Designing UI has always been complex but
resource access. This layer is the foundation of the
Android Studio has completely changed this.
Android Platform.
v) The new interface design in Android Studio is
faster, responds to changes more rapidly and has Positioned at the bottom of the Android software
more customization options than Eclipse stack, the Linux Kernel provides a level of abstraction
between the device hardware and the upper layers of
3. Android SDK the Android software stack. Based on Linux version
2.6, the kernel provides pre-emptive multitasking,
The Android SDK (software development kit) is a set
low-level core system services such as memory,
of development tools used to develop applications for
process and power management in addition to
Android platform. The Android SDK includes the
providing a network stack and device drivers for
following :
hardware such as the device display, Wi-Fi and
· Required libraries
audio.
· Debugger · Contains all low level drivers for various hardware
· An emulator components support.
· Relevant documentation for the Android · Android Runtime relies on Linux Kernel for core
Application Program Interfaces (APIs) system services like,
· Sample source code · Memory, process management, threading etc.
· Tutorials for the Android OS · Network stack
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-9 Android and its Tools
Applications
Graphics Cellular
Audio Camera Bluetooth GPS Wi-Fi
radio
A summary of some key core Android libraries · android.database : Used to access data published by
available to the Android developer is as follows : content providers and includes SQLite database
· android.app : Provides access to the application management classes.
model and is the cornerstone of all Android · android.graphics : A low-level 2D graphics drawing
applications. API including colors, points, filters, rectangles and
· android.content : Facilitates content access, canvases.
publishing and messaging between applications and · android.hardware : Presents an API providing
application components. access to hardware such as the accelerometer and
light sensor.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1 - 10 Android and its Tools
· android.opengl : A Java interface to the OpenGL ES C/C++ libraries are included to fulfil a wide and
3D graphics rendering API. diverse range of functions including 2D and 3D
· android.os : Provides applications with access to graphics drawing, Secure Sockets Layer (SSL)
standard operating system services including communication, SQLite database management, audio
messages, system services and inter-process and video playback, bitmap and vector font
communication. rendering, display subsystem and graphic layer
management and an implementation of the standard
· android.media : Provides classes to enable playback
C system library (libc).
of audio and video.
· android.net : A set of APIs providing access to the In practice, the typical Android application developer
network stack. Includes android.net.wifi, which will access these libraries solely through the Java
provides access to the device's wireless stack. based Android core library APIs. In the event that
direct access to these libraries is needed, this can be
· android.print : Includes a set of classes that enable
achieved using the Android Native Development Kit
content to be sent to configured printers from
(NDK), the purpose of which is to call the native
within Android applications.
methods of non-Java or Kotlin programming
· android.provider : A set of convenience classes that
languages (such as C and C++) from within Java code
provide access to standard Android content
using the Java Native Interface (JNI).
provider databases such as those maintained by the
· SQLite Library used for data storage and light in
calendar and contact applications.
terms of mobile memory footprints and task
· android.text' : Used to render and manipulate text execution.
on a device display.
· WebKit Library mainly provides Web Browsing
· android.util : A set of utility classes for performing engine and a lot more related features.
tasks such as string and number conversion, XML
· The surface manager library is responsible for
handling and date and time manipulation.
rendering windows and drawing surfaces of various
· android.view : The fundamental building blocks of apps on the screen.
application user interfaces.
· The media framework library provides media
· android.widget : A rich collection of pre-built user codecs for audio and video.
interface components such as buttons, labels, list
· The OpenGl (Open Graphics Library) and SGL
views, layout managers, radio buttons etc.
(Scalable Graphics Library) are the graphics libraries
· android.webkit : A set of classes intended to allow for 3D and 2D rendering, respectively.
web-browsing capabilities to be built into
· The FreeType Library is used for rendering fonts.
applications.
3) Android runtime
C/C++ Libraries
In android runtime, there are core libraries and DVM
The Android runtime core libraries outlined in the
(Dalvik Virtual Machine) which is responsible to run
preceding section are Java-based and provide the
android application. DVM is like JVM but it is
primary APIs for developers writing Android
optimized for mobile devices. It consumes less
applications. It is important to note, however, that the
memory and provides fast performance. The Dalvik
core libraries do not perform much of the actual
VM makes use of Linux core features like memory
work and are, in fact, essentially Java "wrappers"
management and multi-threading, which is intrinsic
around a set of C/C++ based libraries. When making
in the Java language. The Dalvik VM enables every
calls, for example, to the android.opengl library to
Android application to run in its own process, with
draw 3D graphics on the device display, the library
its own instance of the Dalvik virtual machine.
actually ultimately makes calls to the OpenGL ES C++
library which, in turn, works with the underlying When an Android app is built within Android Studio
Linux kernel to perform the drawing tasks. it is compiled into an intermediate bytecode format
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1 - 11 Android and its Tools
Java compiler, e.g..javac The Android framework includes the following key
services :
Java bytecode
(.class file) · Activity Manager : Manages the life cycle of an
applications and maintains the back stack as well so
dex translator
that the applications running on different processes
Dalvik executable has smooth navigations.
(.dex file)
· Package Manager : Keeps track of which
interpreted by VM applications are installed in your device.
· Window Manager : Manages windows which are
Dalvik VM
java programming abstractions on top of lower level
surfaces provided by surface manager.
Fig. 1.4.2 Android runtime · Telephony Managers : Manages the API which is
used to build the phone applications
· Dalvik is a specialized virtual machine designed · Content Providers : Provide feature where one
specifically for Android and optimized for application can share the data with another
battery-powered mobile devices with limited application, like phone number, address, etc.
memory and CPU.
· View Manager : Buttons, Edit text, all the building
· Android apps execute on Dalvik VM, a blocks of UI, event dispatching etc.
"clean-room" implementation of JVM
· Resource Manager : Provides access to non-code
· Dalvik optimized for efficient execution embedded resources such as strings, colour settings
· Dalvik: register-based VM, unlike Oracle's and user interface layouts.
stack-based JVM · Notifications Manager : Allows applications to
· Java .class bytecode translated to Dalvik EXecutable display alerts and notifications to the user.
(DEX) bytecode, which Dalvik interprets · Telephony Manager : Provides information to the
application about the telephony services available
on the device such as status and subscriber
information.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1 - 12 Android and its Tools
5) Applications
On the top of android framework, there are
applications. These comprise both the native
applications provided with the particular Android
implementation (for example web browser and email
applications) and the third party applications installed
by the user after purchasing the device. All
applications such as home, contact, settings, games,
browsers are using android framework that uses
android runtime and libraries.
qqq
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - II
2
2.1 The Android Operating System
Installation and
Configuration of Android
· Android is an open-source mobile operating system. It is a variant of Linux hence providing extensive
security, modularity and productivity at the mobile device level.
· Originally, Android was created by a company called Android Inc. Google acquired this company in
2005. After then, Google made it open source.
· Android has seven major releases each having several minor revisions. In order to follow these
versions easier, developers name them with cookie names. The popular versions of Android are Kitkat
(Android 4.4), Lollipop (Android 5.1) and Marshmallow (Android 6.0), Nougat (Android 7.0) is also
gaining popularity.
· Android is utilized not only in smartphones but also in tablets, netbooks, digital television boxes,
handheld game devices and even in single board computers such as UDOO. UDOO is a single-board
computer with an integrated Arduino Due compatible microcontroller, designed for computer science
education, the world of Makers and the Internet of Things.
Our project
Android
What
Java code APK Dalvik virtual the
Graphics DFX code machine user
Sound + resources sees
Layouts
Other resources
· There are different ways the programs run on various platforms. The lowest level software can be
written in machine code that runs directly on the microprocessor. This is shown in Fig. 2.1.2. Since it
is difficult to develop complex applications in machine code, operating systems are used. Operating
systems provide a communication and control layer between the application software and the
hardware as shown in Fig. 2.1.3. If we want to develop a native application for running on a specific
(2 - 1)
Mobile Application Development 2-2 Installation and Configuration of Android
Executable
Source Computer file - runs on the
Linker
code operating system
· Therefore, as long as a computer has the virtual machine running, the application software can run on
that computer independent of the hardware and the
operating system. A good example is the Java Virtual
Machine (JVM). JVM runs on almost all operating
Application
systems and platforms. Therefore, when we develop software
Java software, it will be run on the JVM independent Virtual
of the operating system/platform. The obvious machine
advantage of developing apps that run on virtual Operating
system
machines can then be stated as : "develop once and
run on all platforms". However, applications running Hardware
on virtual machines are slower than native
applications. General development process of virtual Fig. 2.1.5 Virtual machine between the app
machine applications is summarized in Fig. 2.1.6. and the operating system
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-3 Installation and Configuration of Android
Interpreted as
native code
· Similar to Java applications, Android applications also run on a JVM. There are two special virtual
machines used in Android : Dalvik Virtual Machine (DVM) and Android RunTime (ART). These are
specialized JVMs which can run on low system resources. The .apk files (executables of Android apps)
actually run on these virtual machines. DVM has been the default runtime environment (~ virtual
machine) until the Lollipop release (Android 5.0). ART is introduced by Android 4.0 and has been the
default VM as of Android 5.0. DVM and ART basically do the same job : running Android apps
independent of the platform. The main advantage of ART over DVM is the utilization of a concept
called Ahead of Time (AOT) compilation instead of Just in Time (JIT) approach. In AOT, apps are
compiled during installation hence they load faster with lower CPU usage. On the other hand, JIT
compilation provides lower storage space consumption with relatively longer loading times.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-4 Installation and Configuration of Android
· The purpose of the DVM is to hide the complexity and diversity of the hardware and software that
Android runs on but, at the same time, its purpose is to expose all of its useful features. This
exposing of features generally works in two ways. The DVM itself must have access to the hardware,
which it does, but this access must be programmer friendly and easy to use. The way the DVM
allows us access is indeed easy to use because of the Android Application Programming Interface
(API).
SDK tools
Tools for debugging and testing, Android support
plus other useful utilities. The Extra APIs that aren't available
SDK also features a set of in the standard platform.
platform dependent tools
· The Android SDK is a software development kit for Android development that contains the necessary
components to build Android applications. It comes as part of the Android Studio and includes a
comprehensive set of development tools including a debugger, software libraries of prewritten code, a
device emulator to run your Android applications, documentation, sample code, and tutorials. These
tools are used to create apps that look great and take advantage of the hardware capabilities.
· The Android Virtual Device manager that comes with the Android SDK enables to test application
with any version of Android.
· The Android SDK and Gradle tooling incorporate the needed tools to build, compile, and package
Android applications.
· For debugging Android applications, the Android Debug Bridge (adb) tool that enables to connect to
any virtual or real Android device.
· Here's the list of the important packages in the Android SDK :
· SDK Tools · SDK Platform Tools · SDK Platform · System Image · SDK Samples
SDK tools :
SDK tools are generally platform independent and are required no matter which android platform you
are working on. When you install the Android SDK into your system, these tools get automatically
installed. The list of SDK tools has been given below -
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-5 Installation and Configuration of Android
Sr. No. Tool and description range of different devices. Additional templates
may be loaded or custom configurations created to
1. android
This tool lets you manage AVDs, projects, and match any physical Android device by specifying
the installed components of the SDK properties such as processor type, memory capacity
2. ddms and the size and pixel density of the screen. When
This tool lets you debug Android applications launched, an AVD will appear as a window
3. Draw 9-Patch containing an emulated Android device
This tool allows you to easily create a environment. Fig. 2.3.1, for example, shows an AVD
NinePatch graphic using a WYSIWYG editor
session configured to emulate the Google Nexus 6
4. emulator API 15 model. New AVDs are created and managed
This tools let you test your applications using the Android Virtual Device Manager, which
without using a physical device
may be used either in command-line mode or with a
5. mksdcard
more user-friendly graphical user interface.
Helps you create a disk image (external sdcard
storage) that you can use with the emulator
6. proguard
Shrinks, optimizes, and obfuscates your code
by removing unused code
7. sqlite3
Lets you access the SQLite data files created
and used by Android applications
8. traceview
Provides a graphical viewer for execution logs
saved by your application
9. Adb
Android Debug Bridge (adb) is a versatile
command line tool that lets you communicate
with an emulator instance or connected
Android-powered device.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-6 Installation and Configuration of Android
Device Name Name of the hardware profile. The name can contain uppercase or lowercase letters, numbers
from 0 to 9, periods (.), underscores (_), parentheses ( () ), and spaces. The name of the file
storing the hardware profile is derived from the hardware profile name.
Screen Size The physical size of the screen, in inches, measured at the diagonal. If the size is larger than
your computer screen, it's reduced in size at launch.
Screen Resolution Type a width and height in pixels to specify the total number of pixels on the simulated
screen.
Round Select this option if the device has a round screen, such as some Wear OS devices.
Memory : RAM Type a RAM size for the device and select the units, one of B (byte), kB (kilobyte),
MB (megabyte), GB (gigabyte) or TB (terabyte).
Input : Has Hardware Select this option if your device has hardware navigation buttons. Deselect it if these buttons
Buttons (Back/Home/Menu) are implemented in software only. If you select this option, the buttons won't appear on the
screen. You can use the emulator side panel to "press" the buttons, in either case.
Input: Has Hardware Select this option if your device has a hardware keyboard. Deselect it if it doesn't. If you select
Keyboard this option, a keyboard won't appear on the screen. You can use your computer keyboard to
send keystrokes to the emulator, in either case.
Sensors : Accelerometer Select if the device has hardware that helps the device determine its orientation.
Sensors: Gyroscope Select if the device has hardware that detects rotation or twist. In combination with an
accelerometer, it can provide smoother orientation detection and support a six-axis orientation
system.
Sensors : GPS Select if the device has hardware that supports the Global Positioning System (GPS)
satellite-based navigation system.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-7 Installation and Configuration of Android
Sensors: Proximity Sensor Select if the device has hardware that detects if the device is close to your face during a phone
call to disable input from the screen.
Default Skin Select a skin that controls what the device looks like when displayed in the emulator.
Remember that specifying a screen size that's too big for the resolution can mean that the
screen is cut off, so you can't see the whole screen.
An emulator is an application that supports a virtual device which prototypes, develops and tests the
applications without using a real device. It acts as all hardware and software features of device. It
cannot make a real phone call. It runs a full Android system stack, down to the kernel level. It includes
a set of preinstalled applications (such as the dialer, messenger) which can be accessed from our
applications.
Each AVD is an independent device. It has its own storage and data. In each configuration, an
Android platform is specified which is to be run in the emulator along with the set of hardware
options, emulator skin, etc. when emulator is launched, we specify the AVD configuration that we
want to load. As soon as we launch the emulator with an AVD configuration, it automatically loads the
user data and SD card data from the AVD directory. By default, cache, user data and SD card is stored
in AVD directory. AVD manager manages all the emulators.
Dalvik is a purpose built virtual machine designed specifically for android which was developed by
Dan Bornstein and his team. Strictly it was developed for mobile devices. Dalvik virtual machine uses
register based architecture. With this architecture dalvik virtual machine has few advantages over JAVA
virtual machine such as :
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-8 Installation and Configuration of Android
1. Dalvik uses its own 16 bit instruction set than Key Feature :
java 8 bit stack instructions, which reduce the · Android dalvik virtual machine is a registered
dalvik instruction count and raised its interpreter based Virtual machine.
speed. · With using DVM, android device can run multiple
2. Dalvik use less space, which means an instances of VM efficiently.
uncompressed .dex file is smaller in size(few · Duplicate String and other constants used in
bytes) than compressed java archive file(.jar file).
multiple class files are included only once in the
The Dex compiler converts the class files into the
.dex Output to conserve space.
.dex file that run on the Dalvik VM. Multiple
· Java byte code is also converted into alternative
class files are converted into one dex file.
instruction set used by DVM.
The compiling and packaging process : · An uncompressed .dex file is smaller in size as
compare to compressed .jar derived from same
.java files .class file.
.dex file
Source Code · The Dalvik executable may be modified again when
installed onto the mobile devices.
r · DVM was slimmed down to use less space.
ile
p
m
Java compiler
x co x) Packaging · The Dalvik VM executes file in Dalvik executable
(javac) e ( d (aapt)
D (.dex) format which is optimized for minimal
memory foot print.
· DVM not only can run multiple VM instances but
.class files .apk file creation of new VM must be fast as well.
Comparison of Java VM and the Dalvik virtual
machine :
Fig. 2.5.1 Compiling and packaging process
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-9 Installation and Configuration of Android
Java Source
code Java Source
(.java) code
Java (.java)
compiler Java
(javac) compiler
(javac)
Java Byte code
(.class) Java Byte code
(.class)
DEX
compiler
Dalvik Byte
code
(.dex)
Register-based Register-based
Java Virtual
Dalvik Virtual Machine
Machine (JVM)
(DVM)
4. click on the Change button and you will see this window :
5. Browse to the hard drive where you will be installing all of your development tools. Then simplify
the names of the folders in which you will install the JDK to just Java\JDK\.
Folder name :
D:\Java\JDK
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 11 Installation and Configuration of Android
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 12 Installation and Configuration of Android
5. Open the folder where you have downloaded Android Studio. Right-click on the
android-studio-bundle-141.1980579 -windows.exe file and select Run as administrator. Your file will
most likely have a different name based on whichever is the current version of Android Studio at
the time.
6. When you get the Do you want the following program to be allowed to make changes to this
computer message, click on Yes. You will see the first window of the installation process.
7. Let's step through the setup process a window at a time. Pictured next is the first window that you
will see when you start the setup process :
8. Click on Next. Now we can see a few options, as in this next screenshot :
9. Make sure that all the options have a tick next to them, and then click on Next.
10. The next window is the license agreement. Click on "I Agree". Take a look at the next screenshot
that shows you the Install Locations window :
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 13 Installation and Configuration of Android
11. In this step, we want to install the Android Studio IDE and Android SDK to the same hard drive
where we installed the JDK. So you might just be able to click on Next at this point. However, if
you've installed the JDK to another drive, then we need to change the drive and the folders we use
at this step too. This isn't strictly essential, but it can avoid problems for some users.
12. For Android Studio Installation Location, choose the root of the drive where you've installed the
JDK followed by \Android Studio. So in my case, this will be D:\Android Studio. For Android
SDK Installation Location, choose the same hard drive and simply add Android\sdk as the
location. So if, like me, you've installed the JDK on D:, then choose D:\Android\sdk. The next
screenshot makes this clear :
13. Click on Next when you have selected your installation locations.
14. Next, you might see the Emulator Setup window as pictured in the next figure. If you do, then
accept the default settings and click on Next; otherwise, you can skip to step 15. Don't worry if you
don't see this screen, it is a minor issue to do with running the Android emulators a bit more
smoothly. Most of the time, you will probably want to use a real device anyway.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 14 Installation and Configuration of Android
15. The next window asks you to choose a start menu folder, just as when we install any new
Windows app. You might want to make a note of this location. Click on Install to accept the
default settings, and Android Studio will begin to install itself and extract the SDK to the
appropriate folder that we selected earlier. This might take some time.
16. When you see the Installation Complete window, click on Next. Now, you will see the following
window :
17. Click on Finish to bring up the second to last window of the installation process. Assuming that
this is your first time using Android Studio, click on the "I do not have a previous version of
Android Studio" or "I do not want to import my settings" radio button and click on OK.
18. Now, in the next screenshot, you get to choose the theme that Android Studio will use. If you like
conventional black texts on white background appearance, then choose IntelliJ, and if you want a
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 15 Installation and Configuration of Android
cool dark style, choose Darcula. You can alter any of these schemes from within Android Studio if
you change your mind later.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 16 Installation and Configuration of Android
This task can be performed using the Android SDK Settings screen, which may be launched from
within the Android Studio tool by selecting the Configure -> SDK Manager Option from within the
Android Studio welcome dialog. Once invoked, the Android SDK screen of the default settings dialog
will appear as shown below :
Immediately after installing Android Studio for the first time it is likely that only the latest released
version of the Android SDK has been installed. To install preview or 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 Figure.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 17 Installation and Configuration of Android
The above figure 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 below :
Within the Android SDK Tools screen, make sure that the following packages are listed as Installed in
the Status column :
· Android SDK Build-tools
· Google Repository
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 18 Installation and Configuration of Android
Once the installation is complete, review the package list and make sure that the selected packages are
now listed as Installed in the Status column. If any are listed as Not installed, make sure they are
selected and click on the Install packages… button again.
An alternative to using the Android SDK settings panel is to access the Standalone SDK Manager
which can be launched using the link in the lower left hand corner of the settings screen. The
Standalone SDK Manager provides a similar list of packages together with options to perform update
and installation tasks :
Emulators are software that mimics the behaviour of real devices. When we develop an app, we
obviously won't have all the possible devices (Android phones, tablets, etc.) available at hand. Because
of this, we run the apps on emulators for testing on various devices. Emulators are also called as
"Android Virtual Devices (AVDs)" in Android Studio. When Android Studio is first installed, there is
no default AVD. We need to create one before testing our apps.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 19 Installation and Configuration of Android
2. When AVD Manager appears, there won't be any AVDs created or installed. Please click on the
Create a Virtual Device button as shown below :
4. You can select various devices with different screen sizes and other hardware properties. You can
select device groups from the left pane as TV, Phone, etc. Phone group is the default selection. In
this group, Nexus 5 is also selected by default. When you click "Next", you'll be presented by
choices for the Android version of the AVD as shown below.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 20 Installation and Configuration of Android
5. The recommended targets start from Android 5.1. We can Android 7.0 with Goole APIs (Nougat)
as shown in the figure. Then, please click "Next" and give a name you like to the AVD.
6. After clicking "Finish", the AVD is created and shown in the AVD Manager as
7. You can now try your Android apps on this AVD, which will accurately mimic the behaviour of a
real Nexus 5 phone. We can run the AVD by clicking the "Play" button shown inside the square in
above Figure
8. The virtual device will appear as in Figure below which you can use like a real Nexus 5 phone.
qqq
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - III
3
3.1 The Development Process
Components and Layouts
An Android app project begins with an idea and a definition of the requirements necessary to realize
that idea. As the project progresses, it goes through design, development, and testing.
Your app
(3 - 1)
Mobile Application Development 3-2 Components and Layouts
5. Building the project : This means creating the executable (file that actually runs on device or the
emulator). This is not difficult as it sounds; Android Studio does the entire job with a single click
6. Trying the app on an emulator.
7. Running the app on a real Android device (optional).
8. Publishing the app on Google Play (optional).
3. Now, you will see the Welcome to Android Studio start menu ,click on Start a new Android
Studio project. You will see the New Project screen pictured next.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-3 Components and Layouts
8. Click on the Next button to continue and you will see the Target Android Devices window:
9. Here, we can see that we have the option of developing an application for a phone, tablet, TV, and
wear. Wear is the range of Android-enabled smartwatches. In the preceding screenshot, in the
grayed-out part at the bottom of the window, we can also see that we can develop for Glass,
Google's trendy Android-enabled glasses, although we would need to install additional files to do
this. In this book, we will be developing for phones and tablets, so the already selected option is
just what we need. The only other thing we need to choose on this screen is the Minimum SDK.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-4 Components and Layouts
We already know that the Android SDK is a collection of packages of code that we will be using to
develop our apps. Like any good SDK, the Android SDK is regularly updated, and each time it
gets a significant update, the version number is increased. Simply put, the higher the version
number, the newer the features you get to use; the lower the version number, the more devices
our app will work on. For now, the default setting API 15: Android 4.0.3 (IceCreamSandwich) will
give us lots of great features and at least 90% compatibility with the Android devices that are
currently in use.
10. Click on the Next button. Now we can see the Add an activity to Mobile window :
11. An Activity class is a special Java class and every Android app must have at least one. It is the
part of the code where our app will start when it is launched by the user, and this also handles
any interaction with the user. The options on this screen provide different ready-made templates of
the Activity class code in order to give programmers a fast start when creating various types of
apps. As we are starting from scratch, the most appropriate option for us is Blank Activity. Make
sure that Blank Activity is selected by clicking on it and then clicking on Next. Now, take a look at
the Customize the Activity window :
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-5 Components and Layouts
12. The Customize the Activity window gives us four things. It is perfectly possible to leave them all
at their default settings. Activity Name is the name of the class that will contain our code. Name
the activity MyActivity.
13. The next field is Layout Name. Android UI layouts are usually defined in a separate XML text file,
not with our Java code. The layout name is what this file will be called. Name the layout
my_layout.
14. The next field is Title. This is different than the Activity Name field and will be used by Android
on the device's screen as the name of the app. Name the title My App.
15. Finally the Menu Resource Name. Menus are the pop-up options that you get on Android when
you click on the menu button. They might also be shown on the topmost bar of the app known as
the action bar. This varies depending on the version of Android a device is running. These are
considered to be part of the UI as well and are usually defined in this separate XML file. Name the
menu file my_menu.
16. Click on the Finish button, and Android Studio will now create a project for us based on our
choices.
Lets get familier with the main sections of Android Studio
1. Main Sections of the IDE : Android Studio is a sophisticated tool and it has dozens of properties
to make app development easier. The main sections of Android Studio is as shown in Figure 3.1.2
Section 1. The project files and folders can be viewed from here. In addition, new files can be added
from this pane. We need to double-click on the filenames here to open them in the middle pane. The
project structure will be explained in detail in the next subsection.
Section 2. The opened files can be activated from the tabs located here for viewing in the middle pane
Section 3. This is the middle pane. Contents of the active files can be viewed and changed from here.
For the project shown in Figure 3.1.2, the file called "MainActivity.java" is the active tab in Section 2
therefore the middle pane in Section 3 shows the contents of this "MainActivity.java" file.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-6 Components and Layouts
Section 4. This section is also controlled via tabs. The developer can switch project files, structures,
captures and favourites for viewing in the left pane.
Section 5. The current or previous compilation, building or debugging processes are shown here. For
the snapshot of Figure 3.1.2, it is indicated that the "Gradle build finished in 14 seconds". Gradle is the
build system of Android Studio. Therefore, the message says that the building engine completed its
previous task in 14 seconds.
Section 6. This is the Run button of Android Studio. When we set up the user interface and write the
Java code of a project, we click this button to make the Android Studio build the project (which means
creating the executable file from project files) and then we can run it on an emulator or on a real
device.
2. The Tool Windows : In addition to the project view tool window, Android Studio also includes a
number of other windows which, when enabled, are displayed along the bottom and sides of the
main window. The tool window quick access menu can be accessed by hovering the mouse
pointer over the button located in the far left hand corner of the status bar (Fig.3.1.3) without
clicking the mouse button(pointed by the arrow).
Selecting an item from the quick access menu will cause the corresponding tool window to appear
within the main window. Alternatively, a set of tool window bars can be displayed by clicking on the
quick access menu icon in the status bar. These bars appear along the left, right and bottom edges of
the main window (as indicated by the arrows in Fig 3.1.4) and contain buttons for showing and hiding
each of the tool windows. When the tool window bars are displayed,a second click on the button in the
status bar will hide them.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-7 Components and Layouts
Fig. 3.1.5 Settings menu for the project view tool window
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-8 Components and Layouts
Fig. 3.1.5 shows the settings menu for the project versions of the application, or multiple builds to
view tool window(pointed by arrow). Options are target different device categories).
available, for example, to undock a window and to
TODO - As the name suggests, this tool provides a
allow it to float outside of the boundaries of the
place to review items that have yet to be completed
Android Studio main window and to move and
on the project. Android Studio compiles this list by
resize the tool panel.
scanning the source files that make up the project to
All of the windows also include a far right button look for comments that match specified TODO
on the toolbar providing an additional way to hide patterns. These patterns can be reviewed and
the tool window from view. A search of the items changed by selecting the File -> Settings… menu
within a tool window can be performed simply by option and navigating to the TODO page listed
giving that window focus by clicking in it and then under Editor.
typing the search term (for example the name of a
Messages - The messages tool window records
file in the Project tool window). A search box will
output from the Gradle build system (Gradle is the
appear in the window's tool bar and items matching
underlying system used by Android Studio for
the search highlighted.Android Studio offers a wide
building the various parts of projects into runnable
range of window tool windows, the most commonly
applications) and can be useful for identifying the
used of which are as follows:
causes of build problems when compiling application
Project - The project view provides an overview of projects.
the file structure that makes up the project allowing
Android Monitor - The Android Monitor tool
for quick navigation between files. Generally, double
window provides access to the Android debugging
clicking on a file in the project view will cause that
system. Within this window tasks such as monitoring
file to be loaded into the appropriate editing tool.
log output from a running application, taking
Structure - The structure tool provides a high level screenshots and videos of the application,stopping a
view of the structure of the source file currently process and performing basic debugging tasks can be
displayed in the editor. This information includes a performed. The tool also includes real-time GPU,
list of items such as classes, methods and variables in networking, memory and CPU usage monitors.
the file. Selecting an item from the structure list will
Android Model - The Android Model tool window
take you to that location in the source file in the
provides a single location in which to view an
editor window.
exhaustive list of the different options and settings
Captures - The captures tool window provides access configured within the project. These can range from
to performance data files that have been generated by the more obvious settings such as the target
the monitoring tools contained within the Android Android SDK version to more obscure values such
Monitor tool window. as build configuration rules.
Favorites - A variety of project items can be added to Terminal - Provides access to a terminal window on
the favorites list. Right-clicking on a file in the project the system on which Android Studio is running. On
view, for example, provides access to an Add to Windows systems this is the Command Prompt
Favorites menu option. Similarly, a method in a interface, while on Linux and Mac OS X systems this
source file can be added as a favourite by takes the form of a Terminal prompt.
right-clicking on it in the Structure tool window.
Run - The run tool window becomes available when
Anything added to a Favorites list can be accessed
an application is currently running and provides a
through this Favorites tool window.
view of the results of the run together with options
Build Variants - The build variants tool window to stop or restart a running process.If an application
provides a quick way to configure different build is failing to install and run on a device or emulator,
targets for the current application project (for this window will typically provide diagnostic
example different builds for debugging and release information relating to the problem.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-9 Components and Layouts
Event Log - The event log window displays messages relating to events and activities performed
within Android Studio. The successful build of a project, for example,or the fact that an application is
now running will be reported within this tool window.
Gradle Console - The Gradle console is used to display all output from the Gradle system as projects
are built from within Android Studio. This will include information about the success or otherwise of
the build process together with details of any errors or warnings.
Gradle - The Gradle tool window provides a view onto the Gradle tasks that make up the project
build configuration. The window lists the tasks that are involved in compiling the various elements of
the project into an executable application. Right-click on a top level Gradle task and select the Open
Gradle Configmenu option to load the Gradle build file for the current project into the editor.
3. Fundamental User Interface Design : Anroid Studio provides an easy way of designing user
interfaces. The file named "activity_main.xml" located under the "res/layout" folder contains all the
layout information of the current activity. If we try to open an .xml file outside of Android Studio,
it is opened by a text editor or a browser. However, when we open an .xml file in Android Studio,
it reads the .xml file and shows the corresponding activity layout with its components. In order to
open the activity_main.xml in Android Studio, double-click on it in the project explorer and the
activity layout will be displayed in the middle pane as shown below :
As you can see, the layout of the activity is shown in the middle pane. The name of the app appears at
the top of the activity. The default empty activity contains a default text which is shown inside the
circle in the above figure. At the left top of the middle pane, there exists a tab called "Palette" indicated
inside the rectangle in the figure. When we click on this tab, the palette shown in Figure Fig. 3.1.7
appears from which we can add all possible user interface objects and layout templates to the activity.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 10 Components and Layouts
Let's position this text, comprised of a TextView widget, to the middle of the view. For this, select this
TextView and then drag and drop to the middle by the help of the guiding lines as shown below :
After the drag and drop operation, the TextView will be kept selected. We can now change the
properties of the TextView using the Properties pane which is at the right of the Layout view as shown
inside the rectangle in Fig. 3.1.9. Click the arrow shown inside the circle in this figure to open the basic
editable properties of the TextView.
In order to build and run the project, please click the "Run" button as indicated by the arrow in
Fig. 3.1.10 The emulator and device selection dialog shown in Fig. 3.1.11 will appear. When the
emulator starts running, you will see a Nexus 5 screen as shown in Fig. 3.1.12.
Fig. 3.1.11 Selecting the target for running our first app
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 13 Components and Layouts
Fig. 3.1.13 Switching among different ways of viewing files and folders
When the selection is the "Android" mode, the default files and folders shown in Fig. 3.1.14
You can use the arrows (shown inside the circle in the figure)for viewing the contents of folders. The
default folders (shown inside the rectangles in Fig. 3.1.14) and their contents are explained as follows :
1. manifests folder : This folder has the AndroidManifest.xml file inside. This file contains the
configuration parameters of the project such as permissions, services and additional libraries.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 14 Components and Layouts
2. java folder : The source code files written in Java programming language reside in this folder. You
can see that the java file of the activity named "MainActivity.java" is automatically created in this
folder.
3. res folder : The resource files are contained in this folder. Resources basically mean all the needed
files except the source code. The media, image and layout files residing in the resources folder are
accessed via Java code written in MainActivity.java.
The floder structure includes different types Clik on the arrow
of files here and choose
the project option
If you browse through the folder structure, to see the files and
you'll see that the wizard has created various folders that make
up your project
types of files and floders for you :
This is the
· Java and XML soure files : These are the name of
activity and layout files for your app. the project
Some of the key files and directory(folders) are as shown in Fig. 3.1.16 : (See Fig. on next page)
com/hfad/myfirstapp
arc
The src folder contains
source code you write
and edit. R.java
main
Other less edited folders include : 1. Activities : Activities are said to be the
· gen - Generated Java code files, this library is for presentation layer of our applications. An activity
Android internal use only. is the first stepping stone is building an Android
· assets - Uncompiled source files associated with
user application. The UI of our application is
your project; Rarely used. build around one or more extensions of the
Activity class.
· bin - Resulting application package files associated
An activity in android is like your computer
with your project once it's been built.
welcome screen which presents single user
· libs - Before the introduction of Gradle build display. In other words, Activity in android
system, this directory was used for any secondary represents single screen with a user interface. We
libraries (jars) you might want to link to your app. can understand Activity in terms of web
applications For example: We creates numbers of
3.2 Components of Android Application
web pages to build complete web application,
Almost all popular applications are interactive. These similarly on the other hand android application
applications interact with the user, and, depending on consist of several Activities to run as a complete
the data supplied by the user, desired actions and/or application. There is one "main" activity. All
processing are performed. The user interface controls other activities are child activities. There is a
thus play a major role in getting feedback from the stack called back stack. Whenever, there is a new
user. Application components are the ones which window is started, previous activity is pushed to
when combined together, offers you a brilliant the back stack and it is stopped until the new
Android application. So, these components exactly act activity is done. As soon as the back key of your
as the building blocks of an Android application. The device is pressed, new activity is popped out of
information regarding all the application components stack and destroyed. Now previous activity
is provided in the manifest file, which is resumes.
AndroidManifest.xml. This file will help you in 2. Services : These are like invisible workers of our
understanding the use of each and every application app. These components run at backend, updating
component and how do they interact with each other. your data sources and Activities, triggering
Notification and also broadcast Intents. They also
Android provides four important components to
perform some tasks when applications are not
build any android application.
active. This component is responsible for
· Activities
handling the time taking operations which
· Services
generally runs in the background of the
· Intent and broadcast receivers operating system (in this case, Android). The
· Content Providers simple example of the service component is that
Activities when you play music on your mobile phone, you
Views / User interface Must have in any app will be able to use other applications too. A
Intents service can take two forms:
a. Started : After a service starts, it can run
indefinitely and usually performs single
Services
operation. No result is returned to user. For
Content provider Can have in any app
example, uploading a file. After the task is
Broadcast receiver
completed, it should terminate itself.
Activities Intents and broadcast b. Bound : In this case, a component is bound
receivers
to a service so that a particular task can be
Widgets and notifications completed. This type of service provides a
client-server like interface. Requests can be
send, receive requests, and return result to
Services Content providers
the user. Inter process communication is
Fig. 3.2.1 Components of android application achieved through this service.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 17 Components and Layouts
3. Intents and Broadcast Receivers - Android Intent is the message that is passed between
components such as activities, content providers, broadcast receivers, services etc. It is generally
used with startActivity( ) method to invoke activity, broadcast receivers etc. It binds individual
components to each other. Broadcast Receivers simply respond to broadcast messages from other
applications or from the system itself. These messages are sometime called events or intents. For
example, applications can also initiate broadcasts to let other applications know that some data has
been downloaded to the device and is available for them to use, so this is broadcast receiver who
will intercept this communication and will initiate appropriate action. another example is, when
your device boots up or switched on, the system generates a broadcast to all apps. There should be
a procedure or should be something which can receive these broadcasts. These receptors are called
broadcast receivers. There are two types of broadcasts:
a. Normal Broadcasts : These are asynchronous in nature. Many receivers can be activated at the
same time which doesn't have any defined order. But they are very efficient.
b. Ordered Broadcasts : They are synchronous in nature. Broadcast received by one receiver passes
it to other receivers. Broadcasts are delivered to receiver on one-to-one and sequential basis. Either
receiver will pass result to another receiver or it may completely destroy the broadcast.
4. Content Providers - It is used to manage and persist the application data also typically interact
with SQL database. They are also responsible for sharing the data beyond the application
boundaries. The Content Providers of a particular application can be configured to allow access
from other applications, and the Content Providers exposed by other applications can also be
configured. With content providers we can save data in SQLite database, on the web or any other
persistent storage location, where application can easily access the data. This component is useful in
reading and writing private data. For example: we can read and write important reminders or
notes in database(within an application).
5. Android Widgets and Notifications : Android App widgets are the small application views. These
views can be embedded into other applications. They can receive updates on periodic basis. A
widget is a quick view of your app's functionality and data. This view is accessible from home
screen of your device. Now widgets are of following types :
Widgets
d. Hybrid Widgets : These Android widgets The third approach, the combined approach, is highly
combine features of all of the above three. preferred.
· Notification, as the name says keeps the user aware
The graphical user interface for an Android app is
of events going on. User is kept informed like any
built using a hierarchy of View and ViewGroup
news channel. For e.g, everyone of us know about
objects.
facebook or whatsapp, now notification system of
· A View is an interactive UI component (or widget
app is responsible for informing you about any new
or control), such as button and text field. It controls
friend request, chat request, or a new message from
a rectangular area on the screen. It is responsible for
say, dvs or xyz, etc.
drawing itself and handling events (such as clicking,
There are a few other application components that
entering texts). Android provides many ready-to-use
you should be aware of. These application
Views such as TextView, EditText, Button,
components include fragments, views, layouts,
RadioButton, etc, in package android.widget. You
intents, resources, and manifest. All of these
can also create your custom View by extending
components are used for the creation of above
android.view.View.
components.
· A ViewGroup is an invisible container used to layout
Application the View components. Android provides many
S.No. Description
Components ready-to-use ViewGroups such as LinearLayout,
1 Fragments Represents the fragments of
RelativeLayout, TableLayout and GridLayout in
a user interface in the package android.widget. You can also create your
Activity component custom ViewGroup by extending from
2 Views Includes the user interface android.view.ViewGroup.
elements like buttons, Views and ViewGroups are organized in a single tree
drop-down lists, etc. structure called view-tree. You can create a view-tree
3 Layouts Controls the screen format either using programming codes or describing it in a
based on different XML layout file.
hierarchies of the views
Takes care of the
appearance of the views on Layout view groups
the screen
android.view.View
4 Intents Wires the messages of
different components Layouts are a type of
together ViewGroup. ViewGroup
is a subclass of View.
android.view.ViewGroup
5 Resources Includes external elements
like drawable or editable
pictures, strings, and
constants
android.widget. android.widget.
LinearLayout FrameLayout
3.2.1 Creating the user Interface
There are three approaches to creating user interfaces The views for a screen are organized in a hierarchy.
in Android. At the root of this hierarchy is a ViewGroup that
1. You can create user interfaces entirely in Java contains the layout of the entire screen. The view
code group's child screens can be other views or other
view groups as shown in the following figure.
2. Entirely in XML
3. Combining both methods (defining the user 1. The root view group.
interface in XML and then referring and 2. The first set of child views and view groups
modifying it through Java code). whose parent is the root.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 19 Components and Layouts
· TableLayout : In this layout, the screen is assumed FrameLayout Displays a single view; that is, the
to be divided in table rows, and each of the child next view replaces the previous
view and hence is used to
elements is arranged in a specific row and column.
dynamically change the children in
· GridLayout : In this layout, child views are the layout
arranged in a grid format, that is, in the rows and
TableLayout Organizes its children in tabular
columns pattern. The views can be placed at the form
specified row and column location. Also, more than
one view can be placed at the given row and GridLayout Organizes its children in grid
format
column position.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 20 Components and Layouts
Layouts
Linear layout Relative layout Table layout Frame layout Grid layout Absolute layout
The layout editoris used to edit the layout file. You can drag and drop view objects into a graphical
pane, and arrange, resize, and specify properties for them. You immediately see the effect of changes
you make.
To use the layout editor, open the XML layout file. The layout editor appears with the Design tab at
the bottom highlighted.
(If the Text tab is highlighted and you see XML code, click the Design tab.) For the Empty Activity
template, the layout is as shown in the figure below.
1. XML layout file : The XML layout file, typically named activiy_main.xml file.Double-click it to
open the layout editor.
2. Palette of UI elements (views) : The Palette pane provides a list of UI elements and layouts.Add
an element or layout to the UI by dragging it into the design pane.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 21 Components and Layouts
3. Design toolbar : The design pane tool bar provides buttons to configure your layout appearance in
the design pane and to edit the layout properties.See the figure 3.3.6 for details.
4. Properties pane : The Properties pane provides property controls for the selected view.
5. Property control : Property controls correspond to XML attributes. Shown in the figure is the Text
property of the selected TextView, set to Hello World!.
6. Design pane : Drag views from the Palette pane to the design pane to position them in the layout.
7. Component Tree : The Component Tree pane shows the view hierarchy. Click a view or view
Group in this pane to select it.The figure shows the TextView selected.
8. Design and Text tabs Click Design to see the layout editor, or Text to see XML code.The layout
editor's design toolbar offers a row of buttons that let you configure the appearance of the layout :
1. Design, Blueprint and Both : Click the Design icon (first icon) to display a color preview of your
layout. Click the Blueprint icon (middle icon) to show only outlines for each view. You can see
both views side by side by clicking the third icon.
2. Screen orientation : Click to rotate the device between landscape and portrait.
3. Device type and size : Select the device type (phone/tablet, Android TV, or Android Wear) and
Screen configuration (size and density).
4. API version : Select the version of Android on which to preview the layout.
5. App theme : Select which UI theme to apply to the preview.
6. Language : Select the language to show for your UI strings. This list displays only th languages
available in the string resources.
7. Layout Variants : Switch to one of the alternative layouts for this file, or create a new one.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 22 Components and Layouts
In above code snippet, the orientation is defined as vertical, so this aligns all its child layout / views
vertically.
Steps :
1. Create a new android application using android studio and give names as LinearLayout.
2. Now open an activity_main.xml file from \res\layout path and write the code like as shown below:
activity_main.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:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical" >
<EditText
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 23 Components and Layouts
android:id="@+id/txtTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To"/>
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"/>
<EditText
android:id="@+id/txtMsg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="Message"/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Send"/>
</LinearLayout>
3. After creation of layout, load the XML layout resource from activity onCreate() callback
method,for that open main activity file Output :
Attribute Description
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 24 Components and Layouts
android:layout_marginTop This is the extra space on the top side of the layout.
android:layout_marginBottom This is the extra space on the bottom side of the layout.
android:layout_marginLeft This is the extra space on the left side of the layout.
android:layout_marginRight This is the extra space on the right side of the layout.
android:layout_weight This specifies how much of the extra space in the layout
should be allocated to the View.
1. Orientation :
· The orientation attribute used to set the childs/views horizontally or vertically.
· In Linear layout default orientation is vertical.
· The valid values for this attribute are horizontal and vertical.
· If the value of the android:orientation attribute is set to vertical , the children in the linear layout are
arranged in a column layout, one below the other.
· If the value of the android:orientation attribute is set to horizontal, the controls in the linear layout
are arranged in a row format, side by side.
· The orientation can be modified at runtime through the setOrientation() method. That is, by supplying
the values HORIZONTAL or VERTICAL to the setOrientation() method, we can arrange the children
of the LinearLayout in row or column format, respectively as shown below :
For vertical -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"> <!-- Vertical Orientation set -->
<!-- Put Child Views like Button here -->
</LinearLayout>
For horizontal -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"> <!-- Horizontal Orientation set -->
<!-- Child Views are here -->
</LinearLayout>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 25 Components and Layouts
<Button
android:text="BUTTON"
android:layout_width="wrap_content"
android:layout_height="wrap_content" Output
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 1"
android:paddingTop="10px"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 2"
android:paddingTop="10px"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 3"
android:paddingTop="10px"/>
</LinearLayout>
<Button
android:text="BUTTON"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 26 Components and Layouts
Output
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 1"
android:paddingTop="10px"
android:paddingLeft="10px"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 2"
android:paddingTop="10px"
android:paddingLeft="10px"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 3"
android:paddingTop="10px"
android:paddingLeft="10px"/>
</LinearLayout>
2. gravity :
· The gravity attribute is an optional attribute for aligning the content within a control. For example, to
align the text of a control to the right, we set the value of its android:gravity attribute to right .
· The valid options for android:gravity include left, center, right, top, bottom,
center_horizontal , center_vertical , fill_horizontal , and fill_vertical.
· The task performed by few of the above options is as follows :
¡ center_vertical : Places the object in the vertical center of its container, without
changing its size
¡ fill_vertical : Grows the vertical size of the object, if needed, so it completely fills its container
¡ center_horizontal : Places the object in the horizontal center of its container,without changing its size
¡ fill_horizontal : Grows the horizontal size of the object, if needed, so it completely fills its container
¡ center : Places the object in the center of its container in both the vertical and horizontal axis,
without changing its size
Example :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right"
android:orientation="horizontal">
<!--Button Child View Here--->
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 27 Components and Layouts
Output
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click2"
android:id="@+id/click2"
android:background="#0e7d0d" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click1"
android:id="@+id/click"
android:background="#761212" />
</LinearLayout>
3. layout_weight :
· The layout weight attribute specify each child control's relative importance within the parent linear
layout.
· The weight attribute affects the size of the control. That is, we use weight to assign the capability to
expand or shrink and consume extra space relative to the other controls in the container.
· The values of the weight attribute range from 0.0 to 1.0 , where 1.0 is the highest value. Let's suppose
a container has two controls and one of them is assigned the weight of 1. In that case, the control
assigned the weight of 1 consumes all the empty space in the container, whereas the other control
remains at its current size. If we assign a weight of 0.0 to both the controls, nothing happens and the
controls maintain their original size.
· If both the attributes are assigned the same value above 0.0, both the controls consume the extra space
equally. Hence, weight lets us apply a size expansion ratio to the controls.
Example :
<?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="horizontal">
<!--Add Child View Here--->
<Button Output
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Weight 2"
android:background="#5b39c6"
android:layout_margin="5dp"
android:id="@+id/button"
android:layout_weight="2" />
<Button
android:layout_width="wrap_content"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 28 Components and Layouts
android:layout_height="wrap_content"
android:background="#00ff00"
android:layout_margin="5dp"
android:layout_weight="1"
android:text="Weight 1" />
</LinearLayout>
4. WeightSum :
· weightSum is the sum up of all the child attributes weight.
· This attribute is required if we define weight property of the childs.
Example :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="3"
android:orientation="horizontal">
<!--Add Child View Here--->
</LinearLayout>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 29 Components and Layouts
padding
Layout
padding
padding
paddingLeft
Layout
paddingRight
paddingBottom
In this example we have used one TextView and 4 Button. The orientation is set to vertical.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 30 Components and Layouts
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Linear Layout (Without Weight)"
android:id="@+id/textView"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:background="#009300" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
Output
android:background="#e6cf00" />
BUTTON 4
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 4"
android:background="#e100d5" />
</LinearLayout>
Example 2 : In this example of linear layout we have used weight property.
android:weightSum="5"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Linear Layout (With Weight)"
android:id="@+id/textView"
android:layout_gravity="center_horizontal"
android:layout_weight="0"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:background="#009300"
android:layout_weight="1"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:background="#e6cf00"
Output
android:layout_weight="1"/>
Linear Layout (With Weight)
<Button
BUTTON 1
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 3"
BUTTON 2
android:background="#0472f9"
android:layout_weight="1"/>
BUTTON 3
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content" BUTTON 4
android:text="Button 4"
android:background="#e100d5"
android:layout_weight="1"/>
</LinearLayout>
Example 3 : Mixed Example With Horizontal And Vertical Orientation Properties :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 32 Components and Layouts
android:layout_gravity="center"
android:orientation="vertical"
tools:context=".LinearLayout" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="10px"
android:paddingTop="20px"
android:text="LOGIN" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="20px">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10px"
android:paddingTop="20px"
android:text="Username" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:layout_marginLeft="40px"
android:paddingTop="20px" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="20px"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:paddingTop="20px"
android:paddingLeft="10px"/>
<EditText
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 33 Components and Layouts
android:layout_width="wrap_content" Output
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="40px"
android:layout_weight="0.50"
android:paddingTop="20px" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="20px"
android:paddingTop="10px"
android:text="BUTTON" />
</LinearLayout>
android:layout_y="29px">
</AbsoluteLayout>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/btn1"
android:text="Login"
android:textColor="@color/colorPrimary"
android:layout_x="50px"
android:layout_y="361px" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/btn2"
android:textColor="@color/colorPrimary"
android:text="Register"
android:layout_x="350px"
android:layout_y="361px" />
</AbsoluteLayout>
The graphical representation of the above code is as follows.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 35 Components and Layouts
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 36 Components and Layouts
Output
· Using different tags in frame layout you can also
determine whether to measure all the children or
just those that are in the visible or in the invisible
state when measuring. These can be simply defined
within the XML layout resources and in Java' s for
programmatically application. Understanding layout
and when to use these layouts is important for
good android application design. When this layout
is used correctly, it becomes the fundamental layout
in which many interesting android application user
interfaces can be designed.
¡ When the child content is too large to draw
within the bounds of the layout, it uses the
view scroll view to organise the control within
the interface.
¡ When we need a frame around underlying
views for our interface, then frame layout
provides the foreground draw able facility in
3.3.3 Android Frame Layout
addition to the normal ackground,this task is
done with the help od XML' s attributes.
Frame layout
¡ If multiple child view occurs within the frame
layout then they are drawn in such a order
View such that the last one child view on the top,
which is done using the frame layout.
¡
Frame layout are the normal layout of choice
especially when you want to use the overlapped
view of the design.
Fig. 3.3.6 Frame layout supports one view inside it
· Frame Layout is one of the simplest layout to
· Frame layout is the simple layout representation organize view controls. They are designed to block
used to organise the control within the user an area on the screen.
interface of android application. When we want to
· Frame Layout should be used to hold child view,
display a single item on the display and block out
because it can be difficult to display single views at
the other items then frame layout tool is used.
a specific area on the screen without overlapping
Sometimes it is difficult to organize child views in a
each other.
way that is scalable to different screen sizes without
the children over lapping each other, in that case · Multiple children can be addes to a FrameLayout
the frame layout is used a it can hold a single child and control their position by assigning gravity to
view and can block the other view. each child, using the android:layout_gravity
· We can also add multiple children using frame attribute.
layout and also control their position within this by · FrameLayout is used to display a single View.
simply assigning the gravity tags to each child. In · The View added to a FrameLayout is placed at the
this child view are drawn in the stack with the top-left edge of the layout. Any other View added
feature of stack the recently added is on the top to the FrameLayout overlaps the previous View ;
and also last one added is removed from the top. that is, each View stacks on top of the previous one.
The size of the frame layout depends on the size of
its largest child whether it is visible or not.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 37 Components and Layouts
FrameLayout
Component 1
Component 2
Component 3 Component 4
</FrameLayout>
Lets see different properties of Frame Layout which will be used while designing Android App UI :
1. android:id
· This attribute will give the unique identity to the frame layout.
· When you want to access the frame layout from the JAVA class, this id will give you the reference
via findViewById() method.
· Value of this attribute should be unique across the whole android app to reduce the complexity.
Example to use id:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frame"
android:layout_width="200dp"
android:layout_height="300dp"
android:foreground="@color/colorAccent"
tools:context=".MainActivity">
2. android:foreground
· Foreground defines the drawable to draw over the content and this may be a color value.
· Possible color values can be in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb". This all are
different color code model used.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 38 Components and Layouts
Example: To set the blue color for foreground of frameLayout so the ImageView and other child views
of this layout will not be shown.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:foregroundGravity="fill"
android:foreground="#4363d8"><!--foreground color for a FrameLayout-->
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
>
<!-- Imageview will not be shown because of foreground color which is drawn over it-->
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginBottom="10dp"
android:src="@mipmap/ic_launcher"
android:scaleType="centerCrop"
/>
Output
<!--Textview will not be shown because of foreground color is drawn over it-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="vrs"/>
</LinearLayout>
</FrameLayout>
3. android:foregroundGravity
· This defines the gravity to apply to the foreground drawable.
· Default value of gravity is fill.
· We can set values in the form of "top", "center_vertical" , "fill_vertical", "center_horizontal",
"fill_horizontal", "center", "fill", "clip_vertical", "clip_horizontal", "bottom", "left" or "right" .
· It is used to set the gravity of foreground. We can also set multiple values by using "|". Ex:
fill_horizontal|top .Both the fill_horizontal and top gravity are set to framelayout.
4. android:visibility
· We can apply this attribute to any child of the framelayout.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 39 Components and Layouts
<TextView
android:layout_width="100dp"
android:layout_height="50dp"
android:visibility="invisible"
android:textSize="20sp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:background="@color/colorPrimary"
android:textColor="#fff"
android:text="I am TextView" />
</FrameLayout>
You can see that Textview is present (blue border rectangle) but we can not see it.
5. android:measureAllChildren :
· This determines whether to measure all children including gone state visibility or just those which are
in the visible or invisible state of measuring visibility.
· The default value of measureallchildren is false. We can set values in the form of Boolean i.e. "true"
OR "false".
· This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in
the form "?[package:][type:]name") containing a value of this type.
· If measureallchildren is set true then it will show actual width and height of frame layout even if the
views visibility is in gone state.
Example : To set the ImageView visibility to gone and measureAllChildren to true.
activity_main.xml
Note: Make sure you have image in Drawable folder.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frame"
android:orientation="vertical" android:layout_width="wrap_content"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 40 Components and Layouts
android:layout_height="wrap_content"
android:measureAllChildren="true"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:src="@drawable/ic_launcher"/>
</FrameLayout>
code of MainActivity.java . Here we have used Toast to display height and width on screen.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
FrameLayout frame=(FrameLayout)findViewById(R.id.frame);
frame.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int width = frame.getMeasuredWidth();
int height = frame.getMeasuredHeight();
Toast.makeText(getApplicationContext(),"width="+width+" height="+height,Toast.LENGTH_SHORT).show();
}
}
Otuput
Explanation of Example : It measures all the children in the layout. For ex: If we setVisiblity of an
view be gone and set measuresAllChildren property to be true, then also it will also count to that view
which is not visible, but if we set the measuresAllChildren property to be false, then it will not count
to that view which is gone.
Example 1 : Frame Layout using layout gravity. Here we will put textview at different position in
Frame Layout. Below is the code and final output :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 41 Components and Layouts
<TextView android:text="LeftTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RightTop"
android:layout_gravity="top|right" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="CentreTop"
android:layout_gravity="top|center_horizontal" />
<TextView android:text="Left"
android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Right"
android:layout_gravity="right|center_vertical" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Centre"
android:layout_gravity="center" />
<TextView android:text="LeftBottom"
android:layout_gravity="left|bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RightBottom"
android:layout_gravity="right|bottom" />
<TextView android:layout_height="wrap_content" Output
android:layout_width="wrap_content"
android:text="CenterBottom"
android:layout_gravity="center|bottom" />
</FrameLayout>
Step 3 : Let the MainActivity.java has default Android code or
add the below code :
packagevrs.com.A12;
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);
}
}
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 42 Components and Layouts
Example :
activity_main.xml
open main activity file MainActivity.java from \java\com.vrs.framelayout path and write the code like
as shown below.
MainActivity.java
package com.vrs.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 43 Components and Layouts
· A row can have zero or more controls, where each control is called a cell.
· The number of columns in a TableLayout is determined by the maximum number of cells in any row.
· The width of a column is equal to the widest cell in that column. All elements are aligned in a
column; that is, the width of all the controls increases if the width of any control in the column is
increased.
· Table Layout containers do not display a border line for their columns, rows or cells. A Table will
have as many columns as the row with the most cells.
· TableLayout is a ViewGroup subclass which is used to display the child View elements in rows and
columns.
· TableLayout will position its children elements into
Row 1 Row 1 Row 1
rows and columns and it won't display any border Column 1 Column 2 Column 3
lines for rows, columns or cells.
Row 2 Row 2
· The TableLayout in android will work same as Column 1 Column 2
HTML table and table will have as many columns as
Row 3
the row with the most cells. The TableLayout can be Column 1
explained as <table> and TableRow is like <tr>
Fig. 3.3.8 Row and Column in Table Layout Android
element.
</TableRow>
</TableLayout>
android:stretchColumns TableLayout When a column width is less and you need to expand(or stretch) it,
you use this attribute.
android:shrinkColumns TableLayout When you do not need the extra space in a column, you can use
this attribute to shrink and remove the space.
android:collapseColumns TableLayout It hides the column of the given index in the TableLayout.
android:layout_span Any View inside If a view takes only one column width but when you want your
the TableRow view to take more than one column space, then you can use this
attribute.
android:layout_column Any view inside When you want your view present in the first TableRow to appear
the TableRow below the other TableRow's view, you can use this attribute.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 46 Components and Layouts
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/simpleTableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1"> <!-- stretch the second column of the layout-->
android:id="@+id/firstRow"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" 2. whenandroid:stretchColumns="2"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Text 1"
android:textColor="#000"
android:textSize="12dp" />
<TextView
android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
3. whenandroid:stretchColumns="*"
android:layout_height="wrap_content"
android:background="#FF0000"
android:padding="18dip"
android:text="Text 2"
android:textColor="#000"
android:textSize="14dp" />
</TableRow>
</TableLayout>
1. shrinkColumns :
· We can shrink or reduce the width of the
column(s) using the android:shrinkColumns attribute in the TableLayout.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 47 Components and Layouts
· Shrink column attribute is used to shrink or reduce the width of the column's. We can specify either a
single column or a comma delimited list of column numbers for this attribute. The content in the
specified columns word-wraps to reduce their width.
· If the value is 0 then the first column's width shrinks or reduces by word wrapping its content.
· If the value is 0,1 then both first and second columns are shrinks or reduced by word wrapping its
content.
· If the value is '*' then the content of all columns is word wrapped to shrink their widths.
Examples :
· android:shrinkColumns="0": The first column's width shrinks or reduces by wordwrapping its
content.
· android:shrinkColumns="*" : The content of all columns is word-wrapped to shrink their widths.
Example :
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="0"> <!-- shrink the first column of the layout-->
</TableRow>
</TableLayout>
2. collapseColumns :
· We can make the column(s) collapse or become invisible through the android:collapseColumns
attribute in the TableLayout.
· We can specify one or more comma-delimited columns for this attribute. These columns are part of
the table information but are invisible.
· We can also make column(s) visible and invisible through coding by passing the Boolean values false
and true , respectively, to the setColumnCollapsed() method in the TableLayout.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 48 Components and Layouts
For example:
· android:collapseColumns="0" :
¡ The first column appears collapsed; that is, it is part of the table but is invisible. It can be made
visible through coding by using the setColumnCollapsed() method.
¡ Collapse columns attribute is used to collapse or invisible the column's of a table layout. These
columns are the part of the table information but are invisible.
¡ If the values is 0 then the first column appears collapsed, i.e it is the part of table but it is invisible.
Example :
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:collapseColumns="0"> <!-- collapse the first column of the table row-->
<!-- first element of the row that is the part of table but it is invisible-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Columns 1"
android:textColor="#000"
android:textSize="18dp" />
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 49 Components and Layouts
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TableRow android:background="#0079D6" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="UserId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="User Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Location" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Abhi" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Pune" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 50 Components and Layouts
android:text="Rohit" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Nasik" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3" />
<TextView
android:layout_width="wrap_content" Output
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Jaya" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Nasik" />
</TableRow>
</TableLayout>
MainActivity.java
package com.vrs.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
android:gravity="center_horizontal">
<TextView
android:layout_width="match_parent" android:layout_height="wrap_content"
android:textSize="18dp" android:text="Row 1" android:layout_span="3"
android:padding="18dip" android:background="#b0b0b0"
android:textColor="#000"/>
</TableRow>
<TableRow
android:id="@+id/tableRow1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 1"
android:layout_weight="1" android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 2"
android:layout_weight="1" android:background="#d3d3d3"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 3"
android:layout_weight="1" android:background="#cac9c9"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
</TableRow>
<!-- Row 3 with 2 columns -->
<TableRow
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal">
<TextView
android:id="@+id/TextView04" android:text="Row 3 column 1"
android:layout_weight="1 android:background="#b0b0b0"
android:textColor="#000000"
android:padding="18dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 3 column 2"
android:layout_weight="1" android:background="#a09f9f"
android:textColor="#000000"
android:padding="18dip" android:gravity="center"/>
</TableRow>
</TableLayout>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 52 Components and Layouts
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 53 Components and Layouts
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 54 Components and Layouts
Again, for the example, we are considering our parent view to be a RelativeLayout with height and
width set as match_parent, therefore it will cover the whole screen of mobile. So the complete
screen is our parent view.
1. android:layout_alignParentTop="true" : If you write this attribute for a View, then that view will
stick to the top of its parent. Since the parent covers the whole screen of mobile therefore, the view
will appear sticking to the top-left of the mobile screen.
<!-- alignParentTop example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1 align parent top"
android:layout_alignParentTop="true"
android:layout_margin="20dp"
android:textSize="20sp"
android:textColor="#000"/>
2. android:layout_alignParentBottom="true" : If you write
this attribute for a View, then that view will stick to the bottom of its parent. Since the our parent
covers the whole screen of mobile therefore, the view will appear sticking to the bottom of the
mobile screen.
<!-- textView is alignParentBottom -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text Here is AlignParentBottom with bottom margin of 120dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="120dp" />
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 55 Components and Layouts
3. android:layout_alignParentLeft="true" : If you write this attribute for a View, then that view will
stick to the left of its parent. Since the parent in our example covers the whole screen of mobile
therefore, the view will appear sticking to the left of the mobile screen.
<!-- align parent left in Android -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text in Parent Left"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentLeft="true"
/>
4. android:layout_alignParentRight="true" : If alignParentRight property is true, then it makes the
right edge of this view match the right edge of the parent. The value of align parent right is either
true or false. Example: android:layout_alignParentRight="true".
<!-- alignRightParent Example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text in Parent Right"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentRight="true"
/>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 56 Components and Layouts
1:android:layout_toLeftOf="@id/main"
2:android:layout_above="@id/main"
2 id=main 3
3:android:layout_below="@id/main"
4:android:layout_toRightOf="@id/main"
1. android:layout_toLeftOf="@id/main" : This tells the new view that you have to be on the left side
of the view whose id is main.
2. android:layout_toRightOf="@id/main" : This tells the
new view that you have to be on the right side of
a
the view whose id is main. b
1. android:layout_alignTop="@id/a" : This aligns the top margin of the new view with the top margin
of the view having id as a.
2. android:layout_alignBottom="@id/a" : This aligns the bottom margin of the new view with the
bottom margin of the view having id as a.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 57 Components and Layouts
3. android:layout_alignLeft="@id/a" : This aligns the left margin of the new view with the left margin
of the view having id as a.
4. android:layout_alignRight="@id/a" : This aligns the right margin of the new view with the right
margin of the view having id as a.
5. android:layout_alignBaseLine="@id/a" : This aligns the text1 of the new view with the text2 of the
view having id as a.
4. above :
· android:layout_above - The control is placed above the referenced control.
Position the bottom edge of the view above the given anchor view ID and must be a reference of the
another resource in the form of id. Example, android:layout_above="@+id/textView" .
For example, suppose a view with id textview2 is what we want to place above another view with id
textview.
<!-- textView2 is placed above textView-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Text2"
android:id="@+id/textView2"
android:layout_above="@+id/textView"
android:layout_marginBottom="100dp"
android:layout_centerHorizontal="true"/>
· The attributes to control the position of a control in relation to other controls are
· android:layout_below - The control is placed below the referenced control.
· android:layout_toLeftOf - The control is placed to the left of the referenced control.
· android:layout_toRightOf - The control is placed to the right of the referenced control.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 58 Components and Layouts
5. alignBottom :
· android:layout_alignBottom - The bottom of the control is set to align with the bottom of the
referenced control.
alignBottom is used to makes the bottom edge of the view match the bottom edge of the given anchor
view ID and it must be a reference to another resource, in the form of id. Example: android:layout_
alignBottom ="@+id/button1?
For example align a view with id textView2 Bottom of another view with id textView..
<!-- textView2 alignBottom of textView -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_centerHorizontal="true"
android:id="@+id/textView2"
android:layout_alignBottom="@+id/textView"
android:text="Text2 alignBottom of Text1"
android:layout_marginBottom="90dp"
/>
6. alignLeft :
· android:layout_alignLeft - The left side of the control is set to align with the left side of the
referenced control.
alignLeft is used to make the left edge of the view match the left edge of the given anchor view ID
and must be a reference to another resource, in the form of Example: android:layout_ alignLeft
="@+id/button1?.
For example align a view with id textView2 left of another view with id textView.
<!-- textView2 alignLeft of textView -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:text="Text2 alignLeft of Text1"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 59 Components and Layouts
android:layout_below="@+id/textView"
android:layout_marginTop="20dp"/>
7. alignRight :
· android:layout_alignRight - The right side of the control is set to align with the right side of the
referenced control.
alignRight property is used to make the right edge of this view match the right edge of the given
anchor view ID and must be a reference to another resource, in the form like this example:
android:layout_alignRight="@+id/button1?
For example align a view with id textView2 right of another view with id textView.
<!-- textView2 alignRight of textView-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:layout_alignRight="@+id/textView"
android:text="Text2 alignRight of Text1"
android:layout_below="@+id/textView"
android:layout_marginTop="20dp"/>
8. alignStart :
· alignStart property is used to makes the start edge of this view match the start edge of the given
anchor view ID and must be a reference to another resource, in the form of like this example:
android:layout_alignStart="@+id/button1?
For example align a view with id textView2 start of another view with id textView.
<!-- Text2 alignStart-->
<TextView
android:layout_width="wrap_content"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 60 Components and Layouts
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:text="Text2 align start of Text1"
android:layout_alignStart="@+id/textView"
/>
9. alignTop :
· android:layout_alignTop - The top of the control is set to align with the top of the referenced control.
alignTop property is used to makes the top edge of this view match the top edge of the given anchor
view ID and must be a reference to another resource, in the form like this example:
android:layout_alignTop="@+id/button1?.
For example align a view with id textView Top of another image with id imageView.
<!--text is align top on Image-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_alignTop="@+id/imageView"
android:text="Text Here is AlignTop on Image"
/>
10. alignParentEnd : If alignParentEnd property is true, then it makes the end edge of this view match
the end edge of the parent. The value of align parent End is either true or false. Example:
android:layout_alignParentEnd="true".
For example textView is simply displayed on Image in the end.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 61 Components and Layouts
11. alignParentStart: If alignParentStart is true, then it makes the start edge of this view match the
start edge of the parent. The value of align parent start is either true or false. Example:
android:layout_alignParentStart="true".
For example textView is simply displayed on parent Image in the right side.
<!-- alignParentStart Example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text in Parent Start"
android:layout_alignTop="@+id/imageView"
android:layout_alignParentStart="true"
/>
12. For spacing, Android defines two attributes: android:layout_margin and android:padding .
· The android:layout_margin attribute defines spacing for the container, while android:padding
defines the spacing for the view. Let's begin with padding.
· android:padding - Defines the spacing of the content on all four sides of the control. To define
padding for each side individually, use android:paddingLeft ,android:paddingRight ,
android:paddingTop , and android:paddingBottom .
· android:paddingTop - Defines the spacing between the content and the top of the control.
· android:paddingBottom - Defines the spacing between the content and the bottom of the control.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 62 Components and Layouts
· android:paddingLeft - Defines the spacing between the content and the left side of the control.
· android:paddingRight - Defines the spacing between the content and the right side of the control.
13. Here are the attributes that define the spacing between the control and the container:
· android:layout_margin - Defines the spacing of the control in relation to the controls or the
container on all four sides. To define spacing for each side individually, we use the
android:layout_marginLeft , android:layout_marginRight , android:layout_marginTop , and
android:layout_marginBottom options.
· android:layout_marginTop - Defines the spacing between the top of the control and the related
control or container.
· android:layout_marginBottom - Defines the spacing between the bottom of the control and the
related control or container.
· android:layout_marginRight - Defines the spacing between the right side of the control and the
related control or container.
· android:layout_marginLeft - Defines the spacing between the left side of the control and the related
control or container.
Example
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Button2" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button3" />
<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 63 Components and Layouts
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button4" />
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btn2"
android:layout_centerHorizontal="true"
android:text="Button5" />
<Button
android:id="@+id/btn6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btn4"
android:layout_centerHorizontal="true"
android:text="Button6" />
<Button Output
android:id="@+id/btn7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/btn1"
android:layout_toRightOf="@+id/btn1"
android:layout_alignParentRight="true"
android:text="Button7" />
</RelativeLayout>
MainActivity.java
package com.vrs.relativelayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".RelativeLayoutAndroidExample" >
<TextView
android:id="@+id/text1"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 64 Components and Layouts
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:text="LOGIN"
android:layout_marginTop="14dp"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text1"
android:layout_marginTop="20dp"
android:text="Username :"
android:textAppearance="?android:attr/textAppearanceLarge" />
Output
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView1"
android:layout_toRightOf="@+id/textView1"
/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="20dp"
android:text="Password :"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:inputType="textPassword"
/>
<Button
android:id="@+id/btnSubmit"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 65 Components and Layouts
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_below="@+id/editText2"
android:layout_centerInParent="true"
android:text="Submit" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="SIGNUP"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Relative Layout :
· Every element of relative layout arranges itself to the other element or a parent element.
· It is helpful while adding views one next to other etc
· In a relative layout you can give each child a Layout Property that specifies exactly where it should
go in relative to the parent or relative to other children.
· Views can be layered on top of each other.
Linear Layout :
· In a linear layout, like the name suggests, all the elements are displayed in a linear fashion either
vertically or horizontally.
· Either Horizontally or Vertically this behavior is set in android:orientation which is an property of the
node Linear Layout.
android:orientation="horizontal" or android:orientation="vertical"
· Linear layouts put every child, one after the other, in a line, either horizontally or vertically.
qqq
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 66 Components and Layouts
Notes
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - IV
4
4.1 The Android View
Designing User Interface with View
android.widget.EditText android.widget.Button
· Edit Text : Edit Text is a user interface control · Text View is a user interface control which is used
which is used to allow the user to enter or modify to display the text to the user.
the text.
android.view.View
· Android Auto Complete Text View : In android,
Auto Complete Text View is an editable text view
which is used to show the list of suggestions based
on the user typing text. The list of suggestions will android.widget.TextView
be shown as a dropdown menu from which the
user can choose an item to replace the content of
Fig. 4.1.2 Text view
textbox.
4.1.1.2 Declare UI Elements in XML
· Button : Button is a user interface control which is
used to perform an action when the user click or When you create a new Android project, Android
tap on it. Studio always creates the act_ex.xml file which
contains a <TextView> element:
· Image Button : Image Button is a user interface
<?xml version="1.0" encoding="utf-8"?>
control which is used to display a button with
<LinearLayout xmlns:study="url"
image to perform an action when user click or tap
study:orientation="vertical"
on it. Generally, the Image button in android looks
study:layout_width="match_pr"
similar as regular Button and perform the actions
study:layout_height="match_pr">
same as regular button but only difference is for
<TextView
image button we will add an image instead of text.
study:id="@+id/fstTxt"
· Check Box : Checkbox is a two states button that study:layout_width="wrap_cnt"
can be either checked or unchecked. study:layout_height="wrap_cnt"
· Toggle Button : Toggle Button is a user interface study:text="Enter your account number" />
control which is used to display ON (Checked) or </LinearLayout>
OFF (Unchecked) states as a button with a light
4.1.2 Edit Text
indicator.
· A Edit Text is an overlay over Text View that
· Radio Button : Radio Button is a two states button
configures itself to be editable.
that can be either checked or unchecked and it
cannot be unchecked once it is checked. · It is the predefined subclass of Text View that
includes rich editing capabilities.
· Radio Group : Radio Group is used to group one or
more radio buttons into separate groups based on android.view.View
our requirements. In case if we group radio buttons
using radio group, at a time only one item can be
selected from the group of radio buttons.
android.widget.TextView
4.1.1.1 Text View
· In android, Text View is a user interface control
which is used to set and display the text to the user
android.widget.EditText
based on our requirements.
· The Text View control will act as like label control
and it won't allow users to edit the text. Fig. 4.1.3 Edit text view
· In android, we can create a Text View control in · In Android, Edit Text is a standard entry widget in
two ways either in XML layout file or create it in android apps.
Activity file programmatically. · It is an overlay over Text View that configures itself
to be editable.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-3 Designing User Interface with View
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-4 Designing User Interface with View
1. Id : id is an attribute used to uniquely identify a text Edit Text. Below is the example code in
which we set the id of a edit text.
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_height="wrap_cnt"
study:layout_width="match_pr"/>
2. 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.
For example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:text="Enter Name"
study:gravity="left"/>
3. Text : text attribute is used to set the text in a Edit Text. We can set the text in xml as well as in
the java class.
Setting the text in xml
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_centerInParent="true"
study:text="Subject"/>
Setting text in Edit Text In Java class :
example
Edit Text Edit Text = (Edit Text)findViewById(R.id.simpleEdit Text);
Edit Text.setText("Subject");
4. TextColor : textColor attribute is used to set the text color of a text edit text. Color value is in the
form of "#argb", "#rgb", "#rrggbb", or "#aarrggbb".
example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_centerInParent="true"
study:text="Name"
study:textColor="#00ff00"/>
Setting textColor in Edit Text In Java class:
Edit Text simpleEdit Text=(Edit Text)findViewById(R.id.simpleEdit Text);
simpleEdit Text.setTextColor(Color.GREEN);
5. TextColorHint : textColorHint is an attribute used to set the color of displayed hint.
example.
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-5 Designing User Interface with View
study:layout_centerInParent="true"
study:hint="Username"
study:textColorHint="#0f0"/>
Setting textColorHint in Edit Text In Java class :
example
Edit Text simpleEdit Text=(Edit Text)findViewById(R.id.simpleEdit Text);
simpleEdit Text.setHintTextColor(Color.green(0))
6. Hint : hint is an attribute used to set the hint i.e. what you want user to enter in this edit text.
Whenever user start to type in edit text the hint will automatically disappear.
example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_centerInParent="true"
study:hint="Email_id" />
Setting hint in Edit Text In Java class:
Edit Text Edit Text = (Edit Text)findViewById(R.id.simpleEdit Text);
Edit Text.setHint("Email_id");
7. Background : background attribute is used to set the background of a edit text. We can set a color
or a drawable in the background of a edit text.
example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:textColorHint="#fff"
study:textStyle="bold|italic"
study:layout_centerInParent="true"
study:hint="Enter Email_id "
study:padding="20dp"
study:background="#0f0"/>
Setting Background in Edit Text In Java class :
Below is the example code in which we set the background color of a edit text programmatically
means in java class.
Edit Text simpleEdit Text=(Edit Text)findViewById(R.id.simpleEdit Text);
simpleEdit Text.setBackgroundColor(Color.GREEN);
8. Padding : padding attribute is used to set the padding from left, right, top or bottom.
9. TextSize : textSize attribute is used to set the size of text of a edit text. We can set the text size in
sp(scale independent pixel) or dp(density pixel).
example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_centerInParent="true"
study:text="Password"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-6 Designing User Interface with View
study:textSize="35sp" />
Setting textSize in Edit Text in Java class :
example
Edit Text simpleEdit Text=(Edit Text)findViewById(R.id.simpleEdit Text);
simpleEdit Text.setTextSize(35);//
10. TextStyle : textStyle attribute is used to set the text style of a edit text. The possible text styles are
bold, italic and normal. If we need to use two or more styles for a edit text then "|" operator is
used for that.
example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_centerInParent="true"
study:text="Email"
study:textSize="25sp"
study:textStyle="bold|italic"/>
4.1.3 Button
· Button, as understood by its name, is a component which can be pressed or clicked by the user to
perform an action.
· It has the same properties as a Text View, with a few Button specific properties.
· Button, as understood by its name, is a component which can be pressed or clicked by the user to
perform an action.
· It has the same properties as a Text View, with a few Button specific properties.
· Button is a user interface control which is used to perform an action when the user click or tap on it.
· The main usage of the Button view is that whenever we click a button, we can set a method that will
handle that specific button request and will carry out the necessary action.
· This can be done inside the Activity class as following:
· Buttons are usually used to make your app do something when they're clicked.
· Android buttons are Android GUI components which are sensible to taps (clicks) by the user. When
the user taps an Android button in an Android app, the app can respond to the tap.
· Android buttons can be divided into two categories.
¡ Buttons with text on
¡ Buttons with an image on
¡ Buttons with images on can contain both an image and a text.
· Android buttons with images on are also called image buttons..
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-7 Designing User Interface with View
· Generally, the Image button in android looks similar as regular Button and perform the actions same
as regular button but only difference is for image button we will add an image instead of text.
· An image button is just like a button, except it contains an image and no text.
· In simple words we can say, Image Button is a button with an image that can be pressed or clicked
by the users.
· The Image Button component is a button with an image on. The Image Button is represented by the
Android class study.widget.ImageButton .
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-9 Designing User Interface with View
tb.setTextOff("OFF");
tb.setTextOn("ON");
tb.setChecked(true);
layout.addView(tb);
This shows ToggleButton in XML layout file or programmatically in activity file based on our
requirements.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 11 Designing User Interface with View
app:layout_constraintEnd_toStartOf="@+id/toggleButton2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ToggleButton
study:id="@+id/toggleButton2"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:layout_marginRight="60dp"
study:layout_marginTop="80dp"
study:text="ToggleButton"
study:textOff="Off"
study:textOn="On"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
study:id="@+id/button"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:layout_marginBottom="144dp"
study:layout_marginLeft="148dp"
study:text="Submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</study.support.constraint.ConstraintLayout>
Let's write the code to check which toggle button is ON/OFF.
package example.url.togglebutton;
import study.support.AppCompatActivity;
import study.os.Bundle;
import study.view.View;
import study.widget.Button;
import study.widget.Toast;
import study.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private ToggleButton toggleButton1, toggleButton2;
private Button buttonSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick(){
//Getting the ToggleButton and Button instance from the layout xml file
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);
toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
buttonSubmit=(Button)findViewById(R.id.button);
//Performing action on button click
buttonSubmit.setOnClickListener(new View.OnClickListener(){
@Override
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 13 Designing User Interface with View
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 14 Designing User Interface with View
Male Female
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 15 Designing User Interface with View
9. padding : padding attribute is used to set the 3. Enter your radio button items. ...
padding from left, right, top or bottom. 4. Click Add to add more item-value pairs to your
· paddingRight : Set the padding from the right list.
side of the radio button. 5. Click OK.
· paddingLeft : Set the padding from the left side of
Example for radio button :
the radio button.
In this example, we are going to implement single
· paddingTop : Set the padding from the top side of
radio button separately as well as radio button in
the radio button. RadioGroup.
· paddingBottom : Set the padding from the bottom ?xml version="1.0" encoding="utf-8"?>
side of the radio button. <LinearLayout
· Padding : Set the padding from the all side's of xmlns:study="url"
xmlns:tools="url"
the radio button.
study:layout_width="match_pr"
10. drawableBottom, drawableTop, drawableLeft
study:layout_height="match_pr"
And drawableRight : These attribute draw the
study:orientation="vertical"
drawable to the below of the text of RadioButton.
tools:context="url">
For Example : <TextView
study:id="@+id/textView1"
Radio Buttons study:layout_width="fill_pr"
Select your subject? study:layout_height="wrap_cnt"
DBMS study:layout_marginTop="30dp"
C/C++ Programming Radio Buttons in study:gravity="center_horizontal"
Radio Group
Data structures study:textSize="22dp"
Algorithms
study:text="Single Radio Buttons" />
CLEAR SUBMIT <!-- Default RadioButtons -->
<RadioButton
Fig. 4.1.9 Radio button in radio group study:id="@+id/radioButton1"
study:layout_width="fill_pr"
This image shows 4 options of subjects for a question. study:layout_height="wrap_cnt"
In this, each mentioned subject is a Radio Button and study:layout_gravity="center_horizontal"
all the 4 subjects are together enclosed in a Radio study:text="Radio Button 1"
Group. study:layout_marginTop="20dp"
study:textSize="20dp" />
4.1.7 Radio Group <RadioButton
· Radio Group is used to group one or more radio study:id="@+id/radioButton2"
buttons into separate groups based on our study:layout_width="fill_pr"
requirements. study:layout_height="wrap_cnt"
study:text="Radio Button 2"
· In case if we group radio buttons using radio
study:layout_marginTop="10dp"
group, at a time only one item can be selected from
study:textSize="20dp" />
the group of radio buttons
<View
Here's how to use it : study:layout_width="fill_pr"
1. Go to Insert > Form Items > Radio Button Group. study:layout_height="1dp"
This opens the Insert Radio Button Group study:layout_marginTop="20dp"
window. study:background="#B8B894" />
<TextView
2. Enter a name for the group. This will appear in
study:id="@+id/textView2"
your form results. ...
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 16 Designing User Interface with View
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_marginTop="30dp"
study:gravity="center_horizontal"
study:textSize="22dp"
study:text="Radio button inside RadioGroup" />
<!-- Customized RadioButtons -->
<RadioGroup
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:id="@+id/radioGroup">
<RadioButton
study:id="@+id/radioMale"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:text=" Male"
study:layout_marginTop="10dp"
study:checked="false"
study:textSize="20dp" />
<RadioButton
study:id="@+id/radioFemale"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:text=" Female"
study:layout_marginTop="20dp"
study:checked="false"
study:textSize="20dp" />
</RadioGroup>
<Button
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:text="Show Selected"
study:id="@+id/button"
study:onClick="onclickbuttonMethod"
study:layout_gravity="center_horizontal" />
</LinearLayout>
package radbut;
import study.support.AppCompatActivity;
import study.os.Bundle;
import study.view.View;
import study.widget.Button;
import study.widget.RadioButton;
import study.widget.RadioGroup;
import study.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button;
RadioButton genderradioButton;
RadioGroup radioGroup;
@Override
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 17 Designing User Interface with View
Output
app:layout_constraintTop_toBottomOf="@+id
Tea Here we have two checkboxes. /checkBox" />
Users can choose tea, coffee
both tea and coffee or neither.
<CheckBox
Coffee study:id="@+id/checkBox3"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
Fig. 4.1.11 Check box
study:layout_marginLeft="144dp"
study:layout_marginTop="28dp"
4.1.8.1 Check Box Attributes study:text="Burger"
1) study:autoText : If set, specifies that this app:layout_constraintStart_toStartOf="parent"
TextView has a textual input method and
automatically corrects some common spelling app:layout_constraintTop_toBottomOf="@+id
errors. /checkBox2" />
<Button
2) study:drawableBottom : This is the drawable to
study:id="@+id/button"
be drawn below the text.
study:layout_width="wrap_cnt"
3) study:drawableRight : This is the drawable to be study:layout_height="wrap_cnt"
drawn to the right of the text. study:layout_marginLeft="144dp"
4) study:editable : If set, specifies that this study:layout_marginTop="184dp"
TextView has an input method. study:text="Order"
app:layout_constraintStart_toStartOf="parent"
5) study:text : This is the Text to display.
Android check box example : app:layout_constraintTop_toBottomOf="@+id
<?xml version="1.0" encoding="utf-8"?> /checkBox3" />
<study.support.constraint.ConstraintLayout </study.support.constraint.ConstraintLayout>
xmlns:study="url"
xmlns:app="ex.//url/apk/res-auto" Let's write the code to check which toggle button is
xmlns:tools="url" ON/OFF.
study:layout_width="match_pr" package example.url.checkbox;
study:layout_height="match_pr" import study.support.AppCompatActivity;
tools:context="url"> import study.os.Bundle;
<CheckBox import study.view.View;
study:id="@+id/checkBox" import study.widget.Button;
study:layout_width="wrap_cnt" import study.widget.CheckBox;
study:layout_height="wrap_cnt" import study.widget.Toast;
study:layout_marginLeft="144dp"
study:layout_marginTop="68dp" public class MainActivity extends AppCompatActivity {
study:text="Pizza" CheckBox pizza,coffe,burger;
app:layout_constraintStart_toStartOf="parent" Button buttonOrder;
app:layout_constraintTop_toTopOf="parent" /> @Override
<CheckBox protected void onCreate(Bundle savedInstanceState) {
study:id="@+id/checkBox2" super.onCreate(savedInstanceState);
study:layout_width="wrap_cnt" setContentView(R.layout.act_main);
study:layout_height="wrap_cnt" addListenerOnButtonClick();
study:layout_marginLeft="144dp" }
study:layout_marginTop="28dp" public void addListenerOnButtonClick(){
study:text="Coffee" //Getting instance of CheckBoxes and Button from the
app:layout_constraintStart_toStartOf="parent" activty_ex.xml file
pizza=(CheckBox)findViewById(R.id.checkBox);
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 19 Designing User Interface with View
Click to Load
Click to Load
study:layout_width="wrap_cnt" 4. Widget.ProgressBar.Inverse
study:layout_height="wrap_cnt" />
5. Widget.ProgressBar.Large.Inverse
and then manage the visibility in the activity :
6. Widget.ProgressBar.Small.Inverse
// on some click or some loading we need to wait for...
ProgressBar pb = (ProgressBar) To apply style, you can use below xml settings.
findViewById(R.id.pbLoading); <ProgressBar
pb.setVisibility(ProgressBar.VISIBLE); study:id="@+id/progressBar3"
// run a background job and once complete style="@study:style/Widget.ProgressBar.Large.Inverse"
pb.setVisibility(ProgressBar.INVISIBLE); You can also use android system attr to set progress
Typically you want to try to put the ProgressBar in bar style.
the place where data is going to show (i.e. as a
1. progressBarStyle
placeholder for an image). For a ListView, you put
the ProgressBar in the header or footer, which lets 2. progressBarStyleHorizontal
you put an arbitrary layout outside of the adapter. 3. progressBarStyleLarge
4. progressBarStyleSmall
4.1.9.2 Result-based
ProgressBar can be used to report the progress of a 5. progressBarStyleInverse
long-running AsyncTask. In this case : 6. progressBarStyleLargeInverse
· ProgressBar can report numerical results for a 7. progressBarStyleSmallInverse
task. 8. progressBarStyleSmallTitle
· Must specify horizontal style and result max <ProgressBar
value. study:id="@+id/progressBar2"
style="?study:attr/progressBarStyleHorizontal"
· Must publishProgress(value) in your AsyncTask
3. Common Horizontal Progress Bar Example
<ProgressBar
stydy/result/lout/prog.xml
study:id="@+id/progressBar1"
<!-- Settings for common horizontal progress bar.-->
study:layout_width="wrap_cnt"
<TextView
study:layout_height="wrap_cnt"
study:id="@+id/textView13"
study:visibility="invisible"
study:layout_width="match_pr"
style="?study:attr/progressBarStyleHorizontal"
study:layout_height="wrap_cnt"
study:max="100" />
study:text="Common Horizontal Progress Bar"
1. Android ProgressBar Properties study:textSize="20dp"/>
1. progress : An int value to indicate the progress
bar current progress. <ProgressBar
study:id="@+id/progressBar1"
2. secondaryProgress : An int value to indicate the
style="@study:style/Widget.ProgressBar.Horizontal"
progress bar current secondary progress.
study:max="100"
3. indeterminate : A boolean value. true show a study:layout_width="match_pr"
circle bar. false show a horizontal bar. But study:layout_height="wrap_cnt" />
commonly the bar is decided by it's style value. 4. Customize Horizontal Progress Bar Example
2. Progress Bar Style stydy/result/lout/prog.xml
There are several styles that you can apply to a <!-- Settings for custom horizontal progress bar
progress bar. background, progress and secondProgress.-->
<TextView
1. Widget.ProgressBar.Horizontal study:id="@+id/textView14"
2. Widget.ProgressBar.Large study:layout_width="match_pr"
study:layout_height="wrap_cnt"
3. Widget.ProgressBar.Small
study:text="Custom Horizontal Progress Bar"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 21 Designing User Interface with View
study:textSize="20dp"
study:layout_marginTop="20dp"/>
<ProgressBar
study:id="@+id/progressBar2"
style="?study:attr/progressBarStyleHorizontal" Fig. 4.2.1 List view
study:max="100"
study:minHeight="100dp" · List View uses Adapter classes which add the
study:padding="6dp"
content from data source (such as string array,
study:progressDrawable="@drawable/
array, database etc) to ListView.
/my_progress_bar"
· Adapter bridges data between an Adapter Views
study:layout_width="match_pr"
study:layout_height="wrap_cnt" /> and other Views (List View, Scroll View etc).
· In android Grid View is a view group that display
4.2 List View items in two dimensional scrolling grid (rows and
columns), the grid items are not necessarily
· Android List View is a view which contains the predetermined but they are automatically inserted
group of items and displays in a scrollable list. to the layout using a List Adapter.
· List View is implemented by importing android. · A very common example of ListView is your phone
widget. List View class. contact book, where you have a list of your contacts
· List View uses Adapter classes which add the displayed in a ListView and if you click on it then
content from data source (such as string array, user information is displayed.
array, database etc) to List View.
Adapter :
· Android List View is a view which contains the
group of items and displays in a scrollable list. To fill the data in a ListView we simply use adapters.
List items are automatically inserted to a list using an
· In android, List View is a View Group which is
Adapter that pulls the content from a source such as
used to display the list of scrollable of items in
an arraylist, array or database.
multiple rows and the list items are automatically
inserted to the list using an adapter.
List View in Android Studio
· Generally, the adapter pulls data from a sources
List view is present inside Containers. From there
such as an array or database and converts each item
you can drag and drop on virtual mobile screen to
into a result view and that's placed into the list.
create it. Alternatively you can also XML code to
· The pictorial representation of list view in android create it.
applications is shown in Fig. 4.2.1.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 23 Designing User Interface with View
study:dividerHeight="1dp"
study:listSelector="#0f0"/> <!--list selector in green color-->
Example of ListView
<?xml version="1.0" encoding="utf-8"?>
<study.support.constraint.ConstraintLayout xmlns:study="url"
xmlns:app="ex.//url/apk/res-auto"
xmlns:tools="url"
study:layout_width="match_pr"
study:layout_height="match_pr"
tools:context="listview.url.listview.MainActivity">
<ListView
study:id="@+id/listView"
study:layout_width="match_pr"
study:layout_height="fill_pr"
/>
</study.support.constraint.ConstraintLayout>
Create an additional mylist.xml file in layout folder which contains view components displayed in
listview.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:study="url"
study:id="@+id/textView"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:text="Medium Text"
study:textStyle="bold"
study:textAppearance="?study:attr/textAppearanceMedium"
study:layout_marginLeft="10dp"
study:layout_marginTop="5dp"
study:padding="2dp"
study:textColor="#4d4d4d"
/>
Now place the list of data in strings.xml file by creating string-array.
<resources>
<string name="app_name">ListView</string>
<string-array name="array_technology">
<item>C++</item>
<item>Android</item>
<item>Java</item>
<item>Python</item>
</string-array>
</resources>
Activity class
In java class we need to add adapter to listview using setAdapter() method of listview.
package listview.url.listview;
import study.support.AppCompatActivity;
import study.os.Bundle;
import study.view.View;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 24 Designing User Interface with View
import study.widget.AdapterView;
import study.widget.ArrayAdapter;
import study.widget.ListView;
import study.widget.TextView;
import study.widget.Toast;
Output
· Users can then select any grid item by clicking on 2) study:columnWidth : This specifies the fixed
it. width for each column. This could be in px, dp,
sp, in, or mm
· Grid View is default scrollable so we don't need to
use Scroll View or anything else with Grid View. 3) study:gravity : Specifies the gravity within each
cell. Possible values are top, bottom, left, right,
· Grid View is widely used in android applications.
center, center_vertical, center_horizontal etc.
· An example of Grid View is very common in
4) study:horizontalSpacing : Defines the default
applications like calculator, calendar ,your default horizontal spacing between columns. This could
Gallery, where you have number of images be in px, dp, sp, in, or mm
displayed using grid, and many others.
5) study:numColumns : Defines how many columns
· In Grid View, grid items are automatically inserted to show. May be an integer value, such as "100"
to the grid view layout using a list adapter. or auto_fit which means display as many
· Generally, the adapter pulls data from a sources columns as possible to fill the available space
such as an array or database and converts each item 6) study:stretchMode : Defines how columns should
into a result view and that's placed into the list. stretch to fill the available empty space, if any.
This must be either of the values :
4.2.1.1 Methods of Grid View a. none : Stretching is disabled
Grid view has many methods to use, some of them
b. spacingWidth : The spacing between each
are explained here
column is stretched
· getAccessibilityClassName(): return the class name
of object. c. columnWidth : Each column is stretched
Once we are done with creation of layout, we need to create a custom adapter (ImageAdapter.java) by
extending it using BaseExtender to show all the items in the grid.
Open ImageAdapter.java file and write the code like as shown below
package com.study.gridview;
import study.content.Context;
import study.view.View;
import study.view.ViewGroup;
import study.widget.BaseAdapter;
import study.widget.GridView;
import study.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return thumbImages.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
imageView.setImageResource(thumbImages[position]);
return imageView;
}
// Add all our images to arraylist
public Integer[] thumbImages = {
S.drwa.Im1, S.drwa.Im2,
S.drwa.Im3, S.drwa.Im4,
S.drwa.Im5, S.drwa.Im6,
S.drwa.Im7, S.drwa.Im8,
};
}
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 27 Designing User Interface with View
1. id : id is an attribute used to uniquely identify a Below is the example code in which we set the black
image view in android. Below is the example color in the background and an image in the src
code in which we set the id of a image view. attribute of image view.
<ImageView <ImageView
study:id="@+id/sImVw" study:id="@+id/sImVw"
study:layout_width="fill_pr" study:layout_width="fill_pr"
study:layout_height="wrap_cnt" study:layout_height="wrap_cnt"
/> study:src="@drawable/lion"
2. src : src is an attribute used to set a source file study:background="#000"/><!--black color in
or you can say image in your imageview to background of a image view-->
make your layout attractive.
In Java
Below is the example code in which we set the
We can also set the background at run time
source of a imageview lion which is saved in
programmatically in java class. In below example
drawable folder.
code we set the black color in the background of a
<ImageView
image view.
study:id="@+id/sImVw"
/*Add in Oncreate() funtion after setContentView()*/
study:layout_width="fill_pr"
ImageView sImVw=(ImageView)
study:layout_height="wrap_cnt"
findViewById(R.id.sImVw);
study:src="@drawable/lion" /><!--set the source of an
sImVw.setBackgroundColor(Color.BLACK);//set black color
image view-->
in background of a image view in java class
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 28 Designing User Interface with View
4. padding : padding attribute is used to set the · In android, Scroll View is a kind of layout which is
padding from left, right, top or bottom of the useful to add a vertical or horizontal scroll bars to
Imageview. the content which is larger than actual size of
· paddingRight : Set the padding from the right side layouts such as linear layout, relative layout, frame
of the image view. layout, etc.
· paddingLeft : Set the padding from the left side of · Generally, the android Scroll View is useful when
the image view. we have a content that doesn't fit to our android
· paddingTop : Set the padding from the top side of app layout screen.
the image view. · The Scroll View will enable a scroll to the content
· paddingBottom : Set the padding from the bottom which is exceeding the screen layout and allow
side of the image view. users to see the complete content by scrolling.
· padding : Set the padding from the all side's of the · In android, Scroll View supports only vertical
image view. scrolling.
Below is the example code of padding attribute in 4.2.3.1 Vertically Scrolling
which we set the 30dp padding from all the side's of
To make any content vertically scrollable, simply
a image view.
wrap that content in a ScrollView :
<ImageView
<ScrollView
study:id="@+id/sImVw"
study:layout_width="match_pr"
study:layout_width="fill_pr"
study:layout_height="match_pr">
study:layout_height="wrap_cnt"
<LinearLayout
study:background="#000"
study:layout_width="match_pr"
study:src="@drawable/lion"
study:layout_height="wrap_cnt"
study:padding="30dp"/><!--set 30dp padding from all
study:orientation="vertical" >
the sides-->
<TextView
5. scaleType : scaleType is an attribute used to
study:id="@+id/tv_long"
control how the image should be re-sized or
study:layout_width="wrap_cnt"
moved to match the size of this image view. The
study:layout_height="match_pr"
value for scale type attribute can be fit_xy,
study:text="@string/really_long_string" >
center_crop, fitStart etc. </TextView>
Below is the example code of scale type in which we <Button
set the scale type of image view to fit_xy. study:id="@+id/btn_act"
<ImageView study:layout_width="wrap_cnt"
study:id="@+id/sImVw" study:layout_height="wrap_cnt"
study:layout_width="fill_pr" study:text="View" >
study:layout_height="wrap_cnt" </Button>
study:src="@drawable/lion" </LinearLayout>
study:scaleType="fitXY"/><!--set scale type fit xy--> </ScrollView>
· Scrolling activity is an important thing to have in In other cases, we want content to horizontally scroll
your app as it gives your user a perfect view when in which case we need to use the Horizontal Scroll
the layout is long. View instead like this :
<HorizontalScrollView
· The Scrolling activity can be implemented easily in
study:layout_width="match_pr"
android studio project because android studio gives
study:layout_height="match_pr">
a ready to use activity.
<LinearLayout
study:layout_width="match_pr"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 29 Designing User Interface with View
study:layout_height="wrap_cnt"
study:orientation="horizontal" > BUTTON ONE BUTTON TWO BUTTON THREE BUTTON
<!-- child views in here -->
</LinearLayout>
</HorizontalScrollView> Fig. 4.2.5 Android horizontal scroll view example
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 30 Designing User Interface with View
4.2.4.1 Creating a Toast It created a one Button control in XML Layout file to
Here is an Android Toast example : show the custom toast notification when we click on
Button.
Toast toast = Toast.makeText(getApplicationContext(),
<?xml version="1.0" encoding="utf-8"?>
"This is a message displayed in a Toast",
<LinearLayout xmlns:study="url"
Toast.LENGTH_SHORT); toast.show();
study:id="@+id/custom_toast_layout"
The Toast.makeText() method is a factory method study:orientation="horizontal"
which creates a Toast object. study:layout_width="match_pr"
study.widget.Toast class used to create toast alert study:layout_height="match_pr"
message. study:paddingLeft="10dp"
study:paddingRight="10dp"
Toast alert is a notification message that display for
study:background="#80CC28">
certain amount of time, and automtaically fades out
<ImageView study:src="@drawable/ic_notification"
after set time.
study:layout_width="wrap_cnt"
Use it to show alert message to user.
study:layout_height="wrap_cnt"
Use it for debugging your application. study:layout_marginRight="10dp" />
<TextView study:id="@+id/txtvw"
Use toast alert message to show alert from
study:layout_width="wrap_cnt"
background sevice,boadcast reciever,getting data from
study:layout_height="wrap_cnt"
server...etc.
study:layout_marginTop="13dp"
Normal Toast Alert : study:textColor="#FFF"
//Show alert for short period of time study:textStyle="bold"
Toast.makeText(getApplicationContext(), "This is study:textSize="15dp" />
Toast example.", Toast.LENGTH_SHORT).show(); </LinearLayout>
It loading image (ic_notification) from drawable
//Show alert for long period of time
folder so you need to add your icon in drawable
Toast.makeText(getApplicationContext(), "This is
folder to show it in notification.
Toast example.", Toast.LENGTH_LONG).show();
package com.study.cTEx;
Android Custom Toast Example import study.support.AppCompatActivity;
Create a new android application using android import study.os.Bundle;
studio and give names as ToastExample. In case if import study.view.Gravity;
import study.view.LayoutInflater;
you are not aware of creating an app in android
import study.view.View;
studio check this article Android Hello World App.
import study.view.ViewGroup;
Now open an act_ex.xml file from \res\layout path import study.widget.Button;
and write the code like as shown below. import study.widget.TextView;
<?xml version="1.0" encoding="utf-8"?> import study.widget.Toast;
<LinearLayout xmlns:study="url"
study:layout_width="match_pr" public class MainActivity extends AppCompatActivity {
study:layout_height="match_pr" @Override
study:orientation="vertical" > protected void onCreate(Bundle savedInstanceState) {
<Button super.onCreate(savedInstanceState);
study:id="@+id/btnShow" setContentView(R.layout.act_main);
study:layout_width="wrap_cnt" Button btn = (Button)findViewById(R.id.btnShow);
study:layout_height="wrap_cnt" btn.setOnClickListener(new View.OnClickListener() {
study:text="Show Custom Toast" @Override
study:layout_marginTop="150dp" public void onClick(View v) {
study:layout_marginLeft="110dp"/> LayoutInflater inflater = getLayoutInflater();
</LinearLayout>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 31 Designing User Interface with View
When we run above example using Android Virtual Device (AVD) we will get a result like as shown
below.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 32 Designing User Interface with View
3. calendarViewShown : This is a boolean value, only take effect when datePickerMode is spinner. If
set to true, it will display a claendar.
4. spinnersShown : This is a boolean value also, only take effect when datePickerMode is spinner.
If set to true, it will display a spinner.
5. If both above two properties set to true of false, it will show both a spinner besides a calendar.
6. minDate : Set the optional minimum date in mm/dd/yyy format.
7. maxDate : Set the maximum date to select, format is mm/dd/yyyy.
8. startYear : Set optional start year.
9. endYear : Set optional end year.
3.35
Drawable resource id which can be set to 2 29
AM
TimePicker's header background. PM 3 30 AM
3. is24HourView() : Check whether it is 24 hour
4 31 PM
time system.
4. setIs24HourView(boolean 24HourView) : Set if Fig. 4.3.2 Time picker spinner mode
use 24 hour time system.
5. getHour() : Get current hour integer value.
6. getMinute() : Get current minute integer value.
7. setOnTimeChangedListener() : Set call back listener when time is changed
Android time picker example
1. TimePicker
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:study="url"
study:layout_width="fill_pr"
study:layout_height="fill_pr"
study:orientation="vertical" >
<Button
study:id="@+id/btnChangeTime"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:text="Change Time" />
<TextView
study:id="@+id/lblTime"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:text="Current Time (H:M): "
study:textAppearance="?study:attr/textAppearanceLarge" />
<TextView
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 33 Designing User Interface with View
study:id="@+id/tvTime"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:text=""
study:textAppearance="?study:attr/textAppearanceLarge" />
<TimePicker
study:id="@+id/timePicker1"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt" />
</LinearLayout>
2. Code
Read the code's comment, it should be self-explanatory.
package stud.ex;
import java.util.Calendar;
import and.app.Activity;
import and.app.Dialog;
import and.app.TimePickerDialog;
import study.os.Bundle;
import study.view.View;
import study.view.View.OnClickListener;
import study.widget.Button;
import study.widget.TextView;
import study.widget.TimePicker;
qqq
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - V
5
5.1 Intent
Activity and
Multimedia with Database
· An intent is to perform an action on the screen. It is
mostly used to start activity, send broadcast
· An Android Intent is an abstract description of an
receiver, start services and send message between
operation to be performed.
two activities.
· It can be used with start Activity to launch an
· There are two intents available in android as
Activity, broadcast Intent to send it to any
Implicit Intents and Explicit Intents. Here is a
interested Broadcast Receiver components, and start
sample example to start new activity with old
Service (Intent) or bind Service (Intent, Service
activity.
Connection, int) to communicate with a background
Service. · Intents are used generally for starting a new activity
using startActivity().
· The intent itself, an Intent object, is a passive data
structure holding an abstract description of an 5.1.1 Use of Intent
operation to be performed.
1. For Launching an Activity
· Android Intent generally consists of two different
portions of information. They have primary and 2. To start a New Service
secondary attributes. Attributes are as follow : 3. For Broadcasting Messages
· A Uniform Resource Identifier (Uri) is nothing but 4. To Display a list of contacts in ListView
an identifier which identifies an abstract or physical
resource. 5.1.2 Types of Intent in Android
1. Implicit Intent
INTENT
The implicit intent is the intent where instead of
defining the exact components, you define the action
PRIMARY ATTRIBUTES that you want to perform for different activities.
DATA ACTION
An Implicit intent specifies an action that can invoke
any app on the device to be able to perform an
SECONDARY ATTRIBUTES action. Using an Implicit Intent is useful when your
CATEGORY TYPE app cannot perform the action but other apps
probably can and you'd like the user to pick which
COMPONENT EXTRAS app to use.
Syntax :
Fig 5.1.1 Structure of Intent Intent i=new Intent();
i.setAction(Intent.ACTION_SEND);
· There are some other standard actions that intents can use to launch a specific app component, such as
can use for launching activities. a particular activity or service in your app.
1 Device
Intent fired to
launch activity B
Activity 1 ANDROID
SYSTEM Activity B
Intent 2
Manifest : Comparing
intent filter contents of Launching activity B
intent and
intent filter at
3
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5-3 Activity and Multimedia with Databases
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5-4 Activity and Multimedia with Databases
· It may instruct the system about the nature of This is the first callback method and it fires when the
treatment to be given to an activity which is system creates an activity for the first time. During
launched by this intent. the activity creation, activity entered into a Created
state.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5-5 Activity and Multimedia with Databases
Activity
launched
onCreate()
onStart() onRestart()
onResume()
User navigates
to the activity
Activity
App process running
killed
onStop()
onDestroy()
Activity
shut down
The onRestart() method will restore the state of The app will stays in this Resumed state until an
activity from the time that is being stopped. another activity happens to take focus away from the
app like getting a phone call or screen turned off, etc.
The onRestart() callback method in android activity
will always followed by onStart() method. In case if any interruption events happen in Resumed
state, the activity will entered into Paused state and
3. onStart() : the system will invoke onPause() method.
App becomes visible after this method is called. After an activity returned from Paused state to
It is followed by onResume when activity is in the Resumed state, the system again will call onResume()
foreground method due this we need to implement onResume()
method to initialize the components that we release
It is followed by onStop() when activity is hidden.
during onPause() method
At this state, system cannot kill the activity.
Following is the example of defining a onResume()
The onStart() callback method will invoke when an method in android activity.
activity entered into Started State by completing @Override
onCreate() method. The onStart() method will make public void onResume() {
an activity visible to the user and this method super.onResume();
execution will finish very quickly. if (mCamera == null) {
initializeCamera();
Following is the example of defining a onStart()
}
method in android activity.
}
@Override If any interruption happen in Resumed state, the
protected void onStart()
activity will entered into Paused state and the system
{
will invoke onPause() method.
super.onStart()
}
5. onPause() :
After completion of onStart() method execution, the
If activity wants to resume then this method is called.
activity enters into Resumed state and system invoke
This saves all the unsaved changes. Anything which
the onResume() method.
is consuming CPU is stopped. The next stage is not
4. onResume() : started until control returns from paused state. Hence
this stage has a very short life span.
When activity starts interacting onResume() is called.
User interacts with activity and gives the input. It is If activity has to come to foreground then it is to be
at the top of back stack now. followed by onResume().
@Override 7. onDestroy() :
public void onPause() { When activity has to be destroyed, then this method
super.onPause(); is called. It is the final call. It is either called when
if (mCamera != null) { activity is about to finish or it is going to be replaced
mCamera.release(); to save space.
mCamera = null;
} It is not followed by any call as it is final.
} The system kills this activity.
After completion of onPause() method execution, the
next method is either onStop() or onResume() The system will invoke onDestroy() method before an
depending on what happens after an activity entered activity is destroyed and this is the final callback
into Paused state. method which received by the android activity.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5-8 Activity and Multimedia with Databases
1 ACTION_BOOT_COMPLETED When device completes its start up sequence then this broadcast is
fired. This broadcast is received only when the application has the
RECEIVE_BOOT_COMPLETED permission.
3 ACTION_DATE_CHANGED, When date and/ or time are changed manually then these
ACTION_TIME_CHANGED broadcasts are fired respectively.
5 ACTION_MEDIA_MOUNTED, When any external storage media is added and / or removed, these
ACTION_MEDIA_UNMOUNTED broadcasts are fired.
7 ACTION_SCREEN_ON, When screen turns on and/or turns off, this broadcast is fired.
ACTION_SCREEN_OFF
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 10 Activity and Multimedia with Databases
Common Methods
Let us study some of the common methods and they are as follows :
1.abortBroadcast() :
· This method doesn't works with asynchronous broadcasts.
· It sets the flag which indicates that the present receiver should abort this broadcast.
· Other broadcast receivers will be prevented from receiving this broadcast.
· Syntax: public final void abortBroadcast();
2.clearAbortBroadcast() :
· The flag set by abortBroadcast() method is cleared by this function call.
· Syntax: public final void clearAbortBroadcast();
3.getAbortBroadcast() :
· This method returns the flag which signals broadcast receiver to abort the current broadcast or not.
· Syntax: public final Boolean getAbortBroadcast();
4. getDebugUnregister() :
· This returns the previous value given to setDebugUnregister(boolean)
· Syntax: public final Boolean getDebugUnregister();
5.getResultCode() :
· Previous receiver sets a result code.
· This current result code is retrieved by this method.
· Result data is integer
· Syntax: public final intgetResultCode();
6.getResultData() :
· Previous receiver sets a result data.
· It may be null.
· Current result data I retrieved by this method.
· Result data is of type string
· Syntax: public final String getResultData();
7.isInitialStickyBroadcast() :
· If receiver is processing the initial value of a sticky broadcast then this method returns true.
· This has nothing to do with current broadcast.
· It is the value of last broadcast and is held in sticky cache.
· Syntax: public final Boolean isInitialStickyBroadcast();
8.isOrderedBroadcast() :
· When receiver processes a broadcast from ordered broadcast, this method returns true.
· Syntax: public final Boolean isOrderedBroadcast();
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 11 Activity and Multimedia with Databases
9.onReceive(Context,Intent) :
· When broadcast receiver receives some kind of broadcast intent then this method is called.
· Current results can be viewed or modified using other methods when this method was in use.
· By default, this method is associated with the main thread of application.
· If <receiver/> tag is used then as soon as function returns the object is killed.
· Context is in which the receiver is running
· Intent which is intended to be received.
· Syntax: public abstract void onReceive(Context context, Intent intent);
10.setOrderedHint(boolean) :
· This hints whether broadcast receiver is running on ordered mode or not.
· Syntax: public final void setOrederedHint(Boolean isOrdered);
Now the corresponding graphical layout should be similar to the following snapshot:
It's the time for our MainActivity.java file. Open it and type the code as shown below :
package ex.Broadcast;
import android.app.Activity;
import study.content.Intent;
import study.os.Bundle;
import study.view.View;
import study.view.View.OnClickListener;
import study.widget.Button;
import study.widget.EditText;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 13 Activity and Multimedia with Databases
package ex.Broadcast;
import study.content.BroadcastReceiver;
import study.content.Context;
import study.content.Intent;
import study.widget.Toast;
public class BroadcastClass extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
CharSequence inData = arg1.getCharSequenceExtra("broadcast");
Toast.makeText(arg0, "Hello Readers!! Enjoying broadcasts :)" + inData,
Toast.LENGTH_SHORT).show();
}
}
Code for Android Receiver
The last work you have to do is open your manifest file and add the code as shown below :
?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="url"
package="ex.Broadcast"
study:versionCode="1"
study:versionName="1.0" >
<uses-sdk
study:minSdkVersion="8"
study:targetSdkVersion="18" />
<uses-permission study:name="android.permission.READ_PHONE_STATE" />
<application
study:allowBackup="true"
study:icon="@drawable/ic_launcher"
study:label="@string/app_name"
study:theme="@style/AppTheme" >
<activity
study:name="ex.Broadcast.MainActivity"
study:label="@string/app_name" >
<intent-filter>
<action study:name="android.intent.action.MAIN" />
<category study:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver study:name="BroadcastClass" >
<intent-filter>
<action study:name="ex.Broadcast.CUSTOM_INTENT" />
</intent-filter>
</receiver>
</application>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 14 Activity and Multimedia with Databases
Save everything and run your emulator. Now run your application. The output should be similar to
the snapshot listed below :
Now enter the message you want to broadcast and press the button and see the magic what you
wanted to broadcast is actually broadcasted.
AbstractThreadedSyncAdapter CursorLoader
Widgets
Search
· Content providers can help an application manage access to data stored by itself, stored by other
apps, and provide a way to share data with other apps.
· They encapsulate the data, and provide mechanisms for defining data security.
· Content providers are the standard interface that connects data in one process with code running in
another process.
· Implementing a content provider has many advantages. Most importantly you can configure a content
provider to allow other applications to securely access and modify your app data as illustrated in
Fig. 5.3.2.
Your application
Your content
provider Other applications
implementation
Your data
storage
Fig. 5.3.2 Overview diagram of how content providers manage access to storage
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 16 Activity and Multimedia with Databases
5.3.1 Creating a Content Provider 3) update() - This method will update an existing
To create a content provider in android applications rows in our content provider and it return the
we should follow below steps. number of rows updated.
· We need to create a content provider class that 4) delete() - This method will delete the rows in our
content provider and it return the number of
extends the Content Provider base class.
rows deleted.
· We need to define our content provider URI to
5) getType() - This method will return the MIME
access the content.
type of data to given content URI.
· The Content Provider class defines a six abstract 6) onCreate() - This method will initialize our
methods (insert(), update(), delete(), query(), provider. The android system will call this
getType()) which we need to implement all these method immediately after it creates our provider.
methods as a part of our subclass. Android Content Provider Example
· We need to register our content provider in · Following is the example of using Content Provider
AndroidManifest.xml using <provider> tag. in android applications. Here we will create our
Following are the list of methods which need to own content provider to insert and access data in
implement as a part of Content Provider class. android application.
· Create a new android application using android
studio and give names as ContentProvider. In case
if you are not aware of creating an app in android
Content provider
studio check this article Android Hello World App.
· Now we need to create our own content provider
query()
file UsPr.java in
\src\main\study\ex.contentprovider path to define
insert()
our actual provider and associated methods for that
update() right click on your application folder ? Go to New ?
select Java Class and give name as UsPr.java.
delete() · Once we create a new file UsPr.java, open it and
write the code like as shown below
getType()
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 17 Activity and Multimedia with Databases
switch (uriMatcher.match(uri)) {
case uriCode:
qb.setProjectionMap(values);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == "") {
sortOrder = id;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 18 Activity and Multimedia with Databases
}
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long rowID = db.insert(TABLE_NAME, "", values);
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLiteException("Failed to add a record into " + uri);
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.update(TABLE_NAME, values, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.delete(TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
private SQLiteDatabase db;
static final String DATABASE_NAME = "EmpDB";
static final String TABLE_NAME = "Employees";
static final int DATABASE_VERSION = 1;
static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, "
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 19 Activity and Multimedia with Databases
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="url"
study:orientation="vertical" study:layout_width="match_parent"
study:layout_height="match_parent">
<TextView
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:text="Name"
study:layout_marginLeft="100dp"
study:layout_marginTop="100dp"/>
<EditText
study:id="@+id/txtName"
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:layout_marginLeft="100dp"
study:ems="10"/>
<Button
study:id="@+id/btnAdd"
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:onClick="onClickAddDetails"
study:layout_marginLeft="100dp"
study:text="Add User"/>
<Button
study:id="@+id/btnRetrieve"
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:onClick="onClickShowDetails"
study:layout_marginLeft="100dp"
study:text="Show Users"/>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 20 Activity and Multimedia with Databases
<TextView
study:id="@+id/res"
study:layout_width="match_parent"
study:layout_height="wrap_content"
study:layout_marginLeft="100dp"
study:clickable="false"
study:ems="10"/>
</LinearLayout>
package ex.contentprovider;
import study.content.ContentValues;
import study.content.Context;
import study.db.Cursor;
import study.net.Uri;
import study.ex;
import study.os.Bundle;
import study.view.MotionEvent;
import study.view.View;
import study.view.inputmethod.InputMethodManager;
import study.widget.EditText;
import study.widget.TextView;
import study.widget.Toast;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 21 Activity and Multimedia with Databases
strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
}
resultView.setText(strBuild);
}
else {
resultView.setText("No Records Found");
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="url" package="ex.contentprovider">
<application
study:allowBackup="true"
study:icon="@mipmap/ic_launcher"
study:label="@string/app_name"
study:roundIcon="@mipmap/ic_launcher_round"
study:supportsRtl="true"
study:theme="@style/AppTheme">
<activity study:name=".MainActivity">
<intent-filter>
<action study:name="android.intent.action.MAIN" />
<category study:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
study:authorities="ex.contentprovider.UsPr"
study:name=".UsersProvider">
</provider>
</application>
</manifest>
Output of Android Content Provider Example
When we run above example in android emulator we will get a result like as shown below
Fig. 5.3.4
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 22 Activity and Multimedia with Databases
Why does Android System need Content A fragment can implement a behaviour that has
n
Providers ?
no user interface component.
· The need for Content Providers arises because the
· To create a fragment, you must create a subclass of
database created in one application is not visible to
Fragment (or an existing subclass of it).
a second application.
· The Fragment class has code that looks a lot like an
· It is simple to create and store database in different
Activity.
applications using SQLite, however the problem is
this, a database in Android is private to the Fragment is
application that creates it. There is no common added
storage area in Android that every application can
access. Therefore, for different applications to use a onAttach()
database, Android system needs an interface that
allows such inter-application and inter-process data
onCreate()
exchange. This is where content provider comes to
play.
onCreateView()
5.3.2 Fragments
· In Android, Fragment is a part of an activity which
onActivityCreated()
enable more modular activity design. It will not be
wrong if we say a fragment is a kind of
onStart()
sub-activity.
· It represents a behaviour or a portion of user
interface in an Activity. onResume()
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 23 Activity and Multimedia with Databases
· It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and
onStop().
· In fact, if you're converting an existing Android application to use fragments, you might simply move
code from your activity's callback methods into the respective callback methods of your fragment.
· Usually, you should implement at least the following lifecycle methods :
1. onCreate()
The system calls this when creating the fragment. Within your implementation, you should initialize
essential components of the fragment that you want to retain when the fragment is paused or stopped,
then resumed.
2. onCreateView()
The system calls this when it's time for the fragment to draw its user interface for the first time. To
draw a UI for your fragment, you must return a View from this method that is the root of your
fragment's layout. You can return null if the fragment does not provide a UI.
3. onPause()
The system calls this method as the first indication that the user is leaving the fragment (though it
doesn't always mean the fragment is being destroyed). This is usually where you should commit any
changes that should be persisted beyond the current user session (because the user might not come
back).
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 24 Activity and Multimedia with Databases
<fragment
study:id="@+id/fragment2"
study:name="ex.java.in.fragmentexample.Fragment2"
study:layout_width="0px"
study:layout_height="match_parent"
study:layout_weight="1"
/>
</LinearLayout>
<FrameLayout xmlns:android="url"
xmlns:tools="url"
study:layout_width="match_parent"
study:layout_height="match_parent"
study:background="#F5F5DC"
tools:context="ex.java.in.fragmentexample.Fragment1">
<!-- TODO: Update blank fragment layout -->
<TextView
study:layout_width="match_parent"
study:layout_height="match_parent"
study:text="@string/hello_blank_fragment" />
</FrameLayout>
<FrameLayout xmlns:android="url"
xmlns:tools="url"
study:layout_width="match_parent"
study:layout_height="match_parent"
study:background="#F0FFFF"
tools:context="ex.java.in.fragmentexample.Fragment2">
<!-- TODO: Update blank fragment layout -->
<TextView
study:layout_width="match_parent"
study:layout_height="match_parent"
study:text="@string/hello_blank_fragment" />
</FrameLayout>
package ex.java.in.fragmentexample;
import study.ex;
import study.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
}
}
package ex.java.in.fragmentexample;
import study.os.Bundle;
import study.support.v4.app.Fragment;
import study.view.LayoutInflater;
import study.view.View;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 25 Activity and Multimedia with Databases
import study.view.ViewGroup;
public class Fragment1 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
package ex.java.in.fragmentexample;
import study.os.Bundle;
import study.support.v4.app.Fragment;
import study.view.LayoutInflater;
import study.view.View;
import study.view.ViewGroup;
Output :
Fig. 5.3.6
5.4 Service
· Service is a component which runs in the background, without direct interaction with the user.
· As the service has no user interface it is not bound to the lifecycle of an activity.
· Services are used for repetitive and potential long running operations, checking for new data, data
processing, indexing content, etc.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 26 Activity and Multimedia with Databases
Call to Call to
startService() bindService()
onCreate() onCreate()
onStartCommand() onBind()
onDestroy() onDestroy()
Service Service
shut down shut down
Unbounded Bounded
service service
5.4.2 Features of Service · You can start a service from an activity or other
application component by passing an Intent to start
5.4.2.1 Android Platform Service Service() or start Foreground Service() .
· The Android platform is Google Inc.'s open and free · The Android system calls the service's on Start
software stack that includes an operating system, Command() method and passes it the Intent , which
middleware and also key applications for use on specifies which service to start.
mobile devices, including smartphones. Android is
·A service needs to be declared in the
an Open Handset Alliance Project.
AndroidManifest.xml file and the implementing
What are Services in Android System ? class must extend the Service class or one of its
subclasses.
1) Faceless components : The components of
Android system that run in the background are 5.4.3.1 Create a Service
Service components. They are very much like
· Generally, in android to create a service we must
activities, only without a User Interface.
create a subclass of Service or use one of existing
2) Taking care of long running background tasks : subclass.
They carry out long-running tasks desired by the
· In android the application component such as an
application (without user intervention). Services
activity can start the service by calling start
run the background tasks that do not require a
Service() which results in calling the service's on
User Interface.
Start Command() method.
3) Unaffected by activity switching : Each Service · Following is the simple example of creating a
has a specific job, and they keep at it if you service in android application.
switch between different Activities, or even if
public class SampleService extends Service {
you switch to a different application altogether.
@Override
4) It can also provide functionality to other public int onStartCommand(Intent intent, int flags, int
applications. startId) {
5) Example of Service : A good example is your //TODO write your own code
music player. return Service.START_NOT_STICKY;
} @Override
· When you play music in your Android handset
public IBinder onBind(Intent intent) {
using a playlist, the music player takes care of the
//TODO for communication return IBinder
job itself, without user intervention. You do not
implementation
have to change the song every time one song ends.
return null;
This automation is due to the service component of
}
Android.
}
Service Components in Facebook Application Register a Service in Manifest File
· Talking about Facebook application again, the · Once we create a service, we must need to register
various friend feeds and friendship notifications etc. that isn android manifest file using <service>
are examples of Services. The new friend invites element like as shown below.
always update in the background, whether you <manifest ... >
interact with it or not. ...
<application ... >
5.4.3 Defining New Service <service study:name=".SampleService" />
Starting and defining custom services </application>
· Custom services are started from other Android ...
components, i.e., activities, broadcast receivers and </manifest>
other services.
Start a Service
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 28 Activity and Multimedia with Databases
Intent intent = new Intent(this, MyService.class); The service cannot be stopped until all clients unbind
the service.
startService(intent);
· There can be two forms of a service.The lifecycle of Following is the example of start playing music in
service can follow two different paths : started or background when we start a service and that music
bound. will play continuously until we stop the service in
android application.
1) Started Service
· Create a new android application using android
A service is started when component (like activity) studio and give names as Services. In case if you
calls startService() method, now it runs in the are not aware of creating an app in android studio
background indefinitely. It is stopped by stopService() check this article Android Hello World App.
method. The service can stop itself by calling the
stopSelf() method.
onCreate() onCreate()
onStart() onBind()
The service
is stopped
(no callback)
onUnbind()
onDestroy() onDestroy()
Service is Service is
shut down shut down
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 29 Activity and Multimedia with Databases
· Now we need to create our own custom service file MyService.java in \study\ex.services path to
define our actual provider and associated methods
· Once we create a new file MyService.java, open it and write the code like as shown below :
package ex.services;
import android.app.Service;
import study.content.Intent;
import android.media.MediaPlayer;
import study.os.IBinder;
import android.provider.Settings;
import study.widget.Toast;
study:onClick="startService"
study:layout_marginLeft="130dp"
study:layout_marginTop="150dp"
study:text="Start Service"/>
<Button
study:id="@+id/btnstop"
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:onClick="stopService"
study:layout_marginLeft="130dp"
study:layout_marginTop="20dp"
study:text="Stop Service"/>
</LinearLayout>
Now open MainActivity.java file from \study\ex.services path and write following to implement
custom broadcast intents.
package ex.services;
import study.content.Intent;
import study.ex;
import study.os.Bundle;
import study.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
}
// Start the service
public void startService(View view) {
startService(new Intent(this, MyService.class));
}
// Stop the service
public void stopService(View view) {
stopService(new Intent(this, MyService.class));
}
}
Now we need to register our service in android manifest file (AndroidManifest.xml) using <service>
attribute like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="url"
package="ex.services">
<application
study:allowBackup="true"
study:icon="@mipmap/ic_launcher"
study:label="@string/app_name"
study:roundIcon="@mipmap/ic_launcher_round"
study:supportsRtl="true"
study:theme="@style/AppTheme">
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 31 Activity and Multimedia with Databases
<activity study:name=".MainActivity">
<intent-filter>
<action study:name="android.intent.action.MAIN" />
<category study:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service study:name=".MyService" />
</application>
</manifest>
Output of Android Service Example
When we run above example in android emulator we will get a result like as shown below
Fig. 5.4.3
If we click on Start Service button, the default ringtone will start playing and it will continue until we
stop the service. This is how we can create, start or stop services in android applications based on our
requirements.
5.4.5 Permissions
· Android uses permission.
· API reference for the manifest tag that declares your app's required permissions.
· Device compatibility : Information about how Android works on different types of devices and an
introduction to how you can optimize your app for each device or restrict your app's availability to
different devices.
Linux kernel
1. Bottom layer of android operating system is Linux kernel.
2. Android is built on top of Linux 2.6 Kernel and few architectural changes made by Google.
3. Linux Kernel provides the basic system functionality such as process management, memory
management and device management
4. Linux kernel also provides array of device drivers which make our task easier while interfacing the
android with peripheral devices.
Libraries
1. On the top of Linux Kernel another layer called libraries is present.
2. It provides the different libraries useful for well functioning of android operating system.
3. Libraries are java libraries build specific for android operating system.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 32 Activity and Multimedia with Databases
Applications
Applications Framework
Libraries
Core
Surface Media Libraries
FreeType
Manager Framework
Dalvik Virtual
SSL SGL libc Machine
Linux kernel
Libraries Explanation
SQLite It is used to access data published by content providers and includes SQLite database management
classes
SSL It is used to provide internet security
OpenGL It is used to provide Java interface to the OpenGL/ES 3D graphics rendering API.
Media framework It is used to provides different media codecs which allow the recording and playback of different
media formats
WebKit It is the browser engine used to display internet content or HTML content
Android Runtime
1. It is third component of the android architecture and placed in second layer from bottom
2. It provides most important part of android called Dalvik Virtual Machine.
3. Dalvik Virtual Machine is similar to JVM but only difference is that it is designed and optimized
for Android.
4. Dalvik Virtual machine uses core functions of Linux such as memory management and
multithreading and enables each android app to run its own process.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 33 Activity and Multimedia with Databases
Application framework 2. All this top layer you will find all the
1. It is 2nd topmost component in android operating applications that comes along with your android
system stack device like phone, contacts, web browsers,
2. Android applications directly interacts with Camera etc. This layer shows all the applications
application framework. developed by you.
3. Application framework manages the basic
5.5.1 Multimedia Framework
functions of android device such as resource
management, voice call management etc · The Android multimedia framework includes
Important blocks of Application framework are : support for playing variety of common media types,
so that you can easily integrate audio, video and
Block Explanation images into your applications. (Refer Fig. 5.5.2)
Activity Block is used to manage complete · As the name suggests, Android multimedia
Manager activity life cycle of applications framework is used for playing media files. You can
Content Block is used to manage the data use the Media Player API to play an audio or a
Providers sharing between two applications video file :
Telephony Block is used to manages all voice 1. From your application's resources.
Manager calls
2. From standalone files (using internal URIs).
Location Block is used to manage the
Manager Locations obtained using GPS or cell 3. From a stream over a network connection (using
tower URLs).
Resource Block is used to manage the
Manager different types of resources used in 5.5.2 Play Audio and Video
android app · Android supports the playing of audio and video
Applications through the Media Player class.
1. Applications created by third party users or · The Media Player class is at the heart of the
developer will be installed on application layer. Android media package.
mediarecorder
Camera mediaplayer
Audio
MediaPlayer Service Filnger
Camera Service
Surface
UI lib Filnger
Midi Vorbis libaudio
Camera PV Author PVPlayer Player Player
Hardware Alsa lib
Packet Video Framework
Native
Driver V412
Capture Hardware Codes Main Video Audio
framebuffer Plane (Alsa)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 34 Activity and Multimedia with Databases
· Apart from the Media Player class, the Sound Pool Playing Audio from file-system
and Jet Player classes are also provided to be used · SoundPool Class load (String path, int priority)
to play audio files. method is used to load the audio file from raw
folder. If you want to load a sound from the raw
5.5.2.1 Playing Audio Files resource file "bigwave.mp3", you would specify
· Media Player is the most widely used class for "R.raw.bigwave" as the resource ID. This returns the
playing media files. integer SoundID that can be use to play the sound.
· Media Player has been designed to play large audio
files and streams also supporting playback ToneGenerator or Stream
operations like stop, start, pause etc and seeking · This class provides methods to play DTMF tones,
operations. call supervisory tones and proprietary tones.
· It also supports listeners related to the media · The ToneGenerator object requires an output stream
operations. type and volume. startTone() is used to play the
· Playing of audio and video in MediaPlayer can be tone. startTone() method starts the playback of a
done through the following ways : tone of the specified type for the specified duration.
n Playing from raw resource.
//Output Stream Type and Volume
n Playing from file-system.
ToneGenerator tg=new
n Playing from stream. ToneGenerator(AudioManager.STREAM_RING, 100);
//Play Tone
Playing Audio from resourse
tg.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT);
· This is the most common way of playing audio
files. 5.5.2.2 Playing Video Files
· In this case the audio file should be present in the · Android provides a specialized view control
raw or assets folder of the project like the one study.widget.
shown in Fig. 5.5.3.
· VideoView that encapsulates creating and
initializing the MediaPlayer.
· The VideoView class can load images from various
sources (such as resources or content providers),
and takes care of computing its measurement from
the video so that it can be used in any layout
manager, also providing various display options
such as scaling and tinting.
· VideoView can be used to display video files
present in SDCard FileSystem or files present
online.
· MediaPlayer class provides a different type of
methods to control audio and video files based on
requirements.
· Voice input based command and text to speech is a study:text="Enter Text to Speak"/>
trend now. In this tutorial, we will explore how <EditText
"Text-To-Speech(TTS)" feature can be implemented study:id="@+id/txtSpeak"
in an Android APP. study:layout_width="wrap_content"
study:layout_height="wrap_content"
· Text to speech (TTS) makes an android device read
study:layout_marginLeft="100dp"
the text and convert it to audio out via the speaker.
study:ems="10"/>
Android TTS supports multiple languages.
<Button
· TTS is a simple but powerful feature. study:id="@+id/btnSpeech"
· It can also be effectively used in mobile APPs study:layout_width="wrap_content"
dedicated to visually impaired people or in study:layout_height="wrap_content"
educational app for kids or can be used in study:layout_marginLeft="100dp"
pronunciation learning app, etc. These are some of study:text="Speak" />
the ways you can use TTS. </LinearLayout>
Now open your main activity file MainActivity.java
· Using TextToSpeech enhances interaction between
from \study\ex.textspeechexample path and write the
the user and the mobile application.
code like as shown below
· Android TTS was available from version 1.6.
package ex.textspeechexample;
· It has features to control speed, pitch of speech as import study.os.Build;
well as type of language. We will also learn to use import android.speech.tts.TextToSpeech;
these features in this tutorial. import study.ex;
· TextToSpeech needs to be initialized first. For this, import study.os.Bundle;
you need to implement the TextToSpeech. import study.util.Log;
OnInitListener interface and override the method : import study.view.View;
onInit. import study.widget.Button;
Example : TextToSpeech tts = new TextToSpeech(this, import study.widget.EditText;
import java.util.Locale;
this)
text = "Please enter some text to speak."; motion, and include accelerometers, gravity
} sensors, gyroscopes, and rotation vector sensors.
if (Build.VERSION.SDK_INT >= · In addition, sensors can either be :
Build.VERSION_CODES.LOLLIPOP) { n Hardware based. These are physical components
textToSpeech.speak(text,
that are built into the device and directly
TextToSpeech.QUEUE_FLUSH, null, null);
measure specific properties, such as acceleration
}
or the strength of the surrounding geomagnetic
else {
textToSpeech.speak(text,
fields.
TextToSpeech.QUEUE_FLUSH, null); Software based, sometimes known as virtual
n
Fig. 5.5.4
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 37 Activity and Multimedia with Databases
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 38 Activity and Multimedia with Databases
¡ Progress : The type of the progress units published during the background computation
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 39 Activity and Multimedia with Databases
· Android has a built in microphone through which you can capture audio and store it , or play it in
your phone.
· There are many ways to do that but the most common way is through Media Recorder class. Android
provides MediaRecorder class to record audio or video.
· Android provides MediaRecorder class to record audio or video.
· In order to use MediaRecorder class, you will first create an instance of MediaRecorder class. Its
syntax is given below.
MediaRecorder myAudioRecorder = new MediaRecorder();
Now you will set the source , output and encoding format and output file. Their syntax is given below.
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
5.6.1 Camera
· Camera is mainly used to capture picture and video. We can control the camera by using methods of
camera api.
· The Android framework provides the facility of working with Camera in two ways :
1. By using existing camera application
2. By using Camera Api
1. Using camera by using camera application : We can capture pictures without using the instance of
Camera class. Here you will use an intent action type of MediaStore.ACTION_IMAGE_CAPTURE
to launch an existing Camera application on your phone. In Android MediaStore is a type of
DataBase which stores pictures and videos in android.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
2. Using Camera By using Camera Api : This class is used for controlling device cameras. It can be
used to take pictures when you are building a camera application.
Camera API works in following ways :
1. Camera Manager : This is used to get all the cameras available in the device like front camera back
camera each having the camera id.
2. CameraDevice : You can get it from Camera Manager class by its id.
3. CaptureRequest: You can create a capture request from camera device to capture images.
4. CameraCaptureSession : To get capture request's from Camera Device create a
CameraCaptureSession.
5. CameraCaptureSession.CaptureCallback : This is going to provide the Capture session results.
Understanding basic classes of Camera Intent and API There are mainly four classes that we are going to discuss.
1. Intent : By the help of 2 constants of MediaStore class, we can capture picture and video without using the
instance of Camera class.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 40 Activity and Multimedia with Databases
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 41 Activity and Multimedia with Databases
When we click on Take a Photo button, the camera the discoverable devices using a service discovery
will start and we can take the picture of whatever we process.
want, the captured image will be shown in defined · Once the device accepts the pairing request, the two
imageview. devices will exchange a security keys to complete
the bonding process and the devices will cache
5.7 Bluetooth these security keys for later use.
· Once the pairing and bonding process completes,
the devices are ready to exchange the required
information.
· When the session is complete, the device that
initiated the pairing request will release the channel
that linked to the discoverable device.
· The two devices remain bonded, so they can
reconnect automatically during a future session as
long as they're in the range of each other.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 43 Activity and Multimedia with Databases
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 44 Activity and Multimedia with Databases
13. Together Animation Step 3 : Now, you have to create some Animation
files in the anim folder that you have created in the
Basic Animation using XML
previous step. So, right click on res/anim and select
· The best part about animation that I like is the fact
New > Animation Resource File and then enter the
that you can use animation just by writing some
XML code. Yeah and this is the need because in file name and click on OK. Here, we will see how to
Animation, you are dealing with the UI part and in use the Fade In animation. So, my file name is
order to have Animation, XML codes can be used. fade_in.xml.
· In order to have a thorough knowledge of Step 4 : Our next step is to add the animation that
Animation, you should know some of the important
we want to perform in the file that we have added
XML attributes that can be used in your application
in the previous step. Add the below code for Fade In
to have a perfect Animation. Some of these
attributes are : animation in your fade_in.xml file :
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 45 Activity and Multimedia with Databases
xmlns:tools="url" applicationContext,
xmlns:app="ex/apk/res-auto" R.anim.fade_in)
study:layout_width="match_parent" //handling aniamtion on button click
study:layout_height="match_parent" btn.setOnClickListener {
tools:context=".MainActivity"> txtMessage.setVisibility(View.VISIBLE)
<TextView // starting the animation
study:id="@+id/text" txtMessage.startAnimation(animFadein)
study:layout_width="wrap_content" }
study:layout_height="wrap_content" }
study:text="Hello World!" }
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
loadAnimation() method is used to load the desired
app:layout_constraintRight_toRightOf="parent"
animation i.e. in our case, it is fade_in.xml file.
app:layout_constraintTop_toTopOf="parent"/>
<Button startAnimation() method is used to start an animation
study:id="@+id/btn" on a particular component. If you want to perform
study:layout_width="wrap_content" some operations before, after or during the
study:layout_height="wrap_content" Animation, then you can implement the
app:layout_constraintTop_toBottomOf="@+id/text" AnimationListener in your call and then override the
app:layout_constraintEnd_toEndOf="parent" below function for the same :
study:layout_marginEnd="8dp"
study:layout_marginRight="8dp" 1. onAnimationStart(): Will be called when the
app:layout_constraintStart_toStartOf="parent" Animation will start.
study:layout_marginLeft="8dp" 2. onAnimationEnd(): Will be called when the
study:layout_marginStart="8dp" Animation will end.
study:layout_marginBottom="8dp"
3. onAnimationRepeat(): Will be called when you
app:layout_constraintBottom_toBottomOf="parent"
repeat an Animation.
study:text="Click Me"/>
</studyx.constraintlayout.widget.ConstraintLayout> All you need to do is implement the
AnimationListener and then set the animation
Step 6 : After adding the UI, our last step is to listener. Our final code after implementing the
connect the animation when the Button is clicked. So, AnimationListener will be :
the code of MainActivty.kt file looks like : class MainActivity : AppCompatActivity(),
Animation.AnimationListener {
class MainActivity : AppCompatActivity() {
//TextView
//TextView lateinit var txtMessage: TextView
lateinit var txtMessage: TextView //Button
//Button lateinit var btn: Button
lateinit var btn: Button // Animation
// Animation lateinit var animFadein: Animation
lateinit var animFadein: Animation override fun onCreate(savedInstanceState: Bundle?) {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState)
super.onCreate(savedInstanceState) setContentView(R.layout.act_main)
setContentView(R.layout.act_main) txtMessage = findViewById<TextView>(R.id.text)
txtMessage = findViewById<TextView>(R.id.text) btn = findViewById<Button>(R.id.btn)
btn = findViewById<Button>(R.id.btn) //loading Animation
//loading Animation animFadein = AnimationUtils.loadAnimation(
animFadein = AnimationUtils.loadAnimation( applicationContext,
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 46 Activity and Multimedia with Databases
R.anim.fade_in) study:toDegrees="360"
//set animation listener study:pivotX="50%"
animFadein.setAnimationListener(this) study:pivotY="50%"
//handling aniamtion on button click study:duration="5000" >
btn.setOnClickListener { </rotate>
txtMessage.setVisibility(View.VISIBLE) <rotate xmlns:android="url"
// starting the animation study:startOffset="5000"
txtMessage.startAnimation(animFadein) study:fromDegrees="360"
} study:toDegrees="0"
} study:pivotX="50%"
override fun onAnimationRepeat(p0: Animation?) { study:pivotY="50%"
//To change body of created functions use File | study:duration="5000" >
Settings | File Templates. </rotate>
} </set>
override fun onAnimationEnd(p0: Animation?) {
//To change body of created functions use File |
Settings | File Templates.
Animation for Blink
<?xml version="1.0" encoding="utf-8"?>
}
<set xmlns:android="url">
override fun onAnimationStart(p0: Animation?) {
<alpha study:fromAlpha="0.0"
//To change body of created functions use File |
study:toAlpha="1.0"
Settings | File Templates.
}
study:interpolator="@study:anim/accelerate_interpolator"
}
study:duration="600"
study:repeatMode="reverse"
Run your application on mobile device and see the study:repeatCount="infinite"/>
Animation. </set>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 47 Activity and Multimedia with Databases
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 48 Activity and Multimedia with Databases
3. SQLite is embedded within the Android 5.8.3 Extracting Value from Cursor
operating System, so you don't need anything · The SQLite Database always presents the results as
external on Android to use SQLite a Cursor in a table format that resembles that of a
4. To manipulate data (insert, update, delete) in SQL database.
SQLite database - we'll use SQL (Structured · Cursors are what contain the result set of a query
Query Language) made against a database in Android.
· The Cursor class has an API that allows an app to
5.8.1 Necessity of SQLite Database
read (in a type-safe manner) the columns that were
· SQLite is an open-source relational database i.e.
returned from the query as well as iterate over the
used to perform database operations on android
rows of the result set.
devices such as storing, manipulating or retrieving
· The basic purpose of a cursor is to point to a single
persistent data from the database.
row of the result fetched by the query.
· It is embedded in android bydefault. So, there is no
· You can think of the data as an array of rows.
need to perform any database setup or
administration task. · A cursor is a pointer into one row of that structured
data.
5.8.2 Creation and Connection of the Database · The Cursor class provides methods for moving the
1. At a shell or DOS prompt, enter: "sqlite3 test.db". cursor through the data structure, and methods to
This will create a new database named "test.db". get the data from the fields in each row.
(You can use a different name if you like.) · The Cursor class has a number of subclasses that
2. Enter SQL commands at the prompt to create implement cursors for specific types of data.
and populate the new database. SQLiteCursor exposes results from a query on a
n
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 49 Activity and Multimedia with Databases
n close() releases all resources and makes the cursor completely invalid. Remember to call close to
free resources!
Advantage of SQLite :
1. If you have data related with each other, file will not allow you to relate them. At that time SQLite
will help you.
2. If you want to query your data, store the data in structured manner you will prefer SQLite
3. SQLite has higher performance
4. An SQLite database can also be queried and the data retrieval is much more robust.
5. The study.db and study.db.sqlite packages offer a higher-performance alternative where source
compatibility is not an issue.
6. Android-databases created in Android are visible only to the application that created them
7. There is no file parsing and generating code to write and debug.
8. Content can be accessed and updated using powerful SQL queries, greatly reducing the complexity
of the application code.
9. Extending the file format for new capabilities in later releases is as simple as adding new tables or
new columns to existing tables.
10. Diverse content which might otherwise be stored as a "pile-of-files" can be encapsulated into a
single disk file.
11. The content can be viewed using third-party tools.
12. The application file is portable across all operating systems, 32-bit and 64-bit and big- and
little-endian architectures.
13. The application only has to load as much data as it needs, rather than reading the entire
application file and holding a complete parse in memory. Startup time and memory consumption
are reduced.
14. Small edits only overwrite the parts of the file that change, not the entire file, thus improving
performance and reducing wear on SSD drives.
15. Content is updated continuously and atomically so that there is no work lost in the event of a
power failure or crash.
16. Applications can leverage the full-text search and RTREE capabilities that are built into SQLite.
17. Performance problems can often be resolved using CREATE INDEX rather than redesigning,
rewriting, and retesting application code.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 50 Activity and Multimedia with Databases
18. A federation of programs, perhaps written in different programming languages, can all access the
same application file with no compatibility concerns.
19. Multiple processes can attach to the same application file and can read and write without
interfering with each another.
20. Cross-session undo/redo can be implemented using triggers.
21. In many common cases, loading content from an SQLite database is faster than loading content
out of individual files. See Internal Versus External BLOBs for additional information.
22. Content stored in an SQLite database is more likely to be recoverable decades in the future, long
after all traces of the original application have been lost. Data lives longer than code.
Step 2 : Add components in the main activity as shown in the Fig. 5.8.2 below.
Name
Surname
Marks
id
Update Delete
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 51 Activity and Multimedia with Databases
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 52 Activity and Multimedia with Databases
study:id="@+id/textView_id"
study:layout_below="@+id/editText_Marks"
study:layout_alignParentLeft="true"
study:layout_alignParentStart="true" />
<EditText
study:layout_width="match_parent"
study:layout_height="wrap_content"
study:id="@+id/editText_id"
study:layout_alignTop="@+id/textView_id"
study:layout_toRightOf="@+id/textView3"
study:layout_toEndOf="@+id/textView3" />
</RelativeLayout>
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME
TEXT,SURNAME TEXT,MARKS INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name,String surname,String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public boolean updateData(String id,String name,String surname,String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}
public Integer deleteData (String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
}
MainActivity.java
package my.example.programmingknowledge.sqliteapp;
import android.app.AlertDialog;
import study.db.Cursor;
import study.support.v7.app.ActionBarActivity;
import study.os.Bundle;
import study.view.Menu;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 54 Activity and Multimedia with Databases
import study.view.MenuItem;
import study.view.View;
import study.widget.Button;
import study.widget.EditText;
import study.widget.Toast;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 55 Activity and Multimedia with Databases
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 56 Activity and Multimedia with Databases
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}}
Output
Fig 5.8.4 Add Data Fig. 5.8.5 Data Successfully added to Fig. 5.8.6 View Data
sqlite database
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 57 Activity and Multimedia with Databases
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 58 Activity and Multimedia with Databases
Notes
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - VI
6
6.1 SMS Telephony
Security and Application Deployment
6.1.1 Sending and Receiving SMS Messages nYou can manage SMS operations such as
dividing a message into fragments, sending a
Android smartphones can send and receive messages
multipart message, get carrier-dependent
to or from any other phone that supports Short
configuration values, and so on.
Message Service (SMS).
To receive SMS messages, use the onReceive()
You have two choices for sending SMS messages : method of the BroadcastReceiver class.
· Use an implicit Intent to launch a messaging app
with the ACTION_SENDTO intent action. 6.2 Location Based Service
n This is the simplest choice for sending messages.
Developing applications for mobile devices gives us a
The user can add a picture or other attachment lot more opportunities for context based information
in the messaging app, if the messaging app than a traditional web application.
supports adding attachments.
One of the inputs for context sensitive information is
n Your app doesn't need code to request
the users current location.
permission from the user.
n If the user has multiple SMS messaging apps 6.2.1 Location API's
installed on the Android phone, the App This was not ideal since as a developer of an
chooser will appear with a list of these apps, application, you probably are not concerned about
and the user can choose which one to use. the implementation details of obtaining users location.
(Android smartphones will have at least one, Fortunately Google's Location API's provide a much
such as Messenger.) better way for working with location data.
n The user can change the message in the
The Location API's provide the following
messaging app before sending it.
functionality :
n The user navigates back to your app using the · Fused location provider which abstracts away the
Back button. underlying location providers.
· Send the SMS message using the sendTextMessage()
· Geofencing. Lets your application setup geographic
method or other methods of the SmsManager class.
boundaries around specific locations and then
receive notifications when the user enters or leaves Any app that wants to behave as the user's default
those areas. SMS app must handle the following intents:
· Activity recognition. Is the user walking or in a car. · In a broadcast receiver, include an intent filter. The
Android System gives the opportunity to determine broadcast receiver must also require the
the current geographical location and to build BROADCAST SMS permission. This allows your
location-aware applications, without focusing on the app to directly receive incoming SMS messages.
details of the underlying location technology. · In a broadcast receiver, include an intent filter for
the broadcast receiver must also require the
To obtain the user location, we can use one of :
BROADCAST_WAP_PUSH permission. This allows
· GPS Provider
your app to directly receive incoming MMS
· Android's Network Location Provider (availability messages.
of cell tower and WiFi access points)
· In your activity that delivers new messages, include
Every provider has it's cons and pros and can be an intent filter for SENDTO with schemas, sms:,
used depending on the circumstances at each smsto:, mms:, and mmsto:. This allows your app to
situation. receive intents from other apps that want to deliver
For example GPS, is exact and more appropriate for a message.
outdoors, but it consumes a lot of battery power. On · In a service, include an intent filter for Telephony
the other hand, network provider works for indoors Manager with schemas, sms:, smsto:, mms:, and
as well for outdoors and has a lower battery mmsto:.This service must also requirethe
consumption and a faster response. SEND_RESPOND_VIA_MESSAGE permission.
Location Based Services are provided by Android · This allows users to respond to incoming phone
through its location framework. calls with an immediate text message using your
app.
The framework provides a location API which
Other apps that are not selected as the default SMS
consists of certain classes and interface.
app can only read the SMS Provider, but may also be
These classes and interface are the key components notified when a new SMS arrives by listening for the
which allow us to develop Location Based RECEIVED_ACTION broadcast.
Application in Android.
6.2.3 Getting the Maps API Key
6.2.1.1 Classes and Interfaces of Location Based Services
LocationManager - This class helps to get access to 6.2.3.1 What is a Google Maps API Key ?
the location service of the system. ·A Google Maps API key is a personal code
provided by Google to access Google Maps on this
LocationListener - This interface acts as the listener
site.
which receives notification from the location manager
when the location changes or the location provider is · Your API key provides you with a free quota of
Step 1 :
Open Google developer console and signin with your
gmail account :
https://console.developers.google.exm/project
Step 2 :
Now create new project. You can create new project
by clicking on the Create Project button and give Fig 6.2.4 Google Map Android API
name to your project.
Step 6 :
Now enable the Google Maps Android API.
Step 8 :
Fig 6.2.2 Opening a dashboard Here click on Create credentials and choose API key
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-4 Security and Application Deployment
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-5 Security and Application Deployment
3. Importantly, while importing, check Copy projects into workspace option as shown in the below
image.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-6 Security and Application Deployment
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-7 Security and Application Deployment
<meta-data
study:name="my.ex.maps.API_KEY"
study:value="Your_API_Key" />
OpenGL ES V2 - Required for Google Maps V2. The next thing you need to do is to add some
permissions along with the Google Map API. Its
Add the following features to your manifest. syntax is given below :
<!-- Required OpenGL ES 2.0. for Maps V2 --> <!--Permissions-->
<uses-permission
<uses-feature
study:name="android.permission.ACCESS_NETWORK_STA
study:glEsVersion="0x00020000" TE" />
<uses-permission
study:required="true" />
study:name="android.permission.INTERNET" />
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-8 Security and Application Deployment
methods available in the Gmap class , that helps you 1. abstract void onConnected(Bundle
more customize the map. connectionHint)
This callback method is called when location
In Android, Zoom Controls class display simple set service is connected to the location client
of controls that is used for zooming and provides successfully. You will use connect () method to
connect to the location client.
callback to register for events. Zoom Controls has
two buttons Zoom In and Zoom Out which are used 2. abstract void onDisconnected()
to control the zooming functionality. This callback method is called when the client
is disconnected. You will use disconnect
6.2.5.2 Important Methods of Zoom Controls () method to disconnect from the location client.
Now let's discuss some common methods which are 3. abstract void
used to configure Zoom Controls in our application. onConnectionFailed(ConnectionResult result)
This callback method is called when there was
an error connecting the client to the service.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-9 Security and Application Deployment
You should create the location client in onCreate() method of your activity class, then connect it in
onStart(), so that Location Services maintains the current location while your activity is fully visible.
You should disconnect the client in onStop() method, so that when your app is not visible, Location
Services is not maintaining the current location. This helps in saving battery power up-to a large extent.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6 - 10 Security and Application Deployment
Fig 6.2.18 Google Maps Activity and then click Next and finish
Step 4 : Here enter your Google Maps API key in Step 7 : Now define internet and location
place of YOUR_KEY_HERE. permissions in Android Manifest
Step 5 : Now open build.gradle and add compile Step 8 : Now we will code MapsActivity.java file
'my.ex.gms:play-services:8.4.0' in dependencies for inserting callbacks in Google Maps
Step 6 : Now open activity_maps.xml and add a
6.2.9 Geocoding and Reverse Geocoding
fragment code in it
· Android Geocoder class is used for Geocoding as
Here add a fragment element to the activity's layout well as Reverse Geocoding. Geocoding refers to
file to define a Fragment object. In this element, set transforming street address or any address into
the study:name attribute to latitude and longitude.
"my.ex.gms.maps.MapFragment". · Reverse Geocoding refers to transforming latitude
and longitude into its corresponding street address.
This automatically attaches a MapFragment to the
activity. · Geocoding is the process of transforming a
description of a location-such as a pair of
coordinates, an address, or a name of a place-to a
location on the earth's surface.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6 - 11 Security and Application Deployment
· You can geocode by entering one location description at a time or by providing many of them at once
in a table.
· Android Geocoder class is used for Geocoding as well as Reverse Geocoding.
· Reverse geocoding is the process of back (reverse) coding of a point location (latitude, longitude) to a
readable address or place name.
· Reverse Geocoding refers to transforming latitude and longitude into its corresponding street address.
· The process of turning coordinates into a String address is called reverse geocoding.
· Instead of supplying the builder with a String address you'd pass in coordinates instead.
· Handling the response is like forward geocoding.
· While the geocoder gives one coordinate, the response will often give you multiple valid ways to
describe the specific location.
· For example, one might be the street name while another result will be the country. The ordering of
the list usually goes from most relevant to least.
Geocoding request :
Before making a geocoding request, you must build the MapboxGeocoding object by passing in two
required parameters; a valid Mapbox access token and a location query (typically an address or
description). Many other parameters are available to help bias and manipulate the response that you
receive.
MapboxGeocoding mapboxGeocoding = MapboxGeocoding.builder()
.accessToken(MAPBOX_ACCESS_TOKEN)
.query("1600 Pennsylvania Ave NW")
.build();
Geocoding response
Once you have built your MapboxGeocoding object with all the parameters that you'd like to use in
the request, you'll need to asynchronously send the request using enqueueCall(). Once the request
receives a response, it will tell the callback where you can handle the response appropriately.
mapboxGeocoding.enqueueCall(new Callback<GeocodingResponse>() {
@Override
public void onResponse(Call<GeocodingResponse> call, Response<GeocodingResponse> response) {
List<CarmenFeature> results = response.body().features();
if (results.size() > 0) {
// Log the first results Point.
Point firstResultPoint = results.get(0).center();
Log.d(TAG, "onResponse: " + firstResultPoint.toString());
} else {
6.3 Android Security Model well as certain system features (such as camera and
internet).
The security model adopted by Android is Identity
Based. Answer : The security model adopted by · Depending on the feature, the system might grant
Android is the Linux OS based, where the the permission automatically or might prompt the
applications need to take permission from the user user to approve the request.
before using any hardware component of the · A central design point of the Android security
androiddevice. architecture is that no app, by default, has
permission to perform any operations that would
Android's Security Model :
adversely impact other apps, the operating system,
· Like the rest of the system, Android's security
or the user.
model also takes advantage of the security features
offered by the Linux kernel. · This includes reading or writing the user's private
data (such as contacts or emails), reading or writing
· Linux is a multiuser operating system and the
another app's files, performing network access,
kernel can isolate user resources from one another,
keeping the device awake, and so on.
just as it isolates processes.
· In a Linux system, one user cannot access another 6.3.1.1 Define a Custom App Permission
user's files (unless explicitly granted permission) · By defining custom permissions, an app can share
and each process runs with the identity (user and its resources and capabilities with other apps.
group ID, usually referred to as UID and GID) of Android is a privilege-separated operating system,
the user that started it, unless the set-user-ID or in which each app runs with a distinct system
set-group-ID (SUID and SGID) bits are set on the identity (Linux user ID and group ID). Parts of the
corresponding executable file. system are also separated into distinct identities.
· Android takes advantage of this user isolation, but · Linux thereby isolates apps from each other and
treats users differently than a traditional Linux from the system.
system (desktop or server) does.
· Apps can expose their functionality to other apps
· In a traditional system, a UID is given either to a by defining permissions which those other apps can
physical user that can log into the system and request.
execute commands via the shell, or to a system
· They can also define permissions which are
service (daemon) that executes in the background
automatically made available to any other apps
(because system daemons are often accessible over
which are signed with the same certificate.
the network, running each daemon with a dedicated
UID can limit the damage if one is compromised). 6.3.1.2 App Signing
· Android was originally designed for smartphones, · All APKs must be signed with a certificate whose
and because mobile phones are personal devices, private key is held by their developer.
there was no need to register different physical · This certificate identifies the author of the app.
users with the system.
· The certificate does not need to be signed by a
· The physical user is implicit, and UIDs are used to certificate authority; it is perfectly allowable, and
distinguish applications instead. typical, for Android apps to use self-signed
· Thisforms the basis of Android's application certificates.
sandboxing. · The purpose of certificates in Android is to
distinguish app authors.
6.3.1 Declaring and using Permissions
· This allows the system to grant or deny apps access
· The purpose of a permission is to protect the
to signature-level permissions and to grant or deny
privacy of an Android user.
an app's request to be given the same Linux
· Android apps must request permission to access identity as another app.
sensitive user data (such as contacts and SMS), as
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6 - 13 Security and Application Deployment
6.3.1.3 User IDs and File Access · You must do this if the apps are not all signed with
· At install time, Android gives each package a the same certificate.
distinct Linux user ID. · Even if the apps are all signed with the same
· The identity remains constant for the duration of certificate, it's a best practice to define each
the package's life on that device. permission once only.
· On a different device, the same package may have a · If the functionality is only available to apps signed
different UID; what matters is that each package with the same signature as the providing app, you
has a distinct UID on a given device. may be able to avoid defining custom permissions
· Because security enforcement happens at the by using signature checks.
process level, the code of any two packages cannot · When one of your apps makes a request of another
normally run in the same process, since they need of your apps, the second app can verify that both
to run as different Linux users. apps are signed with the same certificate before
· Any data stored by an app will be assigned that
complying with the request.
app's user ID, and not normally accessible to other
packages. 6.4 Application Deployment
· This certificate has a private key with a known Once you create the profile, it will be automatically
password, so you can run and debug your app linked to your developer account.
without typing the password every time you make
a change to your project. Step 3 : Create an App
· Android Studio signs your app in debug mode
Now that you have set up your Play Console, you
automatically when you run or debug your project can finally add your app. Here's how to do that :
from the IDE. 1. Navigate to the 'All applications' tab in the menu
· You can run and debug an app signed in debug 2. Click on 'Create Application'
mode on the emulator and on devices connected to
3. Select your app's default language from the
your development manchine through USB, but you
drop-down menu
cannot distribute an app signed in debug mode.
4. Type in a title for your app
· By default, the debug configuration uses a debug
keystore, with a known password and a default key 5. Click on "Create"
with a known password. The title of your app will show on Google Play after
you've published. Don't worry too much about it at
6.4.2.2 Signing in Release Mode
this stage; you can always change the name later.
In release mode, you sign your app with your own
After you've created your app, you'll be taken to the
certificate :
store entry page. Here, you will need to fill out all
1. Create a keystore. A keystore is a binary file that the details for your app's store listing.
contains a set of private keys. You must keep
your keystore in a safe and secure place. Step 4 : Prepare Store Listing
2. Create a private key. A private key represents · Before you can publish your app, you need to
the entity to be identified with the app, such as a prepare its store listing.
person or a company. · These are all the details that will show up to
3. Add the signing configuration to the build file customers on your app's listing on Google Play.
for the app module. Note : You don't necessarily have to complete this
step before moving on to the next one. You can
6.4.3 Deploying App on Google Play Store, always save a draft and revisit it later when you're
Become a Publisher, Developer Console ready to publish.
Step 1 : Create a Developer Account
Step 5 : Upload APK to an App Release
· Before you can publish any app on Google Play,
· Now that you have prepared the ground to finally
you need to create a Developer Account.
upload your app, it's time to dig out your APK file.
· You can easily sign up for one using your existing
· The Android Package Kit (or APK, for short) is the
Google Account.
file format used by the Android operating system to
Step 2 : Plan to Sell ? Link Your Merchant Account distribute and install apps.
If you want to publish a paid app or plan to sell · Simply put, your APK file contains all the elements
in-app purchases, you need to create a payments needed for your app to actually work on a device.
center profile, i.e. a merchant account. Here's how
· Google offers you multiple ways to upload and
you can do that :
release your APK. Before you upload the file,
1. Sign in to your Play Console however, you need to create an app release.
2. Click on Download Reports - Financial · To create a release, select the app you created in
· Here, you need to select the type of release you Step 7 : Set Up Pricing and Distribution
want to upload your first app version to. · Before you can fill out the details required in this
step, you need to determine your app's
· You can choose between an internal test, a closed
monetization strategy.
test, an open test, and a production release.
· Once you know how your app is going to make
· The first three releases allow you to test out your
money, you can go ahead and set up your app as
app among a select group of users before you make
free or paid.
it go live for everyone to access.
· However, if you create a production release, your Step 8 : Rollout Release to Publish Your App
uploaded app version will become accessible to · You're almost done. The final step involves
everyone in the countries you choose to distribute it reviewing and rolling out your release after making
in. sure you've taken care of everything else.
· Once you've picked an option, click on 'Create · Before you review and rollout your release, make
release.' sure the store listing, content rating, and pricing
· Next, follow the on-screen instructions to add your and distribution sections of your app each have a
APK files, and name and describe your release. green check mark next to them.
· Once you're sure you've filled out those details,
Step 6 : Provide an Appropriate Content Rating
select your app and navigate to 'Release
· If you don't assign a rating to your app, it will be
management' - 'App releases.' Press 'Edit release'
listed as 'Unrated'. Apps that are 'Unrated' may get
next to your desired release, and review it.
removed from Google Play.
· Next, click on 'Review' to be taken to the 'Review
· To rate your app, you need to fill out a content
and rollout release' screen. Here, you can see if
rating questionnaire. You can access it when you
there are any issues or warnings you might have
select your app in the Play Console, and navigate to
missed out on.
'Store presence' - 'Content rating' on the left menu.
· Finally, select 'Confirm rollout.' This will also
· Make sure you enter accurate information.
publish your app to all users in your target
Misrepresentation of your app's content can lead to
countries on Google Play.
suspension or removal from the Play Store.
· An appropriate content rating will also help you get
to the right audience, which will eventually qqq
improve your engagement rates.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6 - 16 Security and Application Deployment
Notes
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
SOLVED SAMPLE TEST PAPER - I
Mobile Application Development
T.Y. Diploma Sem - VI
Computer Engg. Program Group (CO/CM/IF/CW)
Instructions :
a) State difference between Windows operating system and Android operating system. (Refer section 1.1)
b) List various IDEs that can be used to execute Android operating system. (Refer section 1.3)
c) List different attributes which can be used with any layout managers. (Refer section 3.3.1)
d) List features of Android Operating System. (Refer section 1.2)
e) State the steps for creating the Virtual device. (Refer section 2.3)
Q.2 Attempt any THREE. [12]
qqq
(S - 1)
Mobile Application Development S-2 Solved Sample Papers
Instructions :
a) Explain grid view. Enlist different methods of grid view. (Refer section 4.2.1)
b) Describe in detail Time & Date Picker. (Refer section 4.3)
c) Explain activity life cycle in detail (Refer section 5.2)
d) Write a short note on SQLite database. Enlist their advantages. (Refer section 5.8)
e) Explain the term Android security model (Refer section 6.3)
f) Explain process of application deployment in detail (Refer section 6.4)
qqq
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
SOLVED SAMPLE QUESTION PAPER
Mobile Application Development
T.Y. Diploma Sem - VI
Computer Engg. Program Group (CO/CM/IF/CW)
Instructions :
a) With neat diagram, show the major components of Android stack. (Refer section 1.4)
b) Differentiate between JVM and DVM. (Refer section 2.5)
c) Explain the activity life cycle. (Refer section 5.2)
d) What are the benefits of Content providers. (Refer section 5.3)
Q.3 Attempt any THREE of the following. [12]
a) Explore the Steps to install and configure Android Studio and SDK. (Refer section 2.6.3)
b) Write an xml tag for the determinate progress bar. (Refer section 4.1.9)
c) Define SQLite. Explain example table for SQLite store data in tables. (Refer section 5.8)
d) Define activity. Explain the steps for creating activities. (Refer section 5.2)
Q.4 Attempt any THREE of the following. [12]
(S - 3)
Mobile Application Development S-4 Solved Sample Papers
b) Write a program to create a first display screen of any search engine using Auto Complete Text View.
(Refer section 4.1.1.1)
c) Write steps to create a content provider in android applications. (Refer section 5.3.1)
d) Write a program to display the following output. (Refer section 5.2)
e) Develop an application to send and receive SMS. (Write ONLY Java and permission tag in manifest file).
(Refer section 6.2.2.1)
Q.5 Attempt any TWO of the following. [12]
a) Write a program to insert data in SQLite database using AsyncTask. (Refer section 5.5.5)
b) Write a program to capture an image using camera and display it. (Refer section 5.6.1)
c) Write a program to draw a route between two locations. (Refer section 6.2.6)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development S-5 Solved Sample Papers
a) Develop an application to store student details like roll no., name, branch, marks, percentage and retrieve
student information using roll no. in SQLife database. (Refer section 5.8.2)
b) Write a program to create two screens. First screen will take one number input from user. After click on
Factorial button, second screen will open and it should display factorial of the same number. Also specify which
type of intent you will use in this case. (Refer section 5.1)
c) Develop a simple calculator using table layout. (Refer section 3.3.4)
qqq
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development S-6 Solved Sample Papers
Notes
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Books available @
MUMBAI NASHIK
Student Agencies Pvt. Ltd. Rahul Book Centre
Ph. - 022 - 40496161 / 31 Ph. - 0253 - 27424287
Vidyarthi Sales Agencies Maharashtra Pustak Bhandar
Ph. - 022 - 23829330 Ph. - 0253 - 2317506
022 - 23851416 / 23867279 New India Book House
Bharat Sales Ph. - 9623123458
Ph. - 022 - 23821307 / 7580 Anmol Pustakalaya
Ph. - 9822306289
AHMEDNAGAR Anmol Books
Ph. - 0253 - 2505501
Shripad Granth Bhandar
Ph. - 9922664979 Om Pustakalaya
Ph. - 9422246809
SANGAMNER Pragati Books & Stationers
Ph. - 7721014040
Amrut Book Stall
Ph. - 9850663354 New Om Stationers
& General Stores
NARAYANGAON Ph. - 0253 - 2378874
Shri Ganesh Book Depot
Sunil General Stores
Ph. - 9890335806
Ph. - 9850725770
Eakveera Books
KOPARGAON Ph. - 9422754746
KARAD JALGAON
Archana Bazar Parvati Traders
Ph. - 7588065287 Ph. - 9422277738
(i)
R
(ii)
R