0% found this document useful (0 votes)
110 views

Mobile Application Development New

The document discusses different types of mobile applications and mobile operating systems. It describes native apps, web apps, and hybrid apps, comparing their advantages and disadvantages. Native apps have the best performance but are more expensive to develop. Web apps can be built for all platforms but have limited functionality. Hybrid apps combine aspects of native and web apps. The document also examines the differences between native and web apps in terms of user interface, development process, accessibility, and efficiency. Finally, it provides an overview of popular mobile operating systems like Android and their version histories.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Mobile Application Development New

The document discusses different types of mobile applications and mobile operating systems. It describes native apps, web apps, and hybrid apps, comparing their advantages and disadvantages. Native apps have the best performance but are more expensive to develop. Web apps can be built for all platforms but have limited functionality. Hybrid apps combine aspects of native and web apps. The document also examines the differences between native and web apps in terms of user interface, development process, accessibility, and efficiency. Finally, it provides an overview of popular mobile operating systems like Android and their version histories.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

BWDA ARTS & SCIENCE COLLEGE

Affiliated to Thiruvalluvar University


Tindivanam (Tk), Mailam (Po), Kolliyankunam, Villupuram (Dt),
Tamil Nadu - 604304

Department of Computer
Science

E -NOTES

Class : III B. Sc Computer Science

Subject : Mobile Application Development

S. Parsuvanathan M.Sc., M.Phil Page 1


MOBILE APPLICATIONS DEVELOPMENT

UNIT I Introduction to Mobile Applications:


Native and web applications - Mobile operating systems and applications - Mobile
Databases. Android: History of Android - Android Features – OSS – OHA - Android Versions and
compatibility - Android devices - Prerequisites to learn Android -– Setting up software – IDE -
XML. Android Architecture: Android Stack - Linux Kernel - Android Runtime - Dalvik VM -
Application Framework - Android emulator - Android applications.

UNIT II Android development:


Java - Android Studio – Eclipse – Virtualization – APIs and Android tools – Debugging with
DDMS – Android File system – Working with emulator and smart devices - A Basic Android
Application - Deployment. Android Activities: The Activity Lifecycle – Lifecycle methods –
Creating Activity. Intents – Intent Filters – Activity stack.

UNIT III Android Services:


Simple services – Binding and Querying the service – Executing services.- Broadcast
Receivers: Creating and managing receivers – Receiver intents – ordered broadcasts. Content
Providers: Creating and using content providers – Content resolver. Working with databases:
SQLite – coding for SQLite using Android – Sample database applications – Data analysis.

UNIT IV Android User Interface:


Android Layouts – Attributes – Layout styles - Linear – Relative – Table – Grid – Frame.
Menus: Option menu – context menu - pop-up menu – Lists and Notifications: creation and display.
Input Controls: Buttons-Text Fields-Checkboxes-alert dialogs-Spinners-rating bar-progress bar.

UNIT V Publishing and Internationalizing mobile applications :


Live mobile application development: Game, Clock, Calendar, Convertor, Phone book. App
Deployment and Testing: Doodlz app – Tip calculator app – Weather viewer app.

Notes Prepared by
S. Parsuvanathan M.Sc., M.Phil,
Assr. Professor,
Department of Computer Science.

S. Parsuvanathan M.Sc., M.Phil Page 2


MOBILE APP DEVELOPMENT:
There are three main mobile app types you can explore for your mobile app development project:
web, native and hybrid.
1. Web App Development:
A website typically offers more information than a web app can display. A web app loads in browsers like
Chrome, Safari, or Firefox, and doesn‘t need to be downloaded from app stores like native mobile apps. Web apps also
don‘t take up storage on the user‘s device.
If your goal is to offer mobile-friendly content to a wide range of users, a web app might be the
appropriate development path.

Advantages of Web Apps


Web apps are relatively easy to maintain because they use a common code base across multiple
mobile platforms.
 Web apps can be built for all platforms as long as they can run in an appropriate web browser.
 Compared to native apps, web apps are less expensive up front.
 Web apps don‘t adhere to standard operating system protocols and don‘t require approval from the
app marketplace; they can be released at any time and in any format.
 Updates to web apps don‘t need to go through an app store meaning the user doesn‘t have to manage
updates manually. The newest version always loads when a user opens a web app.

Disadvantages of Web Apps


 Web apps have a much smaller scope when it comes to leveraging device features and hardware.
 A browser is required to run a web app.
 Web apps are slower and much less responsive than native apps.
 Web apps are less interactive and intuitive compared to native apps.

2. Native App Development


Native mobile apps are the most common type of app. They are built for specific platforms and are
written in languages that the platform accepts. For example, Swift and Objective-C for native iOS apps and
Java or Kotlin for native Android apps. Native apps are also built using the specific Integrated Development
Environment (IDE) for the selected operating systems.

Advantages of Native Apps


 Native apps deliver the best performance of all three development approaches.

S. Parsuvanathan M.Sc., M.Phil Page 3


 Native apps receive complete support from app stores and the overall app marketplace. Distribution
in app stores helps with discoverability.
 Native apps are interactive, intuitive, and run more smoothly in terms of user input and output.
 Native development allows developers to access the full feature set of the selected operating system.
 The user experience of native apps is far superior to web apps or hybrid apps. To the user, the flow is
more natural because of each mobile operating system‘s specific UI guidelines and standards.
 A native app must be approved by its respective operating system which assures quality, security,
and device compatibility.

3. Hybrid App Development


Hybrid apps work across multiple platforms and behave like native apps. A hybrid app is essentially
a combination of a native app and a web app. Although this type of app can be installed on a device like a
native app, it technically is a web app. These types of apps are built with HTML, CSS, or JavaScript and run
in a webview.
Hybrid app development is essentially a web app that incorporates additional native features. Including native
features is possible when you deploy a wrapper to act as a bridge between platforms. A hybrid app consists of two
parts:

Advantages of Hybrid App Development


 Hybrid apps don‘t need a web browser like web apps.
 Hybrid apps have access to a device‘s internal APIs and device hardware.
 Only one codebase is needed for hybrid apps.

Disadvantages of Hybrid App Development


 Hybrid apps are much slower than native apps.
 With hybrid app development, you‘re dependent on a third-party platform to deploy the app‘s
wrapper.
 The more customization the app requires takes away from hybrid development, which costs more
money that can be saved with native app development.

S. Parsuvanathan M.Sc., M.Phil Page 4


DIFFERENCE BETWEEN NATIVE AND WEB APPS
In order to know which type of app is better suited to your needs, you need to compare each one of
them. Here is a quick comparison between native apps and web apps.
1. User Interface
From the point of the mobile device user, some native and web apps look and work much the same
way, with very little difference between them. User interface to decide whether to develop a usercentric app
or an application-centric app.

2. App Development Process


Each mobile platform that the native app is developed for, stipulates its own unique development
process. In the case of web apps running on a mobile device‘s web browser, the problem that arises is that
each of these mobile devices have unique features and come with their unique problems as well.

3. Accessibility
While a native app works as a standalone entity, the problem is that the user has to keep downloading
updates. A web app, on the other hand, updates itself without the need for user intervention. However, it
necessarily needs to be accessed via a mobile device‘s browser.

4. Efficiency
Native apps are more expensive to develop. However, they are faster and more efficient, as they
work in tandem with the mobile device they are developed for. Also, they are assured of quality, as users can
access them only via app stores online.

MOBILE OPERATING SYSTEM


A mobile operating system, also called a mobile OS, is an operating system that is specifically
designed to run on mobile devices such as mobile phones, smartphones, PDAs, tablet computers and other
handheld devices.
A mobile operating system is the software platform on top of which other programs can run on
mobile devices. The operating system is responsible for determining the functions and features available on
your device, such as thumb wheel, keyboards, WAP, synchronization with applications, email, text
messaging and more. The mobile OS will also determine which third-party applications (mobile apps) can be
used on your device.

S. Parsuvanathan M.Sc., M.Phil Page 5


Types of Mobile Operating Systems
1. Android OS (Google Inc.)
The Android mobile operating system is Google's open and free software stack that includes an
operating system, middleware and also key applications for use on mobile devices, including smartphones.
Updates for the open source Android mobile operating system have been developed under "dessert-inspired"
version names. (Cupcake, Donut, Eclair, Gingerbread, Honeycomb, Ice Cream Sandwich) with each new
version arriving in alphabetical order with new enhancements and improvements.

2. BlackBerry OS (Research In Motion)


The BlackBerry OS is a proprietary mobile operating system developed by Research In Motion for
use on the company‘s popular BlackBerry handheld devices. The BlackBerry platform is popular with
corporate users as it offers synchronization with Microsoft Exchange, Lotus Domino, Novell GroupWise
email and other business software, when used with the BlackBerry Enterprise Server.

3. iPhone OS / iOS (Apple)


Apple's iPhone OS was originally developed for use on its iPhone devices. Now, the mobile
operating system is referred to as iOS and is supported on a number of Apple devices including the iPhone,
iPad, iPad 2 and iPod Touch. The iOS mobile operating system is available only on Apple's own
manufactured devices as the company does not license the OS for thirdparty hardware. Apple iOS is derived
from Apple's Mac OS X operating system.

4. Symbian OS (Nokia)
Symbian is a mobile operating system (OS) targeted at mobile phones that offers a high-level of
integration with communication and personal information management (PIM) functionality. Symbian OS
combines middleware with wireless communications through an integrated mailbox and the integration of
Java and PIM functionality (agenda and contacts). Nokia has made the Symbian platform available under an
Own Devices.

5. webOS (Palm/HP)
WebOS is a mobile operating system that runs on the Linux kernel. WebOS was initially developed
by Palm as the successor to its Palm OS mobile operating system. HP uses webOS in a number of devices
including several smartphones and HP TouchPads. HP has pushed its webOS into the enterprise mobile
market by focusing on improving security features and management with the release of webOS 3.x.

S. Parsuvanathan M.Sc., M.Phil Page 6


MOBILE DATABASES
Traditionally, large-scale commercial databases were developed as centralized database systems. The
distributed database applications involved usually a strong central database and powerful network
administration. However, the newer technology trends have changed this paradigm because of the following
technological trends:
 The notebook and laptop Computers are being used increasingly among the Business Community
 The development and availability of a relatively low-cost wireless digital communication
infrastructure. This infrastructure is based on wireless local-area networks, cellular digital packet
networks, and other technologies
The rapid advancements of wireless communication technology and computer miniaturizing technology
have enabled users to utilize computing resources anywhere in the computer network.
Some of the commercially available Mobile relational Database systems are:
 IBM's DB2 Everywhere 1.0
 Oracle Lite
 Sybase's SQL
Advantages of Mobile Databases
Some advantages of mobile databases are:
1. The data in a database can be accessed from anywhere using a mobile database. It provides wireless
database access.
2. The database systems are synchronized using mobile databases and multiple users can access the data
with seamless delivery process.
3. Mobile databases require very little support and maintenance.
4. The mobile database can be synchronized with multiple devices such as mobiles, computer devices,
laptops etc.

S. Parsuvanathan M.Sc., M.Phil Page 7


Disadvantages of Mobile Databases
Some disadvantages of mobile databases are:
1. The mobile data is less secure than data that is stored in a conventional stationary database. This
presents a security hazard.
2. The mobile unit that houses a mobile database may frequently lose power because of limited battery.
This should not lead to loss of data in database.

ANDROID
Android is an operating system and programming platform developed by Google for smartphones
and other mobile devices (such as tablets). It can run on many different devices from many different
manufacturers. Android includes a software development kit for writing original code and assembling
software modules to create apps for Android users. It also provides a marketplace to distribute apps.

Features of Android
Apps are developed for a variety of reasons: addressing business requirements, building new
services, creating new businesses, and providing games and other types of content for users. Developers
choose to develop for Android in order to reach the majority of mobile device users.
 Most popular platform for mobile apps: Android powers hundreds of millions of mobile devices
in more than 190 countries around the world. It has the largest installed base of any mobile platform
and is still growing fast.
 Best experience for app users: Android provides a touch-screen user interface (UI) for interacting
with apps. Android's user interface is mainly based on direct manipulation, using touch gestures such
as swiping, tapping and pinching to manipulate on-screen objects.
 Easy to develop apps: Use the Android software development kit (SDK) to develop apps that take
advantage of the Android operating system and UI. The SDK includes a comprehensive set of
development tools including a debugger, software libraries of prewritten code, a device emulator,
documentation, sample code, and tutorials.
 Many distribution options: You can distribute your Android app in many different ways: email,
website or an app marketplace such as Google Play. Android users download billions of apps and
games from the Google Play store
 Attractive UI - Provides beautiful Screen and Perceptive UI.
 Connectivity - CDMA,GSM/EDGE, UMTS,IDEN, EV-DO, Wi-Fi, Bluetooth, LTE and NFC.
 Storage - A light weight relational database SQLite.

S. Parsuvanathan M.Sc., M.Phil Page 8


 Media Support - MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, WAV,
JPEG, PNG, GIF, and BMP.
 Messaging - MMS and SMS.
 Web Browser - Based on the open source WebKit Maxthon web browser is one of the highest rated
browsers for Android today. Google Chrome, Mozilla Firefox, Opera,
 Multi-touch - It has native support for multi-touch.
 Multi-tasking - User can certainly move/jump from one task to another and at the same time various
application can run simultaneously.
 Resizable widgets - Widgets are resizable, so users can expand them to show more content or shrink
them to save space.
 Multi-Language - Supports single direction and bi-directional text.
 Wi-Fi Direct - A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-
peer connection.
 Android Beam - A popular NFC-based technology that lets users instantly share, just by touching
two NFC-enabled phones together.
 Hardware Support - Accelerometer Sensor, Camera, Digital Compass, Proximity Sensor, and GPS
 Tethering - Supports sharing of Internet connections as a wired/wireless hotspot.

The challenges of Android app development


While the Android platform provide rich functionality for app development, there are still a number
of challenges you need to address, such as:
 Building for a multi-screen world
 Getting performance right
 Keeping your code and your users secure
 Remaining compatible with older platform versions
 Understanding the market and the user.

History of Android
The history and versions of android are interesting to know. The code names of android ranges from
A to P currently. Let's understand the android history in a sequence.
 Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United States in
October, 2003.
 In 17th August 2005, Google acquired android Incorporation. Since then, it is in the subsidiary of
Google Incorporation.

S. Parsuvanathan M.Sc., M.Phil Page 9


 The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris White and Nick
Sears.
 Originally intended for camera but shifted to smart phones later because of low market for camera
only.
 Android is the nick name of Andy Rubin given by coworkers because of his love to robots.
 In 2007, Google announces the development of android OS.
 In 2008, HTC launched the first android mobile.

OSS – Open Source Software:


Android offers a unified approach to application development for mobile devices which means
developers need only develop for Android, and their applications should be able to run on different devices
powered by Android.

OHA – Open Handset Alliance:


OHA or open handset alliance is a consortium of 84 companies such as google, Lenovo, Samsung,
HTC, AKM, LG, synaptics, ebay, KDDI, wipro, Garmin, Dell, Teleca, sony Intel etc.
It was established on 5th November, 2007, led by Google. It is committed to advance open standards,
provide services and deploy handsets using the Android Platform.

Android Versions and Compatibility


1. Android 9 – Pie (API – 28)

 User interface updates:


o Rounded corners across the UI
o Notification bar, the clock has moved to the left.
o The "dock" now has a semi-transparent background.
o Volume slider updated
 Richer messaging notifications: with full conversation, large images, smart replies
 The power options now has a "screenshot" button

2. Android 8 and 8.1 – Oreo (API – 26, 27)

 Show battery level in "Quick Settings" for devices connected via Bluetooth
 Navigation buttons dim when not in use
 UI updates to 'Power Off' and 'Restart'
 Toast messages are now white in color with same existing transparency

S. Parsuvanathan M.Sc., M.Phil Page 10


 Automatic light and dark themes
 Emoji updates (ie: Hamburger move the cheese slice position)

3. Android 7, 7.1, 7.1.1 and 7.1.2 – Nougat (API – 24, 25)

 Daydream Virtual Reality mode


 Night Light
 Storage manager improvements
 Performance improvements for Touch and Display managements
 Option to enable fingerprint swipe down gesture
 Seamless system updates

4. Android 6 and 6.0.1 – Marshmallow (API – 23)

 USB Type-C support


 Fingerprint Authentication support
 Better battery life with "deep sleep"
 MIDI support
 Google Now improvements

5. Android 5, 5.0.1, 5.0.2, 5.1 and 5.1.1 – Lollipop (API – 21, 22)

 Multiple SIM cards support


 Quick settings shortcuts to join Wi-Fi networks or control Bluetooth devices
 Lock protection if lost or stolen
 High Definition voice call
 Stability and performance enhancements

6. Android 4.4, 4.4.1 – 4.4.4 and – Lollipop (API – 19)

 Screen recording
 Enhanced notification access
 System-wide settings for closed captioning
 Performance improvements

7. Android 4.2 and 4.3 – Jelly Bean (API – 16, 17 ,18)

 Dial pad auto-complete


 Camera app UI updated

S. Parsuvanathan M.Sc., M.Phil Page 11


 4K resolution support
 Hebrew and Arabic right-to-left (RTL) support
 Bluetooth Low Energy (BLE) support
 Bluetooth Audio/Video Remote Control Profile (AVRCP) 1.3 support
 Security and performance enhancements

8. Android 4.0, 4.0.1 – 4.0.4 and 4.3 – Ice Cream Sandwich (API – 14, 15)

 Facial recognition (Face Unlock)


 UI use Hardware acceleration
 Better voice recognition (dictating/Voice typing)
 Web browser, allows up to 16 tabs
 Updated launcher (customizable)
 Android Beam app to exchange data through NFC

9. Android 3.0 – 3.2.6 – Honeycomb (API – 11, 12, 13)

 UI improvements
 USB host API
 Mice, joysticks, gamepads... support
 Resizable Home screen widgets
 MTP notifications

10. Android 2.3 – 2.3.7 – Gingerbread (API – 9, 10)

 Updated UI
 Improved keyboard ease of use
 Improved copy/paste
 Improved power management
 Social networking features
 Near Field Communication support
 Native VoIP/SIP support
 Video call support

11. Android 2.2 – Froyo (API – 8)

 Speed improvements
 USB Tethering
 Applications installation to the expandable memory

S. Parsuvanathan M.Sc., M.Phil Page 12


 Upload file support in the browser
 Animated GIFs

12. Android 2.0 and 2.1 – Eclair (API – 5, 6, 7)

 HTML
 Digital zoom
 Microsoft Exchange support
 Bluetooth 2.1
 Live Wallpapers
 Updated UI

13. Android 1.0 – 1.6 – Apple Pie, Bananabread, Cupcake, Donut (API – 1, 2, 3, 4)

 Download and updates via Android Market


 Web Browser
 Camera support
 Gmail, Contacts and Google Agenda synchronization
 Google Maps
 YouTube application

Android Devices
An Android device is a device that runs on the Android operating system. Android is an array of
software intended for mobile devices that features an operating system, core applications and middleware.
An Android device may be a smartphone, tablet PC, e-book reader or any type of mobile device that requires
an OS.

Android is developed by the Open Handset Alliance, which is led by Google. Some of the well-
known Android device manufacturers include Acer, HTC, Samsung, LG, Sony Ericsson and Motorola.

Popular Android devices include smartphones, tablets and e-readers. The Android OS is also built
into a limited number of other devices, such as netbooks, portable music players, the Binatone iHome Phone
and Odroid handheld game consoles.

Within a short period, the Android platform became so popular that it surpassed Windows Mobile
and Symbian for a number of applications. The reasons behind this success are as follows:

 Cutting-edge technology offered by Google


 Extremely user friendly platform
 Can be used in smartphones as well as tablets
 Any user can do modifications to the platform as the Android SDK is open to users
 Availability of huge volume of applications

S. Parsuvanathan M.Sc., M.Phil Page 13


Prerequisites for Learning Android Development
 Java Object oriented concepts
 Java Basics [Tokens]
 Type casting and Visibility
 Arrays and Operators
 Control Statements
 Class Fundamentals
 Inheritance, Interface and package
 Multithreading and Exception Handling
 Java Annotations and IO
 Generics and Collection Classes

Setting up software
System Requirements

We can start your Android application development on either of the following operating systems −

 Microsoft® Windows® 10/8/7/Vista/2003 (32 or 64-bit)


 Mac® OS X® 10.8.5 or higher, up to 10.9 (Mavericks)
Second point is that all the required tools to develop Android applications are open source and can be
downloaded from the Web. Following is the list of software's you will need before you start your Android
application programming.
 Java JDK5 or later version

 Java Runtime Environment (JRE) 6


 Android Studio

Setup Android Studio


So let's launch Android Studio.exe,Make sure before launch Android Studio, Our Machine should
required installed Java JDK. To install Java JDK,take a references of

S. Parsuvanathan M.Sc., M.Phil Page 14


Once you launched Android Studio, its time to mention JDK7 path or later version in android studio
installer.

Below the image initiating JDK to android SDK

Need to check the components, which are required to create applications, below the image has
selected Android Studio, Android SDK, Android Virtual Machine and performance(Intel chip).

S. Parsuvanathan M.Sc., M.Phil Page 15


Need to specify the location of local machine path for Android studio and Android SDK, below the image
has taken default location of windows 8.1 x64 bit architecture.

Need to specify the ram space for Android emulator by default it would take 512MB of local machine RAM.

At final stage, it would extract SDK packages into our local machine, it would take a while time to finish the
task and would take 2626MB of Hard disk space.

S. Parsuvanathan M.Sc., M.Phil Page 16


Andriod IDE
Android Studio is the official Integrated Development Environment (IDE) for Android app development,
based on IntelliJ IDEA . On top of IntelliJ's powerful code editor and developer tools, Android Studio offers
even more features that enhance your productivity when building Android apps, such as:

 A flexible Gradle-based build system


 A fast and feature-rich emulator
 A unified environment where you can develop for all Android devices
 Instant Run to push changes to your running app without building a new APK
 Extensive testing tools and frameworks
 Lint tools to catch performance, usability, version compatibility, and other problems
 C++ and NDK support

1. The toolbar lets you carry out a wide range of actions, including running your app and launching
Android tools.
2. The navigation bar helps you navigate through your project and open files for editing. It provides a
more compact view of the structure visible in the Project window.

S. Parsuvanathan M.Sc., M.Phil Page 17


3. The editor window is where you create and modify code. Depending on the current file type, the
editor can change. For example, when viewing a layout file, the editor displays the Layout Editor.
4. The tool window bar runs around the outside of the IDE window and contains the buttons that allow
you to expand or collapse individual tool windows.
5. The tool windows give you access to specific tasks like project management, search, version control,
and more. You can expand them and collapse them.
6. The status bar displays the status of your project and the IDE itself, as well as any warnings or
messages.
You can organize the main window to give yourself more screen space by hiding or moving toolbars and
tool windows. You can also use keyboard shortcuts to access most IDE features.
At any time, you can search across your source code, databases, actions, elements of the user interface,
and so on, by double-pressing the Shift key, or clicking the magnifying glass in the upper right-hand corner
of the Android Studio window. This can be very useful if, for example, you are trying to locate a particular
IDE action that you have forgotten how to trigger.

Android Architecture

1. Linux kernel
At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This provides a
level of abstraction between the device hardware and it contains all the essential hardware drivers like
camera, keypad, display etc. Also, the kernel handles all the things that Linux is really good at such as
networking and a vast array of device drivers, which take the pain out of interfacing to peripheral hardware.

S. Parsuvanathan M.Sc., M.Phil Page 18


2. Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit,
well known library libc, SQLite database which is a useful repository for storage and sharing of application
data, libraries to play and record audio and video, SSL libraries responsible for Internet security etc.

3. Android Libraries
This category encompasses those Java-based libraries that are specific to Android development.
Examples of libraries in this category include the application framework libraries in addition to those that
facilitate user interface building, graphics drawing and database access. A summary of some key core
Android libraries available to the Android developer is as follows −
 android.app − Provides access to the application model and is the cornerstone of all Android
applications.
 android.content − Facilitates content access, publishing and messaging between applications and
application components.
 android.database − Used to access data published by content providers and includes SQLite
database management classes.
 android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API.
 android.os − Provides applications with access to standard operating system services including
messages, system services and inter-process communication.
 android.text − Used to render and manipulate text on a device display.
 android.view − The fundamental building blocks of application user interfaces.
 android.widget − A rich collection of pre-built user interface components such as buttons, labels, list
views, layout managers, radio buttons etc.
 android.webkit − A set of classes intended to allow web-browsing capabilities to be built into
applications.
Having covered the Java-based core libraries in the Android runtime, it is now time to turn our attention to
the C/C++ based libraries contained in this layer of the Android software stack.

4. Android Runtime
This is the third section of the architecture and available on the second layer from the bottom. This
section provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine
specially designed and optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and multi-threading,
which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own
process, with its own instance of the Dalvik virtual machine.

S. Parsuvanathan M.Sc., M.Phil Page 19


The Android runtime also provides a set of core libraries which enable Android application
developers to write Android applications using standard Java programming language.

5. Application Framework
The Application Framework layer provides many higher-level services to applications in the form of
Java classes. Application developers are allowed to make use of these services in their applications.
The Android framework includes the following key services −
 Activity Manager − Controls all aspects of the application lifecycle and activity stack.
 Content Providers − Allows applications to publish and share data with other applications.
 Resource Manager − Provides access to non-code embedded resources such as strings, color
settings and user interface layouts.
 Notifications Manager − Allows applications to display alerts and notifications to the user.
 View System − An extensible set of views used to create application user interfaces.

6. Applications
You will find all the Android application at the top layer. You will write your application to be
installed on this layer only. Examples of such applications are Contacts Books, Browser, Games etc.

7. Android Emulator
The Android SDK includes a virtual mobile device emulator that runs on your computer. The
emulator lets you prototype, develop and test Android applications without using a physical device.
If you want to emulate a real device, first crate an AVD with the same device configurations as real
device, then launch this AVD from AVD manager.
Usually by default when you launch the emulator, its orientation is vertical,
but you can change it orientation by pressing Ctrl+F11 key from keyboard.
Home - Shifts to main screen

F2 - Toggles context sensitive menu

F3 - Bring out call log

F4 - End call

F5 - Search

F7 - Power button

F8 - Toggle data network

Ctrl+F5 - Ring Volume up Ctrl+F6 - Ring Volume down

S. Parsuvanathan M.Sc., M.Phil Page 20


UNIT - II

Java:
Android applications are developed using the Java language. Java is a very popular programming
language developed by Sun Microsystems (now owned by Oracle). Developed long after C and C++, Java
incorporates many of the powerful features of those powerful languages while addressing some of their
drawbacks. Still, programming languages are only as powerful as their libraries. These libraries exist to help
developers build applications.

Some of the Java‘s important core features are:

 It‘s easy to learn and understand

 It‘s designed to be platform-independent and secure, using virtual machines

 It‘s object-oriented

Android relies heavily on these Java fundamentals. The Android SDK includes many standard Java
libraries (data structure libraries, math libraries, graphics libraries, networking libraries and everything else
you could want) as well as special Android libraries that will help you develop awesome Android
applications.

Java is Platform Independence:

With many programming languages, you need to use a compiler to reduce your code down into
machine language that the device can understand. The Java compilers convert your code from human
readable Java source files to something called ―bytecode‖ in the Java world. These are interpreted by a Java
Virtual Machine, which operates much like a physical CPU might operate on machine code, to actually
execute the compiled code.

Android applications run in a special virtual machine called the Dalvik VM. It can allowing you to
not have to worry about whether the device is a Motorola or HTC, or the latest toaster running Android. You
don‘t care so long as the device is Dalvik VM friendly

Java is Secure:

A virtual machine can encapsulate, contain, and manage code execution in a safe manner compared
to languages that operate in machine code directly. Each Android application runs on the (Linux-based)
operating system using a different user account and in its own instance of the Dalvik VM. Android
applications are closely monitored by the operating system and shut down if they don‘t play nice. Therefore,
it‘s important to develop applications that are stable and responsive.

Java is an Object Oriented Programming Language:

OOP is a programming style or technique that relies upon the definition of data structures called
objects. For those new to OOP, an object can be thought of much like a custom data type.

A class typically describes the data and behaviour of an object. The behaviour is defined using
class methods. Method is the common term for a subroutine in an OOP language. Many common object
classes are defined in shared class libraries like software development kits (SDKs), whereas others are
S. Parsuvanathan M.Sc., M.Phil Page 21
defined by you, the developer, for your own purposes. Software is then built up by using and manipulating
object instances in different ways.

Organizing Classes and Interfaces with Packages

Class hierarchies, such as our fish classes, can then be organized into packages. A package is simply
a set of classes and interfaces, bundled together. Developers use namespaces to uniquely name packages.

Introducing to Android Studio


Android is one of the most popular mobile device platforms. The Android platform allows
developers to write managed code using Java to manage and control the Android device. Android Studio is a
popular IDE developed by Google for developing applications that are targeted at the Android platform.
Note that Android Studio has replaced Eclipse as the IDE of choice for developing Android applications.

Android Studio contains tools such as the Android Virtual Device Manager and the Android Device
Monitor. It also contains Gradle, which helps you configure your Android application seamlessly. Some of
the interesting features of Android Studio include the following:

 Support for a fast emulator


 Support for Gradle
 Support for Google Cloud Platform
 Support for template-based wizards for creating Android designs and components
 Support for rich layout editor
 Support for deep code analysis

Creating an Android Application Using Android Studio

We will explore how we can create a simple application using Android Studio in the section. Android
applications are based on the Java programming language and make extensive use of XML. To create an
Android application using Android Studio, follow these simple steps:

1. Start Android Studio in your system.


2. Click "Start a new Android Studio project," as shown in Figure 1.

S. Parsuvanathan M.Sc., M.Phil Page 22


3. In the "New Project" dialog that pops up next, specify the application name and company domain.

1. Click Next to proceed.


2. In the next screen, "Select the form factor your app will run on", check "Phone and Tablet."

1. Specify the SDK version you want to use.


2. Click Next.
3. In the next screen, "Add an activity to Mobile", select "Empty Activity."

S. Parsuvanathan M.Sc., M.Phil Page 23


9. Click Next.
10. In the next screen, "Customize the Activity," specify the activity and layout name.
11. Click Finish when done.
That's all you need to do for now. Please be patient for a while because it would take some time for the
project to be loaded. After a while, your first Android application will be created—default though, because it
doesn't have any custom code.

Eclipse
Eclipse is a IDE for Android Development, a multi-language software development environment
featuring an extensible plug-in system. It can be used to develop various types of applications, using
languages such as Java, Ada, C, C++, COBOL, Python, and others.
For Android development, you should download the Eclipse IDE for Java EE Developers
(www.eclipse.org/downloads/). Six editions are available: Windows (32- and 64-bit), Mac OS X (Cocoa 32-
and 64), and Linux (32- and 64-bit). Simply select the relevant one for your operating system.
Once the Eclipse IDE is downloaded, unzip its content (the eclipse folder) into a folder, say
C:\Android 4.0\. Figure 1-14 shows the content of the eclipse folder. To launch Eclipse, double-click on the
eclipse.exe fi le. You are fi rst asked to specify your workspace. In Eclipse, a workspace is a folder where
you store all your projects. Take the default suggested (or you can specify your own folder as the workspace)
and click OK.

Android Development Tools (ADT)


The ADT is an extension to the IDE that supports the creation and debugging of Android
applications. Using the ADT, you will be able to do the following
 Create new Android application projects.
 Access the tools for accessing your Android emulators and devices.
 Compile and debug Android applications.
 Export Android applications into Android Packages (APKs).
 Create digital certificates for code-signing your APK.
In the Install dialog that appears, specify https://dl-ssl.google.com/android/eclipse/ and press Enter. After
a while, you will see the Developer Tools item appear in the middle of the window (see Figure 1-16).
Expand it to reveal its content: Android DDMS, Android Development Tools, Android Hierarchy Viewer,
and Android Traceview. Check all of them and click Next twice.

S. Parsuvanathan M.Sc., M.Phil Page 24


You will be asked to review and accept the licenses. Check the ―I accept the terms of the license
agreements‖ option and click Finish. Once the installation is completed, you will be asked to restart IDE.
When IDE is restarted, you are asked to configure your Android SDK (see Figure 1-17). As the Android
SDK has already been downloaded earlier in the previous section, check the ―Use existing SDKs‖ option and
specify the directory where you have installed the Android SDK. Click Next. Once you have selected your
choice, click Finish.

Virtualization:
The Android Virtual Device Manager allows you to create Android Virtual Devices (AVDs), which
you can then run to emulate a device on your computer. There‘s an important but subtle distinction between
simulation and emulation. Simulation means that the virtual device is merely a façade that simulates how an
actual physical device might behave, but does not run the targeted operating system. The iOS development
environment uses simulation.

With emulation, however, your computer sets aside a block of memory to reproduce the environment
found on the device that the emulator is emulating. Android Studio uses emulation, which means the
Android Virtual Device Manager launches a sandboxed version of the Linux kernel and the entire Android
stack in order to emulate the environment found on the physical Android device. Although emulation
provides a much more faithful environment on which to test your apps than simulation does, booting up an
AVD can drag into the minutes, depending on the speed of your computer.

That said, let‘s first set up an AVD using the Android Virtual Device Manager.

 Click the Android Virtual Device Manager icon encircled in Figure 1-25. On the first screen of the
Andriod Virtual Device Manager Wizard, click the Create Virtual Device button.

S. Parsuvanathan M.Sc., M.Phil Page 25


 On the next screen, shown in Figure 1-26, choose Galaxy Nexus and click Next. The next screen,
shown in Figure 1-27, allows you to select a system image. Select the first option for Lollipop (or the
latest API) with an ABI of x86_64. Click Next.

 On the next screen, click the Finish button to verify your AVD settings. Congratulations, you just
created a new AVD.

S. Parsuvanathan M.Sc., M.Phil Page 26


DEBUGGING WITH DDMS

Android ships with a debugging tool called the Dalvik Debug Monitor Service (DDMS), which
provides port-forwarding services, screen capture on the device, thread and heap information on the device,
logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and
more.

DDMS ships in the tools/ directory of the SDK. Enter this directory from a terminal/console and type
ddms (or ./ddms on Mac/Linux) to run it. DDMS will work with both the emulator and a connected device.
If both are connected and running simultaneously, DDMS defaults to the emulator.

How DDMS works

DDMS acts as a middleman to connect the IDE to the applications running on the device. When it
starts, DDMS connects to adb and starts a device monitoring service between the two, which will notify
DDMS when a device is connected or disconnected.

 When a device is connected, a VM monitoring service is created between adb and DDMS, which will
notify DDMS when a VM on the device is started or terminated.
 Once a VM is running, DDMS retrieves the the VM's process ID (pid), via adb, and opens a
connection to the VM's debugger, through the adb daemon (adbd) on the device.
 DDMS can now talk to the VM using a custom wire protocol.

Left Pane

The left side of the Debug Monitor shows each emulator/device currently found, with a list of all the
VMs currently running within each. VMs are identified by the package name of the application it hosts.

Right pane

On the right side, the Debug Monitor provides tabs that display useful information and some pretty
cool tools.

Info

This view shows some general information about the selected VM, including the process ID, package name,
and VM version.

S. Parsuvanathan M.Sc., M.Phil Page 27


Threads

The threads view has a list of threads running in the process of the target VM. To reduce the amount
of data sent over the wire, the thread updates are only sent when explicitly enabled by toggling the "threads"
button in the toolbar. This toggle is maintained per VM. This tab includes the following information:

 ID - a VM-assigned unique thread ID. In Dalvik, these are odd numbers starting from 3.
 Tid - the Linux thread ID. For the main thread in a process, this will match the process ID.
 Status - the VM thread status. Daemon threads are shown with an asterisk (*). This will be one of the
following:
 running - executing application code
 sleeping - called Thread.sleep()
 monitor - waiting to acquire a monitor lock
 wait - in Object.wait()
 native - executing native code
 vmwait - waiting on a VM resource
 zombie - thread is in the process of dying
 init - thread is initializing (you shouldn't see this)
 starting - thread is about to start (you shouldn't see this either)
 utime - cumulative time spent executing user code, in "jiffies" (usually 10ms). Only available under
Linux.
 stime - cumulative time spent executing system code, in "jiffies" (usually 10ms).
 Name - the name of the thread

Emulator Control

With these controls, you can simulate special device states and activities. Features include:

 Telephony Status - change the state of the phone's Voice and Data plans (home, roaming, searching,
etc.), and simulate different kinds of network Speed and Latency (GPRS, EDGE, UTMS, etc.).
 Telephony Actions - perform simulated phone calls and SMS messages to the emulator.
 Location Controls - send mock location data to the emulator so that you can perform location-aware
operations like GPS mapping.
 To use the Location Controls, launch your application in the Android emulator and open DDMS.
Click the Emulator Controls tab and scroll down to Location Controls. From here, you can:

S. Parsuvanathan M.Sc., M.Phil Page 28


 Manually send individual longitude/latitude coordinates to the device.
 Click Manual, select the coordinate format, fill in the fields and click Send.

Android File system


Now that you have created your fi rst Hello World Android application, it is time to dissect the innards of the
Android project and examine all the parts that make everything work. First, note the various fi les that make
up an Android project in the Package Explorer in Eclipse (see Figure 1-35).

The various folders and their files are as follows:

 src — Contains the .java source files for your project. In this example, there is one fi le,
HelloWorldActivity.java. The HelloWorldActivity.java file is the source fi le for your activity. You
write the code for your application in this file.
 gen — Contains the R.java fi le, a compiler-generated file that references all the resources found in
your project. You should not modify this file. All the resources in your project are automatically
compiled into this class so that you can refer to them using the class.
 Android library — This item contains one file, android.jar, which contains all the class libraries
needed for an Android application.
 assets — This folder contains all the assets used by your application, such as HTML, text files,
databases, etc.
 bin — This folder contains the files built by the ADT during the build process. In particular, it
generates the .apk file (Android Package). An .apk file is the application binary of an Android
application. It contains everything needed to run an Android application.
 res — This folder contains all the resources used in your application. It also contains a few other
subfolders: drawable-<resolution>, layout, and values.
 AndroidManifest.xml — This is the manifest file for your Android application. Here you specify
the permissions needed by your application, as well as other features.

The AndroidManifest.xml fi le contains detailed information about the application:

 It defines the package name of the application as net.learn2develop.HelloWorld.


 The version code of the application is 1 (set via the android:versionCode attribute). This value is used
to identify the version number of your application. It can be used to programmatically determine
whether an application needs to be upgraded.
 The version name of the application is 1.0 (set via the android:versionName attribute). This string
value is mainly used for display to the user. You should use the format <major>.<minor>.<point>
for this value.

S. Parsuvanathan M.Sc., M.Phil Page 29


 The android:minSdkVersion attribute of the <uses-sdk> element specifi es the minimum version of
the OS on which the application will run.
 The application uses the image named ic_launcher.png located in the drawable folders.
 The name of this application is the string named app_name defined in the strings.xml file.
 There is one activity in the application represented by the HelloWorldActivity.java file.
 The label displayed for this activity is the same as the application name.

Android Emulator:

The Android emulator is an application that provides a virtual mobile device on which you can run
your Android applications. It runs a full Android system stack, down to the kernel level, that includes a set
of preinstalled applications that you can access from your applications. You can choose what version of the
Android system you want to run in the emulator by configuring AVDs, and you can also customize the
mobile device skin and key mappings.

When launching the emulator and at runtime, you can use a variety of commands and options to
control its behavior. The Android system images available through the Android SDK Manager contain code
for the Android Linux kernel, the native libraries, the Dalvik VM, and the various Android packages. The
emulator provides dynamic binary translation of device machine code to the OS and processor architecture
of your development machine.

Android Virtual Devices and the Emulator

To use the emulator, you first must create one or more AVD configurations. In each
configuration, you specify an Android platform to run in the emulator and the set of hardware
options and emulator skin you want to use. Then, when you launch the emulator, you specify the
AVD configuration that you want to load.

Each AVD functions as an independent device, with its own private storage for user data, SD
card, and so on. When you launch the emulator with an AVD configuration, it automatically loads
the user data and SD card data from the AVD directory. By default, the emulator stores the user
data, SD card data, and cache in the AVD directory.

S. Parsuvanathan M.Sc., M.Phil Page 30


Starting and Stopping the Emulator

During development and testing of your application, you install and run your application in the
Android emulator. You can launch the emulator as a standalone application from a command line, or you
can run it from within your Eclipse development environment. In either case, you specify the AVD
configuration to load and any start up options you want to use.

Activities
An application can have zero or more activities. Typically, applications have one or more activities;
and the main purpose of an activity is to interact with the user. From the moment an activity appears on the
screen to the moment it is hidden, it goes through a number of stages, known as an activity‘s life cycle.
Think of fragments as ―miniature‖ activities that can be grouped to form an activity. Apart from
activities, another unique concept in Android is that of an intent. An intent is basically the ―glue‖ that
enables different activities from different applications to work together seamlessly, ensuring that tasks can
be performed as though they all belong to one single application.

Lifecycle:

The Activity base class defi nes a series of events that govern the life cycle of an activity. The
Activity class defines the following events:

 onCreate() — Called when the activity is first created


 onStart() — Called when the activity becomes visible to the user
 onResume() — Called when the activity starts interacting with the user
 onPause() — Called when the current activity is being paused and the previous activity is being
resumed
 onStop() — Called when the activity is no longer visible to the user
 onDestroy() — Called before the activity is destroyed by the
 onRestart() — Called when the activity has been stopped and is restarting again

S. Parsuvanathan M.Sc., M.Phil Page 31


Understanding the Lifecycle:

An activity is destroyed when you click the Back button. This is crucial to know, as whatever state
the activity is currently in will be lost; hence, you need to write additional code in your activity to preserve
its state when it is destroyed. At this point, note that the onPause() method is called in both scenarios when
an activity is sent to the background, as well as when it is killed when the user presses the Back button.

When an activity is started, the onStart() and onResume()methods are always called, regardless of
whether the activity is restored from the background or newly created. When an activity is created for the
first time, the onCreate() method is called.

From the preceding example, you can derive the following guidelines:

 Use the onCreate() method to create and instantiate the objects that you will be using in your
application.
 Use the onResume() method to start any services or code that needs to run while your activity is in
the foreground.

S. Parsuvanathan M.Sc., M.Phil Page 32


 Use the onPause() method to stop any services or code that does not need to run when your activity is
not in the foreground.
 Use the onDestroy() method to free up resources before your activity is destroyed.

Creating Activities:

1. Using Android Studio, create a new Android project and name it Activity101.

2. In the Activity101Activity.java fi le, add the following statements in bold:

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class Activity101Activity extends Activity {
String tag = “Lifecycle”;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(tag, “In the onCreate() event”);
}
public void onStart()
{
super.onStart();
Log.d(tag, “In the onStart() event”);
}
public void onRestart()
{
super.onRestart();
Log.d(tag, “In the onRestart() event”);
}
public void onResume()
{
super.onResume();
Log.d(tag, “In the onResume() event”);
}
public void onPause()
{
super.onPause();
Log.d(tag, “In the onPause() event”);
}
public void onStop()
{
super.onStop();

S. Parsuvanathan M.Sc., M.Phil Page 33


Log.d(tag, “In the onStop() event”);
}
public void onDestroy()
{
super.onDestroy();
Log.d(tag, “In the onDestroy() event”);
}
}
3. Press F11 to debug the application on the Android emulator.
4. When the activity is first loaded, you should see something very similar to the following in the LogCat
window

5. If you click the Back button on the Android emulator, the following is printed:

11-16 06:29:26.665: D/Lifecycle(559): In the onPause() event


11-16 06:29:28.465: D/Lifecycle(559): In the onStop() event
11-16 06:29:28.465: D/Lifecycle(559): In the onDestroy() event

6. Click the Home button and hold it there. Click the Activities icon and observe the following:

11-16 06:31:08.905: D/Lifecycle(559): In the onCreate() event


11-16 06:31:08.905: D/Lifecycle(559): In the onStart() event
11-16 06:31:08.925: D/Lifecycle(559): In the onResume() event

7. Click the Phone button on the Android emulator so that the activity is pushed to the background.
Observe the output in the LogCat window:

11-16 06:32:00.585: D/Lifecycle(559): In the onPause() event


11-16 06:32:05.015: D/Lifecycle(559): In the onStop() event

8. Notice that the onDestroy() event is not called, indicating that the activity is still in memory. Exit the
phone dialer by clicking the Back button. The activity is now visible again. Observe the output in the LogCat
window:
11-16 06:32:50.515: D/Lifecycle(559): In the onRestart() event
11-16 06:32:50.515: D/Lifecycle(559): In the onStart() event
11-16 06:32:50.515: D/Lifecycle(559): In the onResume() event
The onRestart() event is now fi red, followed by the onStart() and onResume() methods.

S. Parsuvanathan M.Sc., M.Phil Page 34


INTENTS
Intents are used as a message-passing mechanism that works both within your application and
between applications. We can use Intents to do the following:

 Explicitly start a particular Service or Activity using its class name


 Start an Activity or Service to perform an action with (or on) a particular piece of data
 Broadcast that an event has occurred

One of the most common uses for Intents is to start new Activities, either explicitly (by specifying the
class to load) or implicitly (by requesting that an action be performed on a piece of data). In the latter case
the action does not need to be performed by an Activity within the calling application.

Explicitly Starting New Activities:

An applications consist of a number of interrelated Activities ,that must be included in the


application manifest. To transition between them, you will often need to explicitly specify which Activity to
open.

To select a specific Activity class to start, create a new Intent, specifying the current Activity‘s
Context and the class of the Activity to launch. Pass this Intent into startActivity,

Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);

startActivity(intent);

After startActivity is called, the new Activity will be created, started, and resumed moving to the top
of the Activity stack. Calling finish on the new Activity, or pressing the hardware back button, closes it and
removes it from the stack. Alternatively, you can continue to navigate to other Activities by calling
startActivity. Note that each time you call startActivity, a new Activity will be added to the stack; pressing
back (or calling finish) will remove each of these Activities, in turn.

Implicit Intents and Late Runtime Binding

An implicit Intent is a mechanism that lets anonymous application components service action
requests. That means you can ask the system to start an Activity to perform an action without knowing
which application, or Activity, will be started.

For example, to let users make calls from your application, you could implement a new dialer, or you
could use an implicit Intent that requests the action (dialing) be performed on a phone

S. Parsuvanathan M.Sc., M.Phil Page 35


if (somethingWeird && itDontLookGood)
{
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(―tel: 9629490090‖));
startActivity(intent);
}
Android resolves this Intent and starts an Activity that provides the dial action on a telephone number
in this case, typically the Phone Dialer. When constructing a new implicit Intent, you specify an action to
perform and, optionally, supply the URI of the data on which to perform that action. You can send additional
data to the target Activity by adding extras to the Intent.

INTENT FILTER:

In android, Intent Filter is an expression in app‘s manifest file (ActivityMainfest.xml) and it is


used to specify the type of intents that the component would like to receive. In case if we create Intent
Filter for an activity, there is a possibility for other apps to start our activity by sending a certain type of
intent otherwise the activity can be started only by an explicit intent.

Generally, the Intent Filters (<intent-filter>) whatever we define in manifest file can be nested in the
corresponding app components and we can specify the type of intents to accept using these three elements.

 <action> - It defines the name of an intent action to be accepted and it must be a literal string value
of an action, not the class constant.
 <category> - It defines the name of an intent category to be accepted and it must be the literal string
value of an action, not the class constant.
 <data> - It defines the type of data to be accepted and by using one or more attributes we can specify
various aspects of the data URI (scheme, host, port, path) and MIME type.

Intent Filter in Manifest File

Following is the code snippet of defining an activity with Intent Filter (<intent-filter>) in Android
Manifest file (AndroidManifest.xml) like as shown below.

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

S. Parsuvanathan M.Sc., M.Phil Page 36


 MAIN - It indicates the app‘s main entry point that means it starts the activity which defines
with MAIN action when the user initially launches the app with launcher icon.
 LAUNCHER - It indicates that this activity icon should be placed in the home screen list of apps. In
case if the <activity>element doesn‘t specify an icon with icon, then the system uses the icon from
the <application> element.
These two (MAIN, LAUNCHER) elements must be paired together in order for the activity to
appear in the app launcher.
Android Intent Filters Example
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/sendMail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="150dp"
android:layout_marginTop="230dp"
android:text="Send Mail" />
</LinearLayout>

Mainactivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity


{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

S. Parsuvanathan M.Sc., M.Phil Page 37


Button btnSend = (Button)findViewById(R.id.sendMail);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent si = new Intent(Intent.ACTION_SEND);
si.setType("message/rfc822");
si.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
si.putExtra(Intent.EXTRA_SUBJECT, "Welcome to Parsu Android");
si.putExtra(Intent.EXTRA_TEXT, "Hi Guest, Welcome to Parsu Android Tutorial Site");
startActivity(Intent.createChooser(si,"Choose Mail App"));
}
});
}
}

Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.intentfilters">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="message/rfc822"/>
</intent-filter>

S. Parsuvanathan M.Sc., M.Phil Page 38


</activity>
</application>
</manifest>

Output:

S. Parsuvanathan M.Sc., M.Phil Page 39


ANDROID STACK:
Android Activities are the logical construct of the screens that we want a user to navigate through.
The relation that each Activity holds with respect to other is very crucial for a good user experience. One of
the most important aspects of achieving the above is to design a proper forward and backward navigations.
The Android design already has taken a very good care of providing a smooth user experience in terms of
managing the screen flows.

A Task holds the Activities, arranged in a Stack called Android Stack. The Stack has LIFO structure
and stores the activities in the order of their opening. The Activities in the Stack are never rearranged. The
navigation of the back stack is done with the help of the Back button.

Behaviours of Android Stack


1. The application launcher creates a new Task with the main Activity created and placed in the root of
the Android stack (It has another role that we will review later).

2. When the current Activity starts another Activity, then the new Activity is pushed on top of the stack
and takes focus.

3. The previous Activity moves below this new Activity in the back stack and is stopped. The system
retains the current state of this Activity‘s user interfaces like text in the form, scroll position etc.

4. The subsequent new Activities keep on piling the back stack.

5. When the Back button is pressed then the current Activity is popped from the top of the back stack.
This destroys the Activity and the previous Activity resumes with its state restored.

6. The Back button then keeps on popping the current Activities and restoring the previous activities.
When the last Activity is removed from the back stack, then the Task terminates to the screen that
was last running before the creation of the Task (in our case the launcher screen).

7. When the back stack goes empty then the Task ceased to exist.

S. Parsuvanathan M.Sc., M.Phil Page 40


8. Activities of different applications invoked by the intent are put into the same Task.

Properties of Android Stack

1. It goes into the background when a new task is created or when the Home button is pressed.

2. It is then brought to the foreground by clicking the launcher icon (this is the another role of the
launcher icon that we mentioned earlier) or by selecting the task from the recent screens.

3. When multiple tasks are in the background or when the user leaves the Task for a long time, the
system in order to recover memory clears the Task of all the Activities except the root Activity.
When the user returns to the Task again, only the root Activity is restored (this behavior can be
overridden as we will see later).

Launch Mode:

The launchModes and its equivalent startActivity Flags allow us to define, how a new instance of an
Activity is associated with the current Task and specifies the instruction for its launch in the given Task. The
types of launchModes and its equivalent startActivity Flags are presented and investigated in the following
points

launchMode — standard: This is the default mode of the Activity. In this mode, a new instance of the
Activity is created and put in the Task which started it by routing the intent to it.

launchMode — singleTop | flag — FLAG_ACTIVITY_SINGLE_TOP: This mode or flag produces


exactly the same behavior as the standard launchMode if the new Activity in not already present in the back
stack as the top. If it is present at the top then it behaves differently.

launchMode — singleTask | flag — FLAG_ACTIVITY_NEW_TASK: If an Activity do not exist in an


already created Task, then it starts the Activity in a new Task with Activity‘s new instance at the root of the
Task‘s back stack, else the Task is brought forward with the Activity‘s last state restored and this Activity
receives the new intent in onNewIntent method.

launchMode — singleInstance: This launchMode is similar to the singleTask except that the System
doesn‘t launch any other Activity into the Task holding the instance. The Activity is always the single and
the only member of its Task. Any Activity started by this one opens in a separate Task.

S. Parsuvanathan M.Sc., M.Phil Page 41


UNIT – III

ANDROID SERVICE:

A Service is an application component that can perform long-running operations in the background,
and it doesn't provide a user interface. Another application component can start a service, and it continues to
run in the background even if the user switches to another application. These are the three different types of
services:

 Foreground: A foreground service performs some operation that is noticeable to the user.
 Background: A background service performs an operation that isn't directly noticed by the user.
 Bound: A service is bound when an application component binds to it by calling bindService(). A
bound service offers a client-server interface that allows components to interact with the service,
send requests, receive results, and even do so across processes with interprocess communication
(IPC).

To create a service, you must create a subclass of Service or use one of its existing subclasses. In your
implementation, you must override some callback methods. These are the most important callback methods
that you should override:

 onStartCommand(): The system invokes this method by calling startService() when another
component (such as an activity) requests that the service be started.
 onBind(): The system invokes this method by calling bindService() when another component wants
to bind with the service (such as to perform RPC).
 onCreate(): The system invokes this method to perform one-time setup procedures when the service
is initially created.
 onDestroy(): The system invokes this method when the service is no longer used and is being
destroyed.

DECLARING A SERVICE IN THE MANIFEST

You must declare all services in your application's manifest file, just as you do for activities and
other components. To declare your service, add a <service> element as a child of the <application> element.
Here is an example:

<manifest ... >


...
<application ... >
<service android:name=".ExampleService" />
...

S. Parsuvanathan M.Sc., M.Phil Page 42


</application>
</manifest>

CREATING A SERVICE

A started service is one that another component starts by calling startService(), which results in a call
to the service's onStartCommand() method.

You can start a service from an activity or other application component by passing
an Intent to startService() or startForegroundService(). The Android system calls the
service's onStartCommand() method and passes it the Intent, which specifies which service to start.

Intent intent = new Intent(this, HelloService.class);


startService(intent);
STOPPING A SERVICE
A started service must manage its own lifecycle. That is, the system doesn't stop or destroy the
service unless it must recover system memory and the service continues to run
after onStartCommand() returns. The service must stop itself by calling stopSelf(), or another component can
stop it by calling stopService(). Once requested to stop with stopSelf() or stopService(), the system destroys
the service as soon as possible.
Example:
Myservice.java
public class MyService extends Service {
private MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
// This will play the ringtone continuously until we stop the service.
player.setLooping(true);
// It will start the player

S. Parsuvanathan M.Sc., M.Phil Page 43


player.start();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// Stopping the player when service is destroyed
player.stop();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startService"
android:layout_marginLeft="130dp"
android:layout_marginTop="150dp"
android:text="Start Service"/>
<Button
android:id="@+id/btnstop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="stopService"
android:layout_marginLeft="130dp"
android:layout_marginTop="20dp"
android:text="Stop Service"/>
</LinearLayout>

S. Parsuvanathan M.Sc., M.Phil Page 44


S. Parsuvanathan M.Sc., M.Phil Page 45
BROADCASTS RECEIVER:
Android apps can send or receive broadcast messages from the Android system and other Android
apps, similar to the publish-subscribe design pattern. These broadcasts are sent when an event of interest
occurs. For example, the Android system sends broadcasts when various system events occur, such as when
the system boots up or the device starts charging.

Apps can register to receive specific broadcasts. When a broadcast is sent, the system automatically
routes broadcasts to apps that have subscribed to receive that particular type of broadcast. However, you
must be careful not to abuse the opportunity to respond to broadcasts and run jobs in the background that can
contribute to a slow system performance, as described in the following video.

RECEIVING BROADCASTS
Apps can receive broadcasts in two ways: through manifest-declared receivers and context-registered
receivers.

1. If you declare a broadcast receiver in your manifest, the system launches your app (if the app is not
already running) when the broadcast is sent.

<receiver android:name=".MyBroadcastReceiver" android:exported="true">


<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
</intent-filter>
</receiver>

2. Subclass BroadcastReceiver and implement onReceive(Context, Intent). The broadcast receiver in the
following example logs and displays the contents of the broadcast:

public class MyBroadcastReceiver extends BroadcastReceiver {


private static final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
StringBuilder sb = new StringBuilder();
sb.append("Action: " + intent.getAction() + "\n");
sb.append("URI: " + intent.toUri(Intent.URI_INTENT_SCHEME).toString() +
"\n");
String log = sb.toString();
Log.d(TAG, log);
Toast.makeText(context, log, Toast.LENGTH_LONG).show();
}
}

SENDING BROADCASTS
Android provides three ways for apps to send broadcast:

S. Parsuvanathan M.Sc., M.Phil Page 46


 The sendOrderedBroadcast(Intent, String) method sends broadcasts to one receiver at a time. As each
receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the
broadcast so that it won't be passed to other receivers.

 The sendBroadcast(Intent) method sends broadcasts to all receivers in an undefined order. This is
called a Normal Broadcast.

 The LocalBroadcastManager.sendBroadcast method sends broadcasts to receivers that are in the


same app as the sender. If you don't need to send broadcasts across apps, use local broadcasts.

Following are some of the important system wide generated intents.

1. android.intent.action.BATTERY_LOW : Indicates low battery condition on the device.


2. android.intent.action.BOOT_COMPLETED : This is broadcast once, after the system has finished
booting
3. android.intent.action.CALL : To perform a call to someone specified by the data
4. android.intent.action.DATE_CHANGED : The date has changed

5. android.intent.action.REBOOT : Have the device reboot

6. android.net.conn.CONNECTIVITY_CHANGE : The mobile network or wifi connection is


changed(or reset)

Example:

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.journaldev.broadcastreceiver.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
S. Parsuvanathan M.Sc., M.Phil Page 47
android:text="Send Broadcast"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ConnectionReceiver receiver;
IntentFilter intentFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
receiver = new ConnectionReceiver();
intentFilter = new IntentFilter("com.journaldev.broadcastreceiver.SOME_ACTION");
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
@OnClick(R.id.button)
void someMethod() {
Intent intent = new Intent("com.journaldev.broadcastreceiver.SOME_ACTION");
sendBroadcast(intent);
}
}
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.journaldev.broadcastreceiver">

S. Parsuvanathan M.Sc., M.Phil Page 48


<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ConnectionReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>

CONTENT PROVIDER:
A content provider manages access to a central repository of data. A provider is part of an Android
application, which often provides its own UI for working with the data. However, content providers are
primarily intended to be used by other applications, which access the provider using a provider client object.

Typically you work with content providers in one of two scenarios; you may want to implement code
to access an existing content provider in another application, or you may want to create a new content
provider in your application to share data with other applications.

A content provider coordinates access to the data storage layer in your application for a number of
different APIs and components as illustrated in figure 1, these include:

 Sharing access to your application data with other applications


 Sending data to a widget

S. Parsuvanathan M.Sc., M.Phil Page 49


 Returning custom search suggestions for your application through the search framework
using SearchRecentSuggestionsProvider
 Synchronizing application data with your server using an implementation
of AbstractThreadedSyncAdapter
 Loading data in your UI using a CursorLoader

When you want to access data in a


content provider, you use
the ContentResolver object in your
application's Context to communicate with the
provider as a client.
The ContentResolver object communicates
with the provider object, an instance of a class
that implements ContentProvider. The provider
object receives data requests from clients,
performs the requested action, and returns the
results. This object has methods that call identically-named methods in the provider object, an instance of
one of the concrete subclasses of ContentProvider. The ContentResolver methods provide the basic "CRUD"
(create, retrieve, update, and delete) functions of persistent storage.
// Queries the user dictionary and returns results
cursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
projection, // The columns to return for each row
selectionClause, // Selection criteria
selectionArgs, // Selection criteria
sortOrder); // The sort order for the returned rows

RETRIEVING DATA FROM THE PROVIDER


To retrieve data from a provider, follow these basic steps:
1. Request the read access permission for the provider.
2. Define the code that sends a query to the provider.
1. Requesting read access permission
To retrieve data from a provider, your application needs "read access permission" for the provider.
You can't request this permission at run-time; instead, you have to specify that you need this permission in
your manifest, using the <uses-permission> element and the exact permission name defined by the provider.
To find the exact name of the read access permission for the provider you're using, as well as the names for
other access permissions used by the provider, look in the provider's documentation.

S. Parsuvanathan M.Sc., M.Phil Page 50


2. Constructing the query
The next step in retrieving data from a provider is to construct a query. This first snippet defines
some variables for accessing the User Dictionary Provider:
// A "projection" defines the columns that will be returned for each row
String[] mProjection =
{
UserDictionary.Words._ID, // Contract class constant for the _ID column name
UserDictionary.Words.WORD, // Contract class constant for the word column name
UserDictionary.Words.LOCALE // Contract class constant for the locale column name
};

// Defines a string to contain the selection clause


String selectionClause = null;

// Initializes an array to contain selection arguments


String[] selectionArgs = {""};

CONTENTRESOLVER.
Each android application can be a content provider. For example, android phone contacts, short
message system and android media library. To get data from a content provider, you need to use
a ContentResolver instance in your app. Generally the ContentResolver instance can be obtained
by Activity‗s getContentResolver() method.
ContentResolver contentResolver = getContentResolver();
Then you can invoke ContentResolver‗s method to insert, delete, update and query data that another
content provider shared. This is something like SQLite database operation.
1 Insert Data To Content Provider:
insert(Uri providerUri, ContentValues values)
2 Update Content Provider Data.
update(Uri providerUri, ContentValues values, String whereClause, String conditionValueArr[])
3 Delete Content Provider Data.
delete(Uri providerUri, String whereClause, String conditionValueArr[])
2.4 Query Content Provider Data.
query(Uri uri, String columnArray[], String whereClause, String wherePlaceHolderValue[], String
orderByClause)

Example:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView

S. Parsuvanathan M.Sc., M.Phil Page 51


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:layout_marginLeft="100dp"
android:layout_marginTop="100dp"/>
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickAddDetails"
android:layout_marginLeft="100dp"
android:text="Add User"/>
<Button
android:id="@+id/btnRetrieve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickShowDetails"
android:layout_marginLeft="100dp"
android:text="Show Users"/>
<TextView
android:id="@+id/res"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:clickable="false"
android:ems="10"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {

S. Parsuvanathan M.Sc., M.Phil Page 52


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
public void onClickAddDetails(View view) {
ContentValues values = new ContentValues();
values.put(UsersProvider.name, ((EditText) findViewById(R.id.txtName)).getText().toString());
getContentResolver().insert(UsersProvider.CONTENT_URI, values);
Toast.makeText(getBaseContext(), "New Record Inserted", Toast.LENGTH_LONG).show();
}
public void onClickShowDetails(View view) {
// Retrieve employee records
TextView resultView= (TextView) findViewById(R.id.res);
Cursor cursor =
getContentResolver().query(Uri.parse("content://com.tutlane.contentprovider.UserProvider/users"), null,
null, null, null);
if(cursor.moveToFirst()) {
StringBuilder strBuild=new StringBuilder();
while (!cursor.isAfterLast()) {
strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
}
resultView.setText(strBuild);
}
else {
resultView.setText("No Records Found");
}
}
}

SQLite DATABASE
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in
with built in SQLite database implementation. SQLite supports all the relational database features. In order
to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c

 The main package is android.database.sqlite that contains the classes to manage your own databases

S. Parsuvanathan M.Sc., M.Phil Page 53


 In order to create a database you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter. It returns an instance of SQLite database which you have to
receive in your own object.Its syntax is given below

1. Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase class.
Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS sample (Username VARCHAR,Password
VARCHAR);");
mydatabase.execSQL("INSERT INTO sample VALUES('admin','admin');");

2. Database - Fetching

We can retrieve anything from database using an object of the Cursor class. We will call a method of
this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move
the cursor forward and retrieve the data.

Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);


resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
Other useful Methods:
 getColumnCount(): This method return the total number of columns of the table.
 getColumnIndex(String columnName): This method returns the index number of a column by
specifying the name of the column
 getColumnName(int columnIndex): This method returns the name of the column by specifying the
index of the column
 getColumnNames(): This method returns the array of all the column names of the table.
 getCount(): This method returns the total number of rows in the cursor
 getPosition(): This method returns the current position of the cursor in the table
 isClosed(): This method returns true if the cursor is closed and return false otherwise

3. Database - Helper class


For managing all the operations related to the database , an helper class has been given and is called
SQLiteOpenHelper. It automatically manages the creation and update of the database. Its syntax is given
below
public class DBHelper extends SQLiteOpenHelper {

S. Parsuvanathan M.Sc., M.Phil Page 54


public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
{}
}
Example:
DBHandler.java
public class DbHandler extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "usersdb";
private static final String TABLE_Users = "userdetails";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_LOC = "location";
private static final String KEY_DESG = "designation";
public DbHandler(Context context){
super(context,DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
String CREATE_TABLE = "CREATE TABLE " + TABLE_Users + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ KEY_LOC + " TEXT,"
+ KEY_DESG + " TEXT"+ ")";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
// Drop older table if exist
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Users);
// Create tables again
onCreate(db);
}
// **** CRUD (Create, Read, Update, Delete) Operations ***** //

S. Parsuvanathan M.Sc., M.Phil Page 55


// Adding new User Details
void insertUserDetails(String name, String location, String designation){
//Get the Data Repository in write mode
SQLiteDatabase db = this.getWritableDatabase();
//Create a new map of values, where column names are the keys
ContentValues cValues = new ContentValues();
cValues.put(KEY_NAME, name);
cValues.put(KEY_LOC, location);
cValues.put(KEY_DESG, designation);
// Insert the new row, returning the primary key value of the new row
long newRowId = db.insert(TABLE_Users,null, cValues);
db.close();
}
// Get User Details
public ArrayList<HashMap<String, String>> GetUsers(){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
String query = "SELECT name, location, designation FROM "+ TABLE_Users;
Cursor cursor = db.rawQuery(query,null);
while (cursor.moveToNext()){
HashMap<String,String> user = new HashMap<>();
user.put("name",cursor.getString(cursor.getColumnIndex(KEY_NAME)));
user.put("designation",cursor.getString(cursor.getColumnIndex(KEY_DESG)));
user.put("location",cursor.getString(cursor.getColumnIndex(KEY_LOC)));
userList.add(user);
}
return userList;
}
// Get User Details based on userid
public ArrayList<HashMap<String, String>> GetUserByUserId(int userid){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
String query = "SELECT name, location, designation FROM "+ TABLE_Users;

S. Parsuvanathan M.Sc., M.Phil Page 56


Cursor cursor = db.query(TABLE_Users, new String[]{KEY_NAME, KEY_LOC, KEY_DESG},
KEY_ID+ "=?",new String[]{String.valueOf(userid)},null, null, null, null);
if (cursor.moveToNext()){
HashMap<String,String> user = new HashMap<>();
user.put("name",cursor.getString(cursor.getColumnIndex(KEY_NAME)));
user.put("designation",cursor.getString(cursor.getColumnIndex(KEY_DESG)));
user.put("location",cursor.getString(cursor.getColumnIndex(KEY_LOC)));
userList.add(user);
}
return userList;
}
// Delete User Details
public void DeleteUser(int userid){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_Users, KEY_ID+" = ?",new String[]{String.valueOf(userid)});
db.close();
}
// Update User Details
public int UpdateUserDetails(String location, String designation, int id){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cVals = new ContentValues();
cVals.put(KEY_LOC, location);
cVals.put(KEY_DESG, designation);
int count = db.update(TABLE_Users, cVals, KEY_ID+" = ?",new String[]{String.valueOf(id)});
return count;
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

S. Parsuvanathan M.Sc., M.Phil Page 57


android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="Name" />
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="@+id/thirdTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Designation"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtDesignation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/btnSave"

S. Parsuvanathan M.Sc., M.Phil Page 58


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Save" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText name, loc, desig;
Button saveBtn;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.txtName);
loc = (EditText)findViewById(R.id.txtLocation);
desig = (EditText)findViewById(R.id.txtDesignation);
saveBtn = (Button)findViewById(R.id.btnSave);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = name.getText().toString()+"\n";
String location = loc.getText().toString();
String designation = desig.getText().toString();
DbHandler dbHandler = new DbHandler(MainActivity.this);
dbHandler.insertUserDetails(username,location,designation);
intent = new Intent(MainActivity.this,DetailsActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Details Inserted
Successfully",Toast.LENGTH_SHORT).show();
}
});
}
}

S. Parsuvanathan M.Sc., M.Phil Page 59


S. Parsuvanathan M.Sc., M.Phil Page 60
UNIT IV
ANDROID LAYOUT:
The basic building block for user interface is a View object which is created from the View class and
occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base
class for widgets, which are used to create interactive UI components like buttons, text fields, etc.
The ViewGroup is a subclass of View and provides invisible container that hold other Views or other
ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical layout
defines the visual structure for an Android user interface and can be created either at run time
using View/ViewGroup objects or you can declare your layout using simple XML
file main_layout.xml which is located in the res/layout folder of your project.

ANDROID LAYOUT TYPES


 Linear Layout - LinearLayout is a view group that aligns all children in a single direction, vertically
or horizontally.
 Relative Layout - RelativeLayout is a view group that displays child views in relative positions.
 Table Layout - TableLayout is a view that groups views into rows and columns.
 Absolute Layout - AbsoluteLayout enables you to specify the exact location of its children.
 Frame Layout - The FrameLayout is a placeholder on screen that you can use to display a single
view.
 List View - ListView is a view group that displays a list of scrollable items.
 Grid View - GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

LAYOUT ATTRIBUTES

Each layout has a set of attributes which define the visual properties of that layout. There are few
common attributes among all the layouts and their are other attributes which are specific to that layout.
Following are common attributes and will be applied to all the layouts:
S. Parsuvanathan M.Sc., M.Phil Page 61
 android:id - This is the ID which uniquely identifies the view.
 android:layout_width - This is the width of the layout.
 android:layout_height - This is the height of the layout
 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_gravity - This specifies how child Views are positioned.
 android:layout_weight - This specifies how much of the extra space in the layout should be
allocated to the View.
 android:paddingLeft - This is the left padding filled for the layout.
 android:paddingRight - This is the right padding filled for the layout.
 android:paddingTop - This is the top padding filled for the layout.
 android:paddingBottom - This is the bottom padding filled for the layout.

1. LinearLayout

The LinearLayout arranges views in a single column or a single row. Child views can be arranged
either vertically or horizontally. To see how LinearLayout works, consider the following elements typically
contained in the main.xml file:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>

2. RelativeLayout

The RelativeLayout enables you to specify how child views are positioned relative to each other.

Consider the following main.xml file:


<RelativeLayout

android:id=”@+id/RLayout”

android:layout_width=”fill_parent”

android:layout_height=”fill_parent”

xmlns:android=”http://schemas.android.com/apk/res/android” >

S. Parsuvanathan M.Sc., M.Phil Page 62


3. TableLayout

The TableLayout groups views into rows and columns. You use the <TableRow> element to
designate a row in the table. Each row can contain one or more views. Each view you place within a row
forms a cell. The width of each column is determined by the largest width of each cell in that column.
Consider the content of main.xml shown here:
<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent” >
<TableRow>
<TextView
android:text=”User Name:”
android:width =”120dp”
/>
<EditText
android:id=”@+id/txtUserName”
android:width=”200dp” />
</TableRow>
<TableRow>
<TextView
android:text=”Password:”
/>
<EditText
android:id=”@+id/txtPassword”
android:password=”true”
/>
</TableRow>
<TableRow>
<TextView />
<CheckBox android:id=”@+id/chkRememberPassword”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Remember Password”
/>
</TableRow>
<TableRow>
<Button
android:id=”@+id/buttonSignIn”
android:text=”Log In” />
</TableRow>
</TableLayout>

4. FrameLayout
The FrameLayout is a placeholder on screen that you can use to display a single view. Views that
you add to a FrameLayout are always anchored to the top left of the layout. Consider the following content
in main.xml:
<?xml version=”1.0” encoding=”utf-8”?>
<RelativeLayout

S. Parsuvanathan M.Sc., M.Phil Page 63


android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
<TextView
android:id=”@+id/lblComments”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Hello, Android!”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true” />
<FrameLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true” >
<ImageView
android:src = “@drawable/droid”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</FrameLayout>
</RelativeLayout>

5. GridView Layout:
Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the grid
items are not necessarily predetermined but they automatically inserted to the layout using a ListAdapter.
The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to
an Adapter, which retrieves data from an external source and creates a View that represents each data entry.
GridView Attributes
 android:id - This is the ID which uniquely identifies the layout.
 android:columnWidth - This specifies the fixed width for each column. This could be in px, dp, sp,
in,
 android:gravity - Specifies the gravity within each cell. Possible values are top, bottom, left, right,
center, center_vertical, center_horizontal etc.
 android:horizontalSpacing - Defines the default horizontal spacing between columns. This could
be in px, dp, sp, in, or mm.
 android:numColumns - Defines how many columns to show. May be an integer value, such as
"100" or auto_fit which means display as many columns as possible to fill the available space.

S. Parsuvanathan M.Sc., M.Phil Page 64


S. Parsuvanathan M.Sc., M.Phil Page 65
MENUS
Menus are a common user interface component in many types of applications. To provide a familiar
and consistent user experience, you should use the Menu APIs to present user actions and other options in
your activities.
Although the design and user experience for some menu items have changed, the semantics to define
a set of actions and options is still based on the Menu APIs. This guide shows how to create the three
fundamental types of menus or action presentations on all versions of Android:
 Options menu: The options menu is the primary collection of menu items for an activity. It's where
you should place actions that have a global impact on the app, such as "
 Context menu : A context menu is a floating menu that appears when the user performs a long-click
on an element. It provides actions that affect the selected content or context frame.
 Popup menu: A popup menu displays a list of items in a vertical list that's anchored to the view that
invoked the menu.

Defining a Menu in XML


For all menu types, Android provides a standard XML format to define menu items. Instead of
building a menu in your activity's code, you should define a menu and all its items in an XML menu
resource. You can then inflate the menu resource (load it as a Menu object) in your activity or fragment.
To define the menu, create an XML file inside your project's res/menu/ directory and build the menu
with the following elements:
 <menu> - Defines a Menu, which is a container for menu items. A <menu> element must be the
root node for the file and can hold one or more <item> and <group> elements.
 <item> - Creates a MenuItem, which represents a single item in a menu. This element may contain a
nested <menu> element in order to create a submenu.
 <group> - An optional, invisible container for <item> elements. It allows you to categorize menu
items so they share properties such as active state and visibility.
Here's an example menu named game_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/ic_new_game"
android:title="@string/new_game"
android:showAsAction="ifRoom"/>
<item android:id="@+id/help"
android:icon="@drawable/ic_help"
android:title="@string/help" />
</menu>

S. Parsuvanathan M.Sc., M.Phil Page 66


OPTIONS MENU
The options menu is where you should include actions and other
options that are relevant to the current activity context, such as "Search,"
"Compose email," and "Settings."
Where the items in your options menu appear on the screen depends
on the version for which you've developed your application:
You can declare items for the options menu from either
your Activity subclass or a Fragment subclass. If both your activity and
fragment(s) declare items for the options menu, they are combined in the
UI. The activity's items appear first, followed by those of each fragment in
the order in which each fragment is added to the activity. If necessary, you
can re-order the menu items with the android:orderInCategory attribute in
each <item> you need to move.
To specify the options menu for an activity,
override onCreateOptionsMenu(). In this method, you can inflate your
menu resource (defined in XML) into the Menu provided in the callback.
For example:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}

2. CONTEXTUAL MENUS
A contextual menu offers actions that affect a specific item or
context frame in the UI. You can provide a context menu for any view,
but they are most often used for items in a ListView, GridView, or other
view collections in which the user can perform direct actions on each
item.
There are two ways to provide contextual actions:
 In a floating context menu. A menu appears as a floating list of
menu items (similar to a dialog) when the user performs a long-
click (press and hold) on a view that declares support for a context
menu. Users can perform a contextual action on one item at a time.

S. Parsuvanathan M.Sc., M.Phil Page 67


 In the contextual action mode. This mode is a system implementation of ActionMode that displays
a contextual action bar at the top of the screen with action items that affect the selected item(s).
When this mode is active, users can perform an action on multiple items at once (if your app allows
it).

Creating Context Menu:


1. Register the View to which the context menu should be associated by
calling registerForContextMenu() and pass it the View.
2. Implement the onCreateContextMenu() method in your Activity or Fragment.
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}

3. Implement onContextItemSelected(). When the user selects a menu item, the system calls this method so
you can perform the appropriate action.

@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.edit:
editNote(info.id);
return true;
case R.id.delete:
deleteNote(info.id);
return true;
default:
return super.onContextItemSelected(item);
}
}

POPUP MENU
A PopupMenu is a modal menu anchored to a View. It appears below
the anchor view if there is room, or above the view otherwise. It's useful
for:
 Providing an overflow-style menu for actions that relate
to specific content (such as Gmail's email headers, shown in
figure 4).
 Providing a second part of a command sentence (such as a button
marked "Add" that produces a popup menu with different "Add"
options).
 Providing a drop-down similar to Spinner that does not retain a
persistent selection.

S. Parsuvanathan M.Sc., M.Phil Page 68


If you define your menu in XML, here's how you can show the popup menu:
1. Instantiate a PopupMenu with its constructor, which takes the current application Context and
the View to which the menu should be anchored.
2. Use MenuInflater to inflate your menu resource into the Menu object returned
by PopupMenu.getMenu().
3. Call PopupMenu.show().
activity_main.xml
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_overflow_holo_dark"
android:contentDescription="@string/descr_overflow_button"
android:onClick="showPopup" />

MainActivity.java
public void showPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.actions, popup.getMenu());
popup.show();
}

LIST
Android ListView is a view which groups several items and display them in vertical scrollable list.
The list items are automatically inserted to the list using an Adapter that pulls content from a source such as
an array or database.
An adapter actually bridges between UI components and the data source that fill data into UI
Component. Adapter holds the data and send the data to adapter view, the view can takes the data from
adapter view and shows the data on different views like as spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be populated by binding
them to an Adapter, which retrieves data from an external source and creates a View that represents each
data entry.
Android provides several subclasses of Adapter that are useful for retrieving different kinds of data
and building views for an AdapterView ( i.e. ListView or GridView). The common adapters
are ArrayAdapter,Base
Adapter, CursorAdapter, SimpleCursorAdapter,SpinnerAdapter and WrapperListAdapter. We will
see separate examples for both the adapters.

List View Attribute:


S. Parsuvanathan M.Sc., M.Phil Page 69
 android:id - This is the ID which uniquely identifies the layout.
 android:divider - This is drawable or color to draw between list items.
 android:dividerHeight - This specifies height of the divider. This could be in px, dp, sp, in, or mm.

 android:entries - Specifies the reference to an array resource that will populate the ListView.
 android:footerDividersEnabled - When set to false, the ListView will not draw the divider before
each footer view. The default value is true.

Example:
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ListActivity" >
<ListView
android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
MainActivity.java
public class ListDisplay extends Activity {
// Array of strings...
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
"WebOS","Ubuntu","Windows7","Max OS X"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, mobileArray);
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
}
}

INPUT CONTROLS:

S. Parsuvanathan M.Sc., M.Phil Page 70


In android ui or input controls are the interactive or View components which are used to design the
user interface of an application. In android we have a wide variety of UI or input controls available, those
are TextView, EditText, Buttons, Checkbox, Progressbar, Spinners, etc. Following is the pictorial
representation of user interface (UI) or input controls in android application.
The View is a base class for all UI components in
android and it is used to create an interactive UI
components such
as TextView, EditText, Checkbox, Radio Button,
etc. and it responsible for event handling and
drawing.

The ViewGroup is a subclass of View and


it will act as a base class for layouts and layout parameters. The ViewGroup will provide an invisible
containers to hold other Views or ViewGroups and to define the layout properties.
In android, we can define a UI or input controls in two ways, those are
 Declare UI elements in XML
 Create UI elements at runtime

1. TEXTVIEW CONTROL
In android, TextView is a user interface control which is used to set and display the text to the user
based on our requirements. The TextView control will act as like label control and it won‘t allow users to
edit the text. In android, we can create a TextView control in two ways either in XML layout file or create it
in Activity file programmatically.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Welcome to Tutlane"
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold" />
</LinearLayout>

TextView Attributes

Following are the some of commonly used attributes related to TextView control in android applications.

 android: id - It is used to uniquely identify the control

S. Parsuvanathan M.Sc., M.Phil Page 71


 android:autoLink - It will automatically found and convert urls and email addresses as a clickable
links.
 android: ems - It is used to make the textview be exactly this many ems wide.
 android:hint - It is used to display the hint text when text is empty
 android:width - It makes the TextView be exactly this many pixels wide.
 android:height - It makes the TextView be exactly this many pixels tall.
 android:text - It is used to display the text.
 android:textColor - It is used to change the color of text.
 android:gravity - It is used to specify how to align the text by the view's x and y axis.

2. BUTTON CONTROL:

In android, Button is a user interface control which is used to perform an action whenever the user
click or tap on it. Generally, Buttons in android will contains a text or an icon or both and perform an action
when user touches it.

Following is the pictorial representation of using Buttons in android applications.

In android, we have a different type of buttons available to use based on our requirements, those
are ImageButton, ToggleButton, RadioButton. In android, we can create a Button control in two ways
either in XML layout file or create it in Activity file programmatically.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
</LinearLayout>

3. CHECKBOX CONTROLS:
In android, CheckBox is a two states button that can be either checked (ON) or unchecked (OFF)
and it will allow users to toggle between the two states (ON / OFF) based on the requirements. Generally, we
can use multiple CheckBox controls in android application to allow users to select one or more options from
the set of values.
By default, the android CheckBox will be in OFF (Unchecked) state. We can change the default
state of CheckBox by using android:checked attribute.
In case, if we want to change the state of CheckBox to ON (Checked), then we need to
set android:checked = ―true‖ in our XML layout file.
In android, we can create CheckBox control in two ways either in XML layout file or create it
in Activity file programmatically.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">

S. Parsuvanathan M.Sc., M.Phil Page 72


<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Java" /> </RelativeLayout>
Generally, whenever the user click on CheckBox to Select or Deselect the CheckBox object will
receives an on-click event. In android, we can define CheckBox click event in two ways either in XML
layout file or create it in Activity file programmatically.
4. SPINNER CONTROL:
In android, Spinner is a view which allow a user to select one value from the list of values. The
spinner in android will behave same like dropdown list in other programming languages. Generally, the
android spinners will provide a quick way to select one item from the list of values and it will show a
dropdown menu with a list of all values when we click or tap on it.
By default, the android spinner will show its currently selected value and by using Adapter we can
bind the items to spinner object.
We can populate our Spinner control with list of choices by defining an ArrayAdapter in
our Activity file. Generally, the Adapter pulls data from a sources such as an array or database and converts
each item into a result view and that‘s placed into the list.
<Spinner android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

5. RATING BAR CONTROL:


In android, RatingBar is a UI control which is used to get the rating from the user. The RatingBar is
an extension of SeekBar and ProgressBar that shows a rating in stars and it allow users to set the rating value
by touch or click on the stars.
The android RatingBar will always return a rating value as floating
point number such as 1.0, 2.0, 2.5, 3.0, 3.5, etc.
In android, by using android:numStars attribute we can define the
number of stars to display in RatingBar. An example of using RatingBar is in
movie sites or product sites to collect the user rating about the movies or products, etc.
In android, by using android.widget.RatingBar component we can display the rating bar with star icons.
Attributes:
android:id - It is used to uniquely identify the control
android:numStars - It is used to define number of stars to display.
android:rating - It is used to set the default rating value for ratingbar.
Example:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

S. Parsuvanathan M.Sc., M.Phil Page 73


android:layout_width="match_parent" android:layout_height="match_parent">
<RatingBar
android:id="@+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginTop="200dp"
android:numStars="5"
android:rating="3.5"/>
6. PROGRESS BAR CONTROL:
In android, ProgressBar is a user interface control which is used to indicate the progress of an
operation. For example, downloading a file, uploading a file.
By default the ProgressBar will be displayed as a spinning wheel, in case if we want to show it like
horizontal bar then we need to change the style property to horizontal
like style="?android:attr/progressBarStyleHorizontal".
<ProgressBar
android:id="@+id/pBar3"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:minWidth="250dp"
android:max="100"
android:indeterminate="true"
android:progress="1" />

If you observe above code snippet, we defined a progress bar (<ProgressBar>) with different
attributes, those are
 android:id - It is used to uniquely identify the control
 android:minHeight - It is used to set the height of progress bar.
 android:minWidth - It is used to set the width of progress bar.
 android:max - It is used to set the maximum value of progress bar.
 android:progress - It is used to set the default progress value between 0 and max. It must be an
integer value.

7. ALERT DIALOG CONTROL:


In android, Dialog is a small window that prompt messages to the user to make a decision or enter
additional details. Generally, the Dialogs are used with modals event and these useful to prompt users to
perform a particular action to proceed further in application.
S. Parsuvanathan M.Sc., M.Phil Page 74
Following is the pictorial representation of using dialogs in android applications.
In android, we have a different type of Dialogs available, those are

Dialog Description

AlertDialog This dialog is used to display prompt to the user with title, upto three buttons, list of
selectable items or a custom layout.

DatePickerDialog This dialog is a predefined UI control and it allow user to select Date.

TimePickerDialog It‘s a predefined UI control and it allow user to select Time.

Android AlertDialog
In android, AlertDialog is used to
prompt a dialog to the user with message
and buttons to perform an action to
proceed further.
The AlertDialog in android
application will contain a three regions
like as shown below.
In android Alert Dialogs, we can
show a title, up to three buttons, a list of
selectable items or a custom layout based on our requirements.

Region Description

Title It‘s an optional and it can be used to show the detailed messages based on our requirements.

Content It is used to display a message, list or other custom layouts based on our requirements.
Area

Action It is used to display an action buttons to interact with the users. We can use upto 3 different
Buttons action buttons in alert dialog, such as positive, negative and neutral.

Generally, in android we can build AlertDialog in our activity file using different dialog methods.
Android AlertDialog Methods

S. Parsuvanathan M.Sc., M.Phil Page 75


Following are the some of commonly used methods related to AlertDialog control to built alert prompt in
android applications.

Method Description

setTitle() It is used to set the title of alertdialog and its an optional component.

setIcon() It is used to set the icon before the title

setMessage() It is used to set the message required message to display in alertdialog.

setCancelable() It is used to allow users to cancel alertdialog by clicking on outside of dialog area by
setting true / false.

setPositiveButton() It is used to set the positive button for alertdialog and we can implement click event
of positive button.

setNegativeButton() It is used to set the negative button for alertdialog and we can implement click event
of negative button.

setNeutralButton() It is used to set the neutral button for alertdialog and we can implement click event
of neutral button.

***** ALL THE BEST *****

S. Parsuvanathan M.Sc., M.Phil Page 76

You might also like