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

Android Notes

The document discusses the tools and software required to develop Android applications, including the Android SDK, Java Development Kit, and Android Studio IDE. It explains that the Android SDK works with Windows, Mac and Linux and developers can set up their environment manually with Eclipse or more easily with the bundled Android Studio IDE.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Android Notes

The document discusses the tools and software required to develop Android applications, including the Android SDK, Java Development Kit, and Android Studio IDE. It explains that the Android SDK works with Windows, Mac and Linux and developers can set up their environment manually with Eclipse or more easily with the bundled Android Studio IDE.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 451

G

GPM

[Pick t he date]
Chapter 1. Android and its tools

1.1 Introduction to Android, open headset alliance, Android Ecosystem.


1.2 Need of Android, Features Of Android.
1.3 Tools and software required for development an Android Application.
1.4 Android Architecture.

1.1 Introduction to Android, open headset alliance, Android Ecosystem.


OHA – Open Handset Alliance

What is open Handset Alliance?


1) Open Handset Alliance (OHA) was formed in NOV 2007.

2 ) The OHA is the group that is in charge of Android smartphones O.S.

3 ) it was created by Google

4) The Open Handset Alliance (DHA) is a business alliance that consists of 47 companiesfor
developing open standard platform for mobile devices

5) The member of OHA include-handset manufacture,


- Chip makers
- Commercialization companies
- Software companies
- Mobile operation

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 1


Handset
Mobile Operators
Manufacture Chip

Open Handset

Software Commercializatio
Companie n Companies
s

Android Ecosystem

What is Android Ecosystem? Explained


1) Android Ecosystem is interdependence between users developers and equipment makers,
one cannot Exit without other.
2) It is created around the Google Play-mobile application market place and including
Orchestrate (Google) customer and application developers.
3) It includes
a) Star holders: consumers that own Android device
b) Google- it develops android
c) OEMS-Original Equipment Manufacturers They manufactures Hardware as well the
custom application component.
d) Application Development companies
They are the major contributors to the ecosystem and employ Android developers and also
contract out the product development to services companies.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 2


1.2 Need of Android, Features Of Android.
Need of Android
Why Android? / Explain need of Android?

1] Browser
i) Android browser is one of the best browser on mobile market It generally loads pages
faster
ii) than safari or any other browser has Flash support and simply does everythinga
browser Should do

2] Desktop
The Android phone adds widgets to desktop The purpose for widget.
Eg. the face book widget allows you to update your Fb desktop.
- The people widget allows you to make.
- possible diff actions for different contacts right from your desktop •
-The message widget allows you to immediately see your email from desktop

3] Connectivity
On one page/ desktop you could be able to have 4 connecting device tool button
1) [Turn on/off Bluetooth
2) LTurn on/off mobile
3) LTurn on/off wifi
4] Multi-Notification:
Android phones have multi-notification system with android the app have access to the
notification system and call all report

5] Endless Personalization
The Android cell phone allows client to configure 40x their mobile to look and behave exactly
like they want.
6] Market
Android has an android market.
The android apps are frees and work as well.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 3


7] Google Integration
The android has inbuilt Google support og: Google map, Gmail etc.
8] Open Source
The code of Android OS as well as apps is available.
9] Open to Carrier
If you know java then you are open to android world
10] Future
The future mobile phones are basically going to be smart phones.

Features of Android
Explain features of Android.
1] Open Source

- Android is an open source operating system This way that source code for Androidis
open to Public dissimilar IOS, which is kept secret by Apple.
- This way that anyone can work on OS, not only one company developers.
- Therefore app developers for Android devices are able to implement extra features of
their apps, due to the access they have to contain source code.
- Again these are only some of unique features to Android
- IOS also have many key abilities that are missing on Android device
2] Storage
- SOLite, a light weight relational database is used for data storage purposes.

3] Media Support
Android supports following audio/video/media formats.
- WebM
- H.263
- H.264
- AAC
- HE-AAC
- MPEG-4 SPon Ok
- AMR

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 4


- AMR-WB
- MP3
- WAV
- JPEG
- PNG
- GIF
- Ogg Vorblu
- FLAC
- BMP
- webp

4] Streaming media Support

- RTP/RTSP streaming (3G PP PSS, LIMA) - HTML progressive download m

- Adobe Flash Streaming CRTMP) and HTTP streaming supported by flash plugin

- Apple HTTP Live Streaming is support through Real Player for Android and the OSfor
duration.

5] Multi-touch

- Android has native support toy media touch which turns initially made available in
handset such as HTC Hero.
- These features has originally disabled at kernel level.
- Google has released an update version for Nexus One and Motorola droid which enables
multi-touch natively.
-
6] Web browser
- The web browser available in Android is based on open SOUT! Web kit layout engine
attached with Chrome's V8 JavaScript engine the browser SCOTOS 100/100 on top of
Acid & fest on Android.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 5


7] Video Calling
- Android does not support local l video calling, but Several handsets have a customized
version of 0.3. That supports it, either the UMTS network on ended IP.
- Video calling the Google Talk is available with in Android 2.34 and later dae2896A
- Gingerbread allows Nexus & to plate Internet calls with It SIP account.
- This allows for enhanced VoIP dialing to other sip accounts.

8] Multitasking
- Multitasking of application with unique handling of memory allocation will be existing.

9] Accessibility
Built in text to speech is provided by Talk back for people with low at no version. Enhancement fra
people the heaving disabilities are available as other aids.

10] Voice based features


- Google search the voice has been available since Opening release.
- Voice activities for navigation, calling, tatting etc. Supported on Android 2.2 forward
- As of Android 4.1, Google has expanded Voice Action with ability to talk back and read
answers from Google's knowledge Graph when queried with Specific Command.

11] External storage

- Most Android devices include incrust not and can Yead thicroSD cards Formatted with
FAT32 Ext 307 Ext file system.

- To allow use of high-capacity storage media such as USB flash drive and USBHDD'S
many Android tablets also include USB 'A' receptacle.

- Storage format with FAT 32 is handled by Litus keine VFAT driver, As 3rd party
solutions are necessary to handle other popular file systems NTFS, HFS Plus and ex FAT
such a NIFS,HFS plus.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 6


1.3 Tools and software required for development an Android Application.

• Generally to build an application for Android we should have Java Development Kit
(JDK), Android SDK and a development environment.
• The Android SDK is compatible with Windows, Mac and Linux operating systems to
build android applications based on our requirements.
• We can setup android development environment using following two ways:
1. Setup Eclipse IDE Manually (Depreciated)
2. Android Studio.(Android studio for developing mobile application)
• Initially Google supported a Manual Eclipse IDE Setup for android development
environment By downloading required components like Eclipse IDE, Android SDK, Java
Development Kit (JDK) etc. from official site.
• Afterwards Google introduced a component called Android Studio to make environment
setup process simple. Android Studio is the official IDE for Android application
development.
• By using Android Studio bundle we can easily setup android development environment
in any operating system to implement Android applications.
• Android Studio is the combination of components (Eclipse IDE, Android SDK, Android
Virtual Device and Eclipse Plugin) to allow users to implement android applications.
• By downloading Android Studio directly from Google website to setup we can easily
setup development environment.
• Check following steps to know more details about setting up android development
environment to implement required apps using Android Studio.

Download and Installing Android Studio:


• In this section we are going to explain how to install android studio on windows machine
which is having Windows 10 operating system.
• Download the latest version of Android Studio from above URL and launch Android
Studio.exe file by double clicking on it.
URL: (https://redirector.gvt1.com/edgedl/android/studio/install/4.2.1.0/android-
studio-ide-202.7351085-windows.exe )

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 7


Fig 1.4

• The initial android studio setup screen will open like as shown below in that click Next to
continue for further steps of environment setup, (See Fig. 1.5).

Fig 1.5

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 8


• Now we need to select a required components to setup an android environment. Here we
selected all three components (Android Studio, Android SDK and Android Virtual
Device) and click Next like as shown in Fig 1.6

Fig 1.6
• Now we need to agree the License agreements to proceed further, click on I Agree button
like as shown in Fig. 1.7.

Fig 1.7

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 9


• Now we need to specify the local machine drive location to install Android Studio and
Android SDK as shown in Fig 1.8

Fig 1.8
After selecting the location path to install required components, click Next like as shown in Fig.
1.9.

Fig 1.9

G. P. CO6I [MAD-22617] 10
MIRAJ ( S.
B.
SHINTRE )
• Now select the install menu folder to create a shortcuts for android studio and click
Install like as shown in Fig 1.10.

Fig 1.10

• Once we click Install button the installation process will start and click Next after
completion of installation like as shown in Fig. 1.11.

Fig 1.11

G. P. CO6I [MAD-22617] 11
MIRAJ ( S.
B.
SHINTRE )
• After that it will show installation completion wizard in that click Finish to launch
android studio like as shown in Fig. 1.12.

Fig 1.12

• While launching Android Studio it will give us an option to import settings from previous
version of studio. In case if we don’t have any previous version, select second option and
click OK like as shown in Fig 1.13.

Fig 1.13

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 12


• Now android studio will open a welcome wizard window in that click Next to validate
our current Android SDK and development environment setup like as shown in Fig. 1.14.

Fig 1.14
• Now select a Standard installation type and click Next to install a common settingsand
options like as shown in Fig. 1.15.

Fig 1.15

G. P. CO6I [MAD-22617] 13
MIRAJ ( S.
B.
SHINTRE )
• Now verify settings and click Finish to complete android studio setup process like as
shown in Fig. 1.16.

Fig 1.16

• After completion of required components installation click on Finish like as shown in


Fig. 1.17.

Fig 1.17

G. P. CO6I [MAD-22617] 14
MIRAJ ( S.
B.
SHINTRE )
• After completion of all required components installation we will be able to see Android
Studio welcome window like as shown in Fig. 1.18.

Fig 1.18
• This is how we can setup android development environment on windows machine whichis
having Windows 10 operating system using android studio IDE.

G. P. CO6I [MAD-22617] 15
MIRAJ ( S.
B.
SHINTRE )
1.4 Android Architecture.
• The Android OS can be referred to as software stack of diff layers, where every layer is
group of several program components
• It includes –
1. Operating systems
2. middle ware
3. Key applications

• Every laver in Architecture provides different services.


• Mostly Android has following layers-

1. Applications
2. Application framework
3. Libraries
4 Android runtime
5 Linux kernel

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 16


1. Applications

• All applications in application layer are written using Java language.


• The various core applications that an Android device provides include:
Email Client
SMS program
Maps
Browser Calendar
Contacts
Parallel running
No compulsory application

Application Framework:

• Android, being open, offers developers the ability to build extremely rich and innovative
application Developers are free to take benefit of the device hardware, access location
information, run set alarm background services, add notifications to the status bar, and
much, much more.
• Developers have full access to the same framework APIs used by the coreapplications.
The application architecture is designed to simplify the reuse of components, any
application can publish its capabilities and any other application may then make use of
those capabilities. They can also be replaced by the user.

• The set of services and systems include:


A rich and extensible set of Views that can be used to build an application, including
lists, buttons, grids, text boxes, and even an embeddable web browser.
Content Providers that allow applications to access data from other applications (such as
Contacts), or to share their own data.
A Resource Manager which provides access to non-code resources such as localized
strings, graphics, and layout files.
A Notification Manager that enables all applications to display custom alerts in thestatus
bar.
An Activity Manager the manages the lifecycle of applications and provides a common
navigation back stack.
This layer is the second layer to the application layer. It contains 10 basic components.
Following are the components this layer:
1. Activity Manager
2. Window Manager

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 17


3. View Manager
4. Contents Manager
5. Notification Manager
6. Package Manager
7. Telephone Manager
8. Resource Manager
9. Location Manager
10. XMPP service Manager

1. Activity Manager: This layer manages the lifecycle of applications and provides a common
navigation back stack.
2. Window Manager: As the name suggest it manages the window surface. Then it organithe
screen layout and locates the drawing surface and also performs other windows related jobs.
3. View Manager: Views the window.
4. Contents Manager: Enables applications access data from other applications or to their own
data.
5. Notification Manager: We get the notification from the system when the battery is tow. If the
programmer wants, he can also enable all applications to display customer alerts in the statusbar.
6. Package Manager: This manager the other packages if it is instant in the machine.
Sometimes we may download some application which is not own. This manages otherpackage.
7. Telephony Manager: Telephony manager is to handle the receiver call or voice calls.
8. Resource Manager: This manager provides access to the non-code resources(Graphics
localized string, and layout files) .
9. Location Manager: This manager helps to locate the mobile devices at which the location of
the mobile device can be searched. Ex- Map, GPS or cell tower.

10. XMPP Service Manager: Every mobile has some service like music applications, browser,
ringtones, services etc. It is managed by service manager.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 18


Linux Kernel:
The basic layer is the Linux kernel. The entire Android OS is built on top of the Linux 26
Kernel with the architectural changes made by Google.
Here it uses Linux kernel for the process and the version is 2.6.
It is highly trusted for years together for giving security giving better and networking etc.
This layer has 10 major components which was are nothing but drivers.
Android run time gives Dex file which converted from the class file. dex file goes to the
Linux kernel and call the suitable drivers so that it can communicate with the
corresponding drivers.
Following are the drivers:
Display driver
Camera driver
Bluetooth driver
Flash memory driver
Binder driver(IPS)
USB driver
Wi-Fi driver
Keypad driver
Audio driver
Power management driver

Libraries:
The 3 layer of android architecture is the libraries layer. The color of this layer is green; it
means it is written in C and C++ libraries.
This layer contents 9 components. This layer is communicated through application
framework layer. The communication happens through the Java Native Interface(JNI)
package.
This package of Java is represented for communication C and C++ language.
Following are the 9 major components:
Surface Manager
Open GLIES
SQLite database
Media Framework
SGL(Scalable graphics libraries)
Free Type
SSL (Secured socket layer)
Web kit
lib c(C libraries)

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 19


Surface Manager: We have seen in the application framework for following manager:
1. Activity manager
2. Window manager
3. View system manager
It gives a frame, button, text field etc
If we are setting the size for the frame, button, image (2D, 3D),
We have to interact with this manager called as surface manager.
This component handles all the surfaces rendered by each component of the frame.

Open GLIES: This component provides mostly 3D graphics libraries which have to be
implemented by Java application and it is rended by the application layer when they want some
3D graphics:

SQLite: When our application wants to connect the database then we can think of some popular
RDBMS like mySQL, Oracle. But they are heavy weight database server as our applications are
light weight. So it is better to have light weight RDBMS.
So we can use SQLite which is an open source RDBMS. It is not exactly tiewith
android.
We can also use file system to store the data.

Media Framework: When we are using any mobile set, what comes our mind are
Picture quality should be good.
Multimedia action should good which include the sounds
So to get those activities or application Android API has to call the media framework
component to play and view the video-audio.

SGL (Scalable graphics libraries): It is responsible for implementing low level graphics by
using JNI.

Free type: It is the responsible for to support the font quality, the image (bitmapimages).
SSL (Secured socket layer): It stands for secure socket layer. It is mostly used in internal
application. Suppose online through mobile we want to access our online through mobile then at
that time we need some secure socket layer. It is also required in case of chat and message.
It supports http and top protocol.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 20


There are some s/w company are available which are providing some 3 party s/w to make
layer more secured and those s/w are:
Cyber cash
Gauntlet

Webkit: It is responsible for giving the browser supports. It also support well to following s/w-
• Google Chromes
• Apple Safari
• It also supports JavaScript, jQuery, HTML, CSS. Ajax

Lib c: It stands for C libraries When we want to access some code C libraries headers then this
components is useful.

Android Runtime:
• Android Runtime consists of Dalvik Virtual Machine and Core Libraries.

DVM(Dalvik Virtual Machine)


• It is a type of JVM used in android devices to run apps and is optimized for low
processing power and low memory environments.
• Unlike the JVM, the Dalvik Virtual Machine does not run class files, instead it runs dex
files. dex files are built from class file at the time of compilation and provide higher
efficiency in low resource environments .
• The DVM allows memory management, security, isolation, and threading support. It is
also developed by Dan Bornstein of Google.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 21


Core libraries:
These are different from Java SE and Java ME libraries. But these libraries provide most of the
functionalities defined in the Java SE libraries.
Data Structure
Network Access
Utilities
Graphics

Linux Kernel:
It is the heart of android architecture that exists at the root of android architecture. Linux kernel
is responsible for device drivers, power management, memory management, device management
and resource access.

Dalvik Virtual Machine:


• Google selected Java as the language for developing Android applications, thereby, it got
away with both JME and the JVM in favour of an alternative deployment target, the
Dalvik virtual machine. Google have also chosen to use an alternative and limited
implementation of the standard Java libraries. Both of these are unusual Java, and
effectively represent fork of the Java platform.
• The key figure in Google's implementation of JVM is Dan Bomstein, who has writtenthe
Dalvik VM-Dalvik is the name of a town in Iceland. Dalvik VM takes the generated Java
class files and combines them into one or more Dalvik Executable (dex) files. It reuses
duplicate information from numerous class files, effectively reducing the gaps
requirement (uncompressed) by half from a traditional jar file.
• Android uses the Dulvik virtual machine with just-during-time compilation to run Dalvik
bytecode, which is frequently translated from Java byte code. Google has also fine-tuned
the garbage collection in the Dalvik VM, but it has chosen to remove just-in-time()
complier, in early releases. Android 23 has added JIT.
• Dalvik VM uses a different kind of assembly-code generation, in which it usesregisters
as the primary units of data storage instead of the stack Google expects to accomplish
30% lesser instructions as a result. The Dalvik VM relies on the Linux kernel for
underlying functionality such as threading and low-level memory management.
• We must remember that the final executable code in Android.as a result of the Dalvik
VM, is based not on Java byte code but on dex files instead. This means you cannot
directly execute lava byte code; you have to start with Java class files and then convert
them to linkable dex files.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 22


This performance is extended into the rest of the Android SDK. For example, the
Android SDK uses XML extensively to define Ul layouts. However, all of this XML is
complied to binary files before these binary files become resident on the devices. Android
provides special mechanisms to use this XML data.
• Android programs are compiled into .dex (Dalvik Executable) files, which are inturn
zipped into single .apk file on the device des files can be created by automatically
translating complied applications written in the lava programming language.
• The Dalvik Debug Monitor Service (DDMS) is a key debugging utility that isintegrated
into the Eclip IDE, the feviured development environment for Android apps.
• The Android uses a particular virtual machine, i.e. the Dalvik Virtual Machine to run
Java base applications. Dalvik is a vital part of Android, which is normally used on
mobile devices such as mobile phones and tablet computers, embedded devices for
example smart TVs and media streamers etc. Dalvik uses an own byte code format.
Dalvik byte code which is different from Jay byte code. So java class files can not
directly run on Android, they need to get converted in the Dalvik byte code format which
is compiled by the Dex compiler.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 23


Unit 2: Installation and configuration of android

Topics and Sub-Topics:

2.1 Operating system, Java JDK, Android SDK


2.2 Android Development Tools(ADT)
2.3 Android Virtual Devices (AVDs)
2.4 Emulators
2.5 DVM difference between JVM and DVM
2.6 steps to install and configure android studio and SDK

G. P. CO6I [MAD-22617] 24
MIRAJ ( S.
B.
SHINTRE )
2.1 Operating system, Java JDK, Android SDK

Operating system

ToDevelop anandroidprogram thenecessaryoperation systemusedin


computer as follow.

MAC
• MOCOS X(Intel) 10.5.8(X 86only)

Windows
• Window XP(32bit)
• Vista(32/64bit)
• Window 7(32/64bit)

Linux (i 386 : tested in Lucid Lynx, Ubuntu Linux)


• GNC c Library (glibc) or later is required
• On Ubuntu Linux, version 8.04 or later is required
• 64-bit distribution should be capable of running 32-bit application

Android JDK(Java Development Kit)

o As Android program are developed in java programming language we have Java


Development Kit(JDK) incomputer whichisfree software where JDK include the
Java SE runtime(JRE)
o The JDK is development environment for building applications, applets and
components using Java Programming Language.
o The JDK issoftwarepackagethatcontainsavarietyoftoolsandutilities that makeit
possibletodeveloppackage,monitoranddeployapplicationsthat buildforany
standard Java platform.

Android SDK(Software Development Kit)

The Android SDK(software Development Kit) is the mostimportant software of android


which isinstalled
The Android SDK provides to test android application the API libraries.
o an Emulator
o Documentation
o sample code
o developer tools
o tutorials

G. P. CO6I [MAD-22617] 25
MIRAJ ( S.
B.
SHINTRE )
Which as help you to build, test and debug apps of android.
Android SDK can be downloaded from http://developer.android.com/SDK/index.html
using android SDK manager which is free.
We find the Android SDK in a zip file and have to unzip its contents(android-sdk- windows)
into folder(c:\android \folder name)
Wecan also create Android virtual Devices(SDK)which runin emulator
Android SDK is made up of 2 main parts.

• Whichyoufirstinstallthe SDK allyou


obtain are basic tool these are basic tool
Tools: thattheseareexecutableand support
that help you develop application.

• Packagesaretherecordsspecifictoa
particular version of android (called
Package: platform)orparticularadd-ontoa
platform.

Android SDK diagram

Android SDK

contains

Debugger Libraries Emulator Documentation SampleCode Tutorials

Feature of android SDK

o No licensing, distribution or development fees.


o WiFi HW access

G. P. CO6I [MAD-22617] 26
MIRAJ ( S.
B.
SHINTRE )
o GSM, EGDE and 3G network or data transfer allows you to make or receive calls or
SMSmessage. Otherwise sendandreceive data acrossmobile Network.
o Comprehensive API’s designed for location-based services such as GPS.
o Full multimedia HWcontrol together withplaybackand recordingusing camera
and microphones
o API’s designed for accelerometer and compass HW.
o IPC message passing.
o Shared data store
o An integrated open source Webkit-based browser
o Fullsupportforapplicationthatintegratemapcontrolaspartoftheiruser interface.
o Peer-to-peer(2p2) support using Google Talk
o Mobile optimized hardware accelerated graphics including a path=based 2D graphics
library and support for 3D graphics usingopen GLI ES.
o Medialibrariesdesigned for playingandrecording varietyofaudio /videoor still
image formats.
o An application framework that encourage reuse of application component and
replacement of native application.

G. P. CO6I [MAD-22617] 27
MIRAJ ( S.
B.
SHINTRE )
2.2 Android Development Tools (ADT)

Android development tools ( ADT )

o Android development tools (ADT) is plugin for Eclipse or Android Studio which
providessuitableenvironmenttodevelopanAndroidapplication.
o Due to ADT creation, compilation and debugging are possible.
o ADT can able to setup new Android projects, create an application UI, insert package
basedonandroid framework API, debug (orclear up) yourapplicationsusing
AndroidSDKtoolsandexportsignedorunsigned.apkfiles in order to distribute
applications
Android Studio
ThisistheofficialIDEforandroid,makingitnumberonechoiceforthe majorityof
developers looking to make basic apps in keeping with Google’s material designandwith
access toallthe advancedfeatures oftheplatform.
Eclipse
Following are the steps to develop application using Eclipse IDE
1. Install the JDK
2. Download and install Eclipse
3. Download and install Android SDK
4. Install the ADT plugin for Eclipse
5. Configure the ADTplugin
6. Create the AVD
7. Create the Hello World Android application

Work of ADT in android studio

1) Create a new Androidapplication


2) Compile and debug Android application
3) Create digital certificates for code-signing of APK (Android Application
Packages)
4) Create an application UI
5) Access the tools foraccessing the android emulators anddevices.

Android developer toolsbundle(ADT bundle)

o Eclipse + ADT plugin / Android Studio


o Android SDK
o Android platform-tools
o The most recent Androidplatform
o The newest Android system image for Emulator.

G. P. CO6I [MAD-22617] 28
MIRAJ ( S.
B.
SHINTRE )
Some toolsincluded
Android Debug Bridge (ADB)

AndroidStudioincludesADB,Whichisacommandlinetoolorbridgeof
communicationbetweenAndroidDevicesandothercomputersthatcan beused
duringdevelopmentandtheoveralldebuggingandQAprocess

AVD manager

TheAVDmanagerisanemulatorusedtorunandroidappsoncomputer.

Fabric

It is the development platform behind Twitter’s mobile app.

GameMaker studio

For android game app developers, oneof the mostpopular development tool is
GameMaker:Studio. It provides everything you need to create 2D games using
very little code.

IntelliJIDEA

Itis designed to maximize developer productivity. Together, intelligent coding


assistance and ergonomicdesign makedevelopmentnotonly productive but
also enjoyable

Gradle

Gradle is one of the most popular development tools for creating large scale
applications.

G. P. CO6I [MAD-22617] 29
MIRAJ ( S.
B.
SHINTRE )
2.3 Android Virtual Devices (AVDs)

Android Virtual Device(AVD)

o An Android Virtual Device (AVD) is an emulator configuration that enables to model


anactualdevicebycallinghardwareandsoftwareoptionstobe emulated bythe
Android Emulator.
o Use the AVD Manager to create an AVD launch it from eclipse by clicking
window/AVD Manager. You can also start AVD Manager bycalling
adoptions, from the <sdk>/tools/directory.
o An Android Virtual Device(AVD) isusedfortesting the Android Applications.
AnAVDisanemulatoroccurrencethatenablestoformareal device.

Things about AVD

A hardwareprofile:
• Definesthehardwarefeaturesofthevirtualdevice. Forexample.Youcandescribe whetherthe
devicehasacamerawhetheritusesaphysicalQWERTYKeyboardora dialing pad, now
much memory it have and so on

A mapping to a system image:


• YoucandefinewhatversionoftheAndroidplatformwillrunonthevirtual machine. You
willbeabletochooseaversionofthestandardAndroidplatformor the system image
packaged with an SDK add-on.
• You can specify the emulator skin you want to use with the AVD, which lets you to control the
screen dimensions, look, and so on You can also specify the emulated SD card to use with
the AVD

Adedicatedstorageareaonyourdevelopmentmachine:
• Thedevice'suserdata(installedapplicationssettings,andsoon)anemulatedSD card are
stored in this area.

WhileselectinganimageforAVD.,refertothebelowpoints:
• The API Level of the goal is important. because our application will not be able to run on a
systemasspecifiedintheminsdkVersion attributeofthemanifestfileof that application.
• CreateatleastoneAVDthatusesatarget whoseAPILevelisgreaterthanthat required by
our application. The downloaded application compatibility of users receive a system update
and normally it will continue to function which is ensured by forward – Compatibility (because
itallowsusto test the forward - compatibility of our application).

G. P. CO6I [MAD-22617] 30
MIRAJ ( S.
B.
SHINTRE )
Android AVDdiagram

Create and manage virtual devices

To open AVD Manager, do one of the following:

• Selecttools AVDManager.ClickAVDManager,AVD
Manager icon in the toolbar

G. P. CO6I [MAD-22617] 31
MIRAJ ( S.
B.
SHINTRE )
• Nowclickthe+CreateVirtualDevice…button.Thiswill bring
upVirtualDeviceConfigurationDialog.

• Selectanydeviceyouwant,thenclickNext.

G. P. CO6I [MAD-22617] 32
MIRAJ ( S.
B.
SHINTRE )
• ChooseAndroid Version,thenclick Next.

• Enter a name foryour emulator,initial orientation, and other


specifications,then click Finish.

G. P. CO6I [MAD-22617] 33
MIRAJ ( S.
B.
SHINTRE )
• NowyouhavegotanewAVDreadyforlaunchingyour
apps on it.

G. P. CO6I [MAD-22617] 34
MIRAJ ( S.
B.
SHINTRE )
2.4 Emulators

Emulators

o AndroidEmulatorsareresponsibleforrunning,debuggingandtestingthe Android
application
o The AndroidemulatorsimulatesAndroiddevicesonyourcomputersothat can test
your application on a variety of devices and Android API levels without needing to
have each physical device.
o The emulator provides almost all of the capabilities ofa realandroid device. Youcan
simulate incoming phone calls, and text messages, specify location of device, simulate
different network speeds, simulate rotation and other hardwaresensors, access
the google play store and much more.
o The Android SDK comes with a virtual mobile device emulator that runs on the
computer.
o TheAndroidemulatormimicsallthehardware andsoftwarefeaturesof typical
mobiledevices,exceptthatitcannotplaceannualphonecalls
o It provides a selection of navigation and control keys which we can press using a
mouseorinputfromkeyboardtogenerateeventsandperformactions respectively.
o It runs onacomplete Android system stack down to the kernel level
o We can selectversionofandroidsystem wewish torunin the emulatorby
configuring the AVDs
o We canalso modifythe deviceskin and keymappingsaccording toour
convenience
o Whilelaunchingtheemulatoratruntime,wecanuseavarietyofcommands and
options to control its behavior.

Theandroidemulatorsupportsmanyhardwarefeatureslikelytobe found on
mobile devices including

o An ARMv5 CPUand thecorresponding memory managementunit (MMU).


o A 16 bit LCDdisplay
o Oneormorekeyboards(AQWERTYbased keyboardandassociateddialpad
/phone buttons)
o A sound chip among output and input capabilities
o Flash memory partitions
o A GSM modem, including a simulated SIM card
o A camera, using awebcamconnected toourdevelopment computer.
o Sensors like an accelerometer, using records from a USB connectedandroid device

G. P. CO6I [MAD-22617] 35
MIRAJ ( S.
B.
SHINTRE )
Requirements andrecommendations

o SDK tools 26.11 orhigher


o 64-bit processor
o Windows
o HAXM 6.2.1 orlater
o Intel processor on Windows or Linux
o AMD processor (Advanced Micro Devices)

Launch theemulator

To start the emulator:


1) Open the AVDManager
2) Double-click an AVD, or click Run
3) The Android emulator loads

Android Emulator

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 36


2.5 Dalvik Virtual Machine(DVM), difference between JVM and DVM

DVM (Dalvik virtual machine)

o Dalvik is a name of a town in Iceland.


o The Dalvik VM was written by Dan Bornstein.
o The modern JVM is high performance and provides excellent memory
management,butitneedstobeoptimizedforlow-poweredhandhelddevices aswell.
o The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for
mobile devices.
o Itoptimizesthevirtualmachineformemory, batterylifeandperformance.
o GoogleintroducedanewVirtualmachineforandroidapplicationsin2014 whichis
knownasAndroidRuntime(ART).Itisdesignedwiththepurposetoimprove
application performance and reduce device battery usage. The last supported version
for the DVM was Android 4.4(Kitkat).

Let’sseethecompilingandpackagingprocessfromthesourcefile

o Thejavactoolcompilesthejavasourcefileintotheclassfile. Thedxtool takesallthe


classfiles of your application and generates a single .dex file. Itis platform specific tool.
o TheAndroidAssetsPackagingTool(AAPT)handlesthepackagingprocess.

G. P. CO6I [MAD-22617] 37
MIRAJ ( S.
B.
SHINTRE )
o And generates .apk executablefile.

Difference between JVM and DVM

JV DVM

• JVMstandsforJava VirtualMachine • DVMstandsforDalvikVirtualMachine

• It compiles Java Bytecode • It compiles Dalvik Bytecode

• Itformsseparateclassesinseparate • Itforms multiple class in one.dex


.class bytecode file bytecode file

• JVM is based on stack based virtual • DVMis based on register basedvirtual


machine architecture machine architecture

• TheexecutableformatofJVMisJAR • TheexecutableformatofDVMisAPK

• It runs on morememory. • It runs on less memory.

• JVMsupports multiple Operating • DVMsupports only Android Operating


System System

• JVMruns .classbytecodedirectly. • The.classbytecodesareoptimizedto


.dex format before executing in DVM
• It has different constant pools.
• It has commonconstant pool

G. P. CO6I [MAD-22617] 38
MIRAJ ( S.
B.
SHINTRE )
2.6 Stepstoinstallandconfigureandroidstudioand SDK

System requirements for android studio

Windows MAC Linux


• Microsoft® Windows® • Mac® OS X® 10.10 • GNOME or KDE
7/8/10 (64-bit) (Yosemite) or higher, up to desktopTested on
• 4 GB RAM minimum, 8 GB 10.14(macOSMojave) gLinux based on
RAMrecommended • 4 GB RAM minimum, 8 GB Debian.
• 2GB ofavailable disk RAMrecommended • 64-bit distribution
spaceminimum, • 2GB ofavailable disk capableofrunning32-bit 4
GB Recommended (500 spaceminimum, applications
MB for IDE + 1.5 GB for 4 GB Recommended (500 • GNUCLibrary(glibc)2.19 or
AndroidSDK and emulator MB for IDE + 1.5 GB for later
system image) Android SDKand emulator • 4 GBRAM minimum, 8 GB
• 1280x800minimum system image) RAM recommended
screenresolution • 1280x800minimum • 2GB ofavailable disk
screenresolution spaceminimum,
4 GB Recommended (500
MB for IDE + 1.5 GB for
AndroidSDK and emulator
system image)
• 1280x800minimum
screenresolution

G. P. CO6I [MAD-22617] 39
MIRAJ ( S.
B.
SHINTRE )
Steps to install android studio

Goto officialsiteand downloadit.

Run asAdministrator

G. P. CO6I [MAD-22617] 40
MIRAJ ( S.
B.
SHINTRE )
SelectandroidvirtualdeviceGoto
next

Select installation path

G. P. CO6I [MAD-22617] 41
MIRAJ ( S.
B.
SHINTRE )
Click oninstall

Installation in progress

G. P. CO6I [MAD-22617] 42
MIRAJ ( S.
B.
SHINTRE )
Click onfinish

Welcome screen

G. P. CO6I [MAD-22617] 43
MIRAJ ( S.
B.
SHINTRE )
Selectinstallationtype

Select uitheme

G. P. CO6I [MAD-22617] 44
MIRAJ ( S.
B.
SHINTRE )
Confirmationwizard

Downloadandsetupenvironment
automatically

G. P. CO6I [MAD-22617] 45
MIRAJ ( S.
B.
SHINTRE )
Steps to configure android SDK

Click on SDK Manager

SelectdesierdSDKPlatform

G. P. CO6I [MAD-22617] 46
MIRAJ ( S.
B.
SHINTRE )
Install all SDk tools

G. P. CO6I [MAD-22617] 47
MIRAJ ( S.
B.
SHINTRE )
Ch.3: UI Components and Layouts

Syllabus:

3.1 Control flow


3.2 Directory Structure
3.3Components ofascreen
3.4 Fundamental UIDesign
3.5 UI layouts:
Linear Layout; Absolute Layout;FrameLayout;Table
Layout; Relative Layout

G. P. CO6I [MAD-22617] 48
MIRAJ ( S.
B.
SHINTRE )
3.1 Control flow

The steps in control flow of an android application is given below

Step 1 : Click on Android Studio icon

Step 2 : Select File -> New-> New Project

Step 3 : Give the Project Name

G. P. CO6I [MAD-22617] 49
MIRAJ ( S.
B.
SHINTRE )
Step 4 : Select your SDK to and click next Target Android Device

G. P. CO6I [MAD-22617] 50
MIRAJ ( S.
B.
SHINTRE )
Step5:Toaddtheprojectunmobileselecttheproperactivityhereweselecttheempty activityand
click Next

Step 6 : Give the activity name and click Finish

The differ components of UI just split the Android windo into parts and give some numbering

Menu Bar : Menu Bar contains the drop-down menus to perform different functions.

Toolbar: Toolbar contains graphical view of some commonly usable buttons.

Navigation Bar: Navigation Bar shows the selected file hierarchy which helps developer to directly
navigate to the parent directories of the file or switchbetween different files.

G. P. CO6I [MAD-22617] 51
MIRAJ ( S.
B.
SHINTRE )
Tool Buttons Bar: Tools Buttons bar allows to switch between different tools in different windows
(Project Tool, Preview, Console Windows).

Project Tool Window: There are three project tool windows in the interface which allows developer to
use indifferent ways. Project ToolWindowin theleft sideallows developer tonavigate through allthe
tools provided in the left side Tool Buttons such as Project hierarchy view, Favourites. Structure view
etc.Right side Project Tool Window allows to navigate between the right Tool Buttons like Application
Interface Preview ondifferent devices, Gradlefunctions etc. Bottom Project ToolWindowallows to
navigate between the bottom Tool Buttons like Terminal, Run. Android etc.

EditorWindow:Editorwindowopentheselectedfiletoallowsdevelopertoeditthemasperthe
requirements.

Status Bar: The status bar displays informational messages about the project and the activities of
Android Studio. It also contain a button in the left corner which lists all the tools menu button.
Hovering over items or button in thestatus bar will provide a description of that field.

G. P. CO6I [MAD-22617] 52
MIRAJ ( S.
B.
SHINTRE )
3.2 Directory Structure:
Here a new Android project application is created.

There are various files that form an Android project in the Package Explorer in eclipse. The various
Folders and their files are as follows:

STC: This folder contains the java source files for the project .In this example, there is one file
AndroidProjectActivity.java .The AndroidProject Activity. java. is the source file for the activity. we
write the code for this application in thisjava file. The java file is listed under the package name ie.
com.pkg. Example for the project.

gen: This folder contains the R.java file, which is generated by the compilerthat references all the
resources found in this project. We cannot modifythis File. All the resources in thisproject are
automatically compiled into this class hence we can transfer to them using the class.

Android 2.2 libraries: This thing contains one file, android.jar, whichcontainsall the class libraries
needed for an Android Application.

Assets: Folder contains all the resources used by this application, such asHTMLtext files, databases, etc.

Bin: This folder contains the Files built by the ADT during the CompilationItgenerates the .apkfile. An
.apkfile is the application binary of an Androidapplication. It contains the entire things needed to run
an android application

Res: This folder contains all the resources files such as pictures, XML filesfordefining layout used in this
application.

Android Manifest.xml: This is the manifest file for this Android project Itcontains information about the
Android application such as minimum Android version, permission to access Android device
capabilities such as internet access permission, ability to use phone permission,etc..

Main.xml: The main.xml file defines the user interface for activity

Layout: contains XML layout files, Layout files are XML files which definehowvarious Android objects
are organized on the screen.

Values: XML Files which stores various string values (titles, labels,etc)

G. P. CO6I [MAD-22617] 53
MIRAJ ( S.
B.
SHINTRE )
3.3 Component of a screen & Fundamentals UI Design:
Component of a screen

An activity displays the user interface of our application, which may contain widgets like buttons,
Image buttons, text boxes, labels.etc. Typically, you define your UI using an xml file (for example,
activity_main.xml file located in the res then inside afolder called layout) which may look like

This:

activity-main.xml

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

<LinearLayout xmlns:android:"http://schemat android com/apk/resandroid”

android: orientation "vertical" android:layout_width="fill_parent” android layout _height:


"fill_parent">

<TextView

android:layout_ width: "fill_parent" android:layout_height:" wrap_content" android: text-"@String


/Hello"/>

</LinearLayout>

During this runtime, we can load the xml UI in the onCreate() event handler in our Activity class, using
The setContentView() method of the Activity class.

@Override

public void onCreate (Bundle saved Instancestate) {

Super.onCreate (saved InstanceState); setContentView LR. Layout main).

During compilation time, each element in the XMLfile is compiled into its equivalent Android GUI
Class, with an attribute represented by methods The android system then Creates the user Interface
(UI) of the Activity when it is loaded

G. P. CO6I [MAD-22617] 54
MIRAJ ( S.
B.
SHINTRE )
3.4 Fundamentals UI Design:

Every item in auser interface is a subclass of the Android View Class which is present inside the
package (android.view)The Android SDK provider a can be used to set of pre-built views that can be
used to construct a user. Interface

Views:

Views are the base class for all visual interface elements.

UI controls, including the layout classer, are derived from view.

Examples of widgets are button, text boxer, labels, etc.

View Groups:

View Groups are extensions of the view class that can contain multiple Child views, In order to Extend
the View Group class to create compound controls made up of interconnected ChildViews

The View Group class is also extended to provide the layoutmanager that help us to control layout
withinouractivitiesA View Group provides the layout in which we can order the appearanceand
sequence of views.

Examples of View Groups are LinearLayout, Frame Layout,etc.

Fragments:

Fragments represents a portion of user interface in an activity

Fragments, introduced in Android 3.0 which uses APF Level 11 are used to encapsulate portions of our
UI

Fragments are Similar to UI view controller iPhone development

Activities

Activities dictate the UI and handle the user interaction to the smart phone screen.

Activities represent a single screen that user interact

Activities are the Android equivalent of Forms in traditional windows desktop development

To display a UI we assign a View (usually a layout or fragment) to an activity

G. P. CO6I [MAD-22617] 55
MIRAJ ( S.
B.
SHINTRE )
3.5 Linear Layout; Absolute Layout; Frame Layout; Table Layout; Relative Layout

UI layouts :

Alayout definesthestructureforaUserInterface intheapplication.

Layouts in android are very important for GUI based apps.

Therearenumbersof layoutsprovidedbyandroid which we willuse in almostall theandroid

applications to provide different view, look and feel.

All elements in the layout are built using a hierarchy of View and View Group
objects.

A View usually draws something the user can see and interact with.

Whereas A View Group is an invisible container that defines the layout structure for View and other

View Group objects

Hierarchy: View -> Viewgroup -> Layouts

You can declare a layout in two ways:

Declare UI elements in XML / XML layout resources

Programmatically in the applications Java code

There 5 types of layout mentioned in our syllabus are as follows:

1.Linear Layout

2.Absolute Layout

3.Frame Layout

4.Table Layout

5.Relative Layout

G. P. CO6I [MAD-22617] 56
MIRAJ ( S.
B.
SHINTRE )
1. Linear Layout:
Android Linear Layout is a view group that aligns, all children in either vertically or horizontally.Linear
Layoutissimpleandeasytouse,itcreatesascrollbar,ifthelengthof thewindowexceedsthelength
of the screen.Linear Layout are one of the simplest and common type of layouts used by
androiddevelopers to keepcontrols within theirinterfaces.The linear layout works asmuch as its
name implies, it organizes the controls either a verticalor horizontal pattern.

Example :

Fig: Horizontal Pattern Fig: Vertical Pattern

Linear layout can be defined within XML layout resources or programmatically in the applications Java
code.

The linear layout’s orientation is set to be vertical, causing each of the

view controls to display in single column from top to bottom.

Attributes of Linear Layout:

ID : Unique identifier of layout

Orientation : Attribute to set linear layout orientation as vertical or horizontal

Linear_weight: This attribute assigns “Importance” valueateach component

G. P. CO6I [MAD-22617] 57
MIRAJ ( S.
B.
SHINTRE )
Layout_width : Used to set the width of the given control. This property has following options:-

wrap_content andmatch_parent
Layout_height : Used to set the height of the given control. This property has following options:-
wrap_content andmatch_parent

Gravity : This attribute shows object position in x-y plan

Divider : This is drawable touseasavertical dividerbetween

Buttons: Youusea colorvalue in theformof “#rgb”, “#rrggbb”.

Constructors of Linear Layout:

LinearLayout(context context)

LinearLayout(context context, Attributes atrs)

LinearLayout(context context, Attributes atrs, int styleAttribute)

LinearLayout(context context, Attributes atrs, int styleAttribute, int styleRes)

Program :

activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" >

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name : John || "
android:textColor="@color/black"/>

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Marks : 92%"
android:textColor="@color/black”/>
</LinearLayout>

MainActivity.java

G. P. CO6I [MAD-22617] 58
MIRAJ ( S.
B.
SHINTRE )
package com.example.exp4_exefcise_que2;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle;
public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Output :

G. P. CO6I [MAD-22617] 59
MIRAJ ( S.
B.
SHINTRE )
2. Absolute Layout:
Absolute layout is based on the simple idea of placing each control at an absolute position.

We specify for the exact x and y co-ordinates on the screen for every control.Absolute layout is less
flexible.It is harder to maintain than other types of layouts without absolute positioning.

Example :

(15,25)

(80,50)

Fig : Absolute Layout Patter

Attributes of Linear Layout:

ID : Unique identifier of layout

Linear_weight: This attribute assigns “Importance” valueateach

component

Layout_width : Used to set the width of the given control. This property has following options:-
wrap_content andmatch_parent

Layout_height : Used to set the height of the given control. This property has following options:-
wrap_content andmatch_parent

G. P. CO6I [MAD-22617] 60
MIRAJ ( S.
B.
SHINTRE )
Layout_x: Componentadded at given xposition

Layout_y: Component added at given yposition

Constructors of absolute layout :

AbsoluteLayout(context context)

AbsoluteLayout(context context, Attributes atrs)

AbsoluteLayout(context context, Attributes atrs, int defStyleAttr)

AbsoluteLayout(context context, Attributes atrs, int defStyleAttr, int defStyleRes)

Program :

activity_main.xml

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

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".MainActivity">

<TextView android:layout_width="wrap_content" android:layout_height="39dp"


android:layout_x="64dp" android:layout_y="60dp" android:text="Name || Age || Mobile
Number" android:textColor="@color/black" android:textSize="20dp"/>

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:layout_x="64dp" android:layout_y="95dp" android:text="Rahul || 18 || 9234567891"
android:textColor="@color/black" android:textSize="20dp" />

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:layout_x="64dp" android:layout_y="129dp" android:text="Ritika || 20 ||
9278923456" android:textColor="@color/black" android:textSize="20dp" />

G. P. CO6I [MAD-22617] 61
MIRAJ ( S.
B.
SHINTRE )
</AbsoluteLayout>
MainActivity.java

package com.example.exp5_exercise_que2;

importandroid.support.v7.app.AppCompatActivity; importandroid.os.Bundle;

public class MainActivity extends AppCompatActivity { @Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);


setContentView(R.layout.activity_main);

Output :

G. P. CO6I [MAD-22617] 62
MIRAJ ( S.
B.
SHINTRE )
3. Frame Layout:

The purpose of the frame layout is to allocate an area of screen. Frame layout is used for displaying a
single view.Generally, frame layout should beused tohold a single child view, because it can be
difficult to organize child views in awaythat’s scalable to different screen size without the children
overlapping each other.

Attributes of frame layout :

android:id – This is the ID which uniquely identifies thelayout

android:foreground – This defines the drawable to draw over the content and possible values may be
a

color value, in the form of “#rgb”, “#argb”, “#rrggbb”.

android:foregroundgravity – Defines the gravity to apply to the foreground drawable.

The gravity defaults to fill

android:measureAllChildren – Determines wherther to measure all children or just those

in the VISIBLE or INVISIBLE state when measuring. Defaults to false.

Constructors of frame layout :

FrameLayout(context context)

FrameLayout(context context, AttributeSet attrs)

FrameLayout(Context context, AttibuteSet attrs, int defStyleAttr)

FrameLayout(Context context, AttibuteSet attrs, int defStyleAttr, int defStyleRes)

Program :

activity_main.xml

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

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"

tools:context=".MainActivity">

G. P. CO6I [MAD-22617] 63
MIRAJ ( S.
B.
SHINTRE )
<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Data types in Object Oriented Programming" android:layout_marginTop="12dp"

android:layout_marginLeft="15dp"

android:textSize="17dp"

android:textStyle="bold" android:textColor="@color/black"/>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Integer"

android:textColor="@color/black"

android:textSize="15dp"

android:layout_marginLeft="15dp"

android:layout_marginTop="80dp”/>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content" a

ndroid:textColor="@color/black"

android:text="Float"

android:textSize="15dp"

android:layout_marginLeft="15dp"

android:layout_marginTop="110dp"

/>

G. P. CO6I [MAD-22617] 64
MIRAJ ( S.
B.
SHINTRE )
</FrameLayout>

MainActivity.java

package com.example.exp6_exercise_que2;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle;

public class MainActivity extends AppCompatActivity { @Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);


setContentView(R.layout.activity_main);

Output

G. P. CO6I [MAD-22617] 65
MIRAJ ( S.
B.
SHINTRE )
4. Table Layout:

The table layout groups views into rows and columns.

It can be declared as:

<TableLayout xmlns:android=http://schemas.android.com/apk/res/android
android:layout_width="match_parent"
android:layout_height="match_parent"
<TableRow>
<TextView
android:text="Name"
android:textSize="23dp"
/>

<TextView
android:text="Marks"
android:textSize="23dp"
/>
</TableRow>
</TableLayout>

Android table layout going to be arranged groups of views into rows and columns.

You will use the <TableRow> element to build a row in the table.

Each row has zero or more cells; each cell can hold one view object. Table layout
containers do not display border lines for their rows, columns, or cells.

G. P. CO6I [MAD-22617] 66
MIRAJ ( S.
B.
SHINTRE )
Example:

Row 1

Row_2 Row_2 Row_2

Col_1 Col_2 Col_3

Row_ Row_
3 3
Col_1 Col_2

Fig : Table Layout

G. P. CO6I [MAD-22617] 67
MIRAJ ( S.
B.
SHINTRE )
Attributes of table layout:

1. android:id : This is the ID which uniquely identifies the layout.


2. android:collapseColumns : This specifies the zero-based index of the columns to
collapse.

Constructors of table layout :

1. TableLayout(context context)
Creates a new TableLayout for the given

2. contextTableLayout(context context, Attributes attrs)


Creates anew TableLayout for the given context and with the specified set sttributes

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

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"

tools:context=".MainActivity">

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Name"

android:textStyle="bold"

android:textSize="23dp"

android:layout_marginLeft="8dp”/>

<TextView

G. P. CO6I [MAD-22617] 68
MIRAJ ( S.
B.
SHINTRE )
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Marks"

android:textStyle="bold"

android:textSize="23dp"

android:layout_marginLeft="8dp”/>

</TableRow>
<TableRow>

<TextView

android:text="Rutuja"

android:textSize="14dp"

android:layout_marginLeft="8dp"/>

<TextView

android:text="88"

android:textSize="14dp"

android:layout_marginLeft="8dp"/>

</TableRow>

<TableRow>

<TextView

android:text="Aryan"

android:textSize="14dp"

android:layout_marginLeft="8dp"/>

<TextView android:text="94"

android:textSize="14dp"

android:layout_marginLeft="8dp"/>

</TableRow>

G. P. CO6I [MAD-22617] 69
MIRAJ ( S.
B.
SHINTRE )
</TableLayout>

MainActivity.java

package com.example.exp6_exercise_que1;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle;

public class MainActivity extends AppCompatActivity { @Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);


setContentView(R.layout.activity_main);

} }

Output :

G. P. CO6I [MAD-22617] 70
MIRAJ ( S.
B.
SHINTRE )
5. Relative Layout:

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

It can be declared like this.

It can be declared as:

<RelativeLayout

android:d=”@+id/RLayout” android:layout_width=”fill_parent” android:layout_height=”fill_parent”

</RelativeLayout>

The position of each view can be specified as relative to sibling elements or relative to the present.

Example:

Fig : Relative Layout

Attributes of relative layout:

1) Android:id

G. P. CO6I [MAD-22617] 71
MIRAJ ( S.
B.
SHINTRE )
2) Android:gravity

3) Android:ignoreGravity

4) Android:layout_above

5) Android:layout_alignBottom

6) Android:layout_alignLeft

7) Android:layout_alignParentBottom

8) Android:layout_alignParentEnd

9) Android:layout_alignParentLeft 10.Android:layout_alignParentRIght

10) Android:layout_alignParentStart 12.Android:layout_alignPrentTop

11) Android:layout_alignRight 14.Android:layout_alignShort 15.Android:layout_alignTop

1) Constructors of Relative Layout :


2) RelativeLayout(context context)
3) RelativeLayout(context context, Attributes attrs)
4) RelativeLayout(context context, Attributes attrs, int defStyleAttr)
5) RelativeLayout(context context,Attributes attrs,intdefStyleAttr, int defStyleRes)

Program activity_main.xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

G. P. CO6I [MAD-22617] 72
MIRAJ ( S.
B.
SHINTRE )
android:text="BLUE"

android:textSize="10dp"

android:layout_alignParentTop="true”/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="RED"

android:textSize="10dp"

android:layout_alignParentBottom="true”/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="GREEN"

android:textSize="10dp"

android:layout_alignParentRight="true"

android:layout_centerVertical="true"/>

</RelativeLayout>

MainActivity.java

package com.example.exp6_extraque;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle;

public class MainActivity extends AppCompatActivity { @Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);


setContentView(R.layout.activity_main);

Output :

G. P. CO6I [MAD-22617] 73
MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 74
MIRAJ ( S.
B.
SHINTRE )
Extra Programs related to Layouts
1.LinearLayout:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#93FF18"
android:orientation="vertical">

<TextView
android:id="@+id/student_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NAME : AROHI AJAY PATEL"
android:textSize="25dp"
android:textColor="#0023FF"
android:layout_marginTop="100dp"
android:layout_gravity="center"
android:textStyle="bold|italic"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AGE : 24"
android:textSize="25dp"
android:textColor="#FF5722"

android:layout_gravity="center"
android:layout_marginTop="50dp"
android:textStyle="bold|italic"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOBILE NUMBER : 9999988888"
android:textSize="25dp"
android:textColor="#0A5A0D"

G. P. CO6I [MAD-22617] 75
MIRAJ ( S.
B.
SHINTRE )
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:textStyle="bold|italic"/>

</LinearLayout>

Output:

G. P. CO6I [MAD-22617] 76
MIRAJ ( S.
B.
SHINTRE )
2..LinearLayout:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#ffffb3"

tools:context=".MainActivity">

<TextView

android:layout_width="360dp"

android:layout_height="55dp"

android:layout_gravity="center"

android:layout_marginTop="50dp"

android:text=" LOGIN PANEL"

android:textAppearance="@style/TextAppearance.AppCompat.Display3"

android:textColor="@color/colorAccent"

android:textSize="40dp" />

<TextViewandroid:layout_width="match_parent

" android:layout_gravity="bottom"

android:layout_height="30dp"

android:layout_marginTop="50dp"

android:text=" USERNAME: "

android:textColor="#669999" />

G. P. CO6I [MAD-22617] 77
MIRAJ ( S.
B.
SHINTRE )
<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:id="@+id/t1"

/>

<TextView

android:layout_width="match_parent"

android:layout_gravity="bottom"

android:layout_height="30dp"

android:layout_marginTop="20dp"

android:text=" PASSWORD:"

android:textColor="#669999" />

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:id="@+id/t2"/>

<Button

android:id="@+id/b1"

android:layout_width="230dp"

android:layout_height="60dp"

android:layout_gravity="center"

android:backgroundTint="#ffcc00"

android:onClick="submit1"

android:text="Submit"

G. P. CO6I [MAD-22617] 78
MIRAJ ( S.
B.
SHINTRE )
android:textAppearance="@style/TextAppearance.AppCompat.Display1"

android:textColor="#001a00"

android:textSize="30dp"

android:layout_marginTop="20dp"

android:background="@drawable/rounded_corners"

android:visibility="visible"

/>

</LinearLayout>

Output:

G. P. CO6I [MAD-22617] 79
MIRAJ ( S.
B.
SHINTRE )
3. Absolute Layout

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

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_gravity="center"

android:background="@drawable/wallpaper"

tools:context=".MainActivity">

<TextView

android:id="@+id/textView"

android:layout_width="59dp"

android:layout_height="63dp"

android:layout_x="293dp"

android:layout_y="74dp"

android:text="05"

android:textColor="#000000"

android:textSize="50dp" />

<TextView

android:id="@+id/textView2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

G. P. CO6I [MAD-22617] 80
MIRAJ ( S.
B.
SHINTRE )
android:layout_x="292dp"

android:layout_y="124dp"

android:text="48"

android:textColor="#000000"

android:textSize="50dp"

/>

<TextView

android:id="@+id/textView3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_x="310dp"

android:layout_y="190dp"

android:text="PM"

android:textColor="#000000" />

<ImageView

android:id="@+id/imageView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_x="8dp"

android:layout_y="645dp"

app:srcCompat="@android:drawable/ic_menu_call" />

<ImageView

android:id="@+id/imageView2"

G. P. CO6I [MAD-22617] 81
MIRAJ ( S.
B.
SHINTRE )
android:layout_width="53dp"

android:layout_height="45dp"

android:layout_x="363dp"

android:layout_y="633dp"

app:srcCompat="@android:drawable/ic_menu_camera" />

<ImageView

android:id="@+id/imageView3"

android:layout_width="49dp"

android:layout_height="39dp"

android:layout_x="282dp"

android:layout_y="307dp"

app:srcCompat="@drawable/fb" /

<ImageView

android:id="@+id/imageView4"

android:layout_width="48dp"

android:layout_height="37dp"

android:layout_x="216dp"

android:layout_y="356dp"

app:srcCompat="@drawable/chrome" />

<ImageView

android:id="@+id/imageView6"

android:layout_width="51dp"

android:layout_height="40dp"

G. P. CO6I [MAD-22617] 82
MIRAJ ( S.
B.
SHINTRE )
android:layout_x="341dp"

android:layout_y="357dp"

app:srcCompat="@drawable/twitter" />

<ImageView

android:id="@+id/imageView7"

android:layout_width="47dp"

android:layout_height="39dp"

android:layout_x="281dp"

android:layout_y="394dp"

app:srcCompat="@drawable/whatsapp" />

<ImageView

android:id="@+id/imageView8"

android:layout_width="66dp"

android:layout_height="48dp"

android:layout_x="209dp"

android:layout_y="436dp"

app:srcCompat="@drawable/instagram" />

<ImageView

android:id="@+id/imageView9"

android:layout_width="46dp"

android:layout_height="41dp"

android:layout_x="345dp"

android:layout_y="439dp"

G. P. CO6I [MAD-22617] 83
MIRAJ ( S.
B.
SHINTRE )
app:srcCompat="@drawable/pinterest" />

<ImageView

android:id="@+id/imageView10"

android:layout_width="34dp"

android:layout_height="33dp"

android:layout_x="291dp"

android:layout_y="482dp"

app:srcCompat="@drawable/linkedin" />

<ImageView

android:id="@+id/imageView11"

android:layout_width="37dp"

android:layout_height="39dp"

android:layout_x="192dp"

android:layout_y="636dp"

app:srcCompat="@drawable/lock" />

<ImageView

android:id="@+id/imageView12"

android:layout_width="42dp"

android:layout_height="45dp"

android:layout_x="218dp"

android:layout_y="514dp"

app:srcCompat="@drawable/camera" />

<ImageView

G. P. CO6I [MAD-22617] 84
MIRAJ ( S.
B.
SHINTRE )
android:id="@+id/imageView13"

android:layout_width="65dp"

android:layout_height="48dp"

android:layout_x="336dp"

android:layout_y="518dp"

app:srcCompat="@drawable/maps" />

<ImageView

android:id="@+id/imageView14"

android:layout_width="52dp"

android:layout_height="43dp"

android:layout_x="280dp"

android:layout_y="554dp"

app:srcCompat="@drawable/music" />

<TextView

android:id="@+id/textView4"

android:layout_width="wrap_content"

android:layout_height="81dp"

android:layout_x="17dp"

android:layout_y="324dp"

android:rotation="270"

android:text="26.2021"

android:textColor="#fff"

android:textSize="20dp"

android:textStyle="bold" />

G. P. CO6I [MAD-22617] 85
MIRAJ ( S.
B.
SHINTRE )
<TextView

android:id="@+id/textView5"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_x="-35dp"

android:layout_y="406dp"

android:rotation="270"

android:text="MONDAY"

android:textColor="#fff"

android:textSize="50dp"

android:textStyle="bold" />

<TextView

android:id="@+id/textView6"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_x="36dp"

android:layout_y="459dp"

android:rotation="270"

android:text="APRIL"

android:textColor="#A6FFFFFF"

android:textSize="70dp" />

<ImageView

android:id="@+id/imageView15"

G. P. CO6I [MAD-22617] 86
MIRAJ ( S.
B.
SHINTRE )
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_x="69dp"

android:layout_y="91dp"

app:srcCompat="@drawable/user" />

</AbsoluteLayout>

Output:

G. P. CO6I [MAD-22617] 87
MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 88
MIRAJ ( S.
B.
SHINTRE )
4. Table Layout:
<?xml version="1.0" encoding="utf-8"?>

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity"

android:background="#000000">

<TableRow android:layout_marginTop="300dp">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:gravity="center"

android:text="1"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:gravity="center"

G. P. CO6I [MAD-22617] 89
MIRAJ ( S.
B.
SHINTRE )
android:text="2"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:gravity="center"

android:text="3"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

</TableRow>

<TableRow android:layout_marginTop="25dp">
<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:gravity="center"

android:text="4"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

<TextView

G. P. CO6I [MAD-22617] 90
MIRAJ ( S.
B.
SHINTRE )
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:gravity="center"

android:text="5"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:gravity="center"

android:text="6"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

</TableRow>

<TableRow android:layout_marginTop="25dp">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

G. P. CO6I [MAD-22617] 91
MIRAJ ( S.
B.
SHINTRE )
android:gravity="center"

android:text="7"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:gravity="center"

android:text="8"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:gravity="center"

android:text="9"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

</TableRow>

G. P. CO6I [MAD-22617] 92
MIRAJ ( S.
B.
SHINTRE )
<TableRow android:layout_marginTop="25dp">

<TextView

android:layout_width="wrap_conte"

android:layout_height="wrap_content"

android:layout_weight="1"

android:gravity="center"

android:text="*"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:gravity="center"

android:text="0"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

G. P. CO6I [MAD-22617] 93
MIRAJ ( S.
B.
SHINTRE )
android:layout_weight="1"

android:gravity="center"

android:text="#"

android:textColor="#fff"

android:textSize="25dp"

android:textStyle="bold" />

</TableRow>

<TableRow android:layout_marginTop="25dp">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:gravity="center"

android:textSize="25dp" />

<ImageView

android:id="@+id/imageView2"

android:layout_width="70dp"

android:layout_height="70dp"

android:layout_weight="1"

app:srcCompat="@drawable/call" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

G. P. CO6I [MAD-22617] 94
MIRAJ ( S.
B.
SHINTRE )
android:layout_weight="1"

android:gravity="center" />

</TableRow>

</TableLayout>

Output:

G. P. CO6I [MAD-22617] 95
MIRAJ ( S.
B.
SHINTRE )
5. Relative Layout:

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@drawable/picture"

tools:context=".MainActivity">

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

android:textStyle="bold"

android:textColor="#FFEB3B"

android:text="OHA"

android:textSize="20sp"

android:backgroundTint="#E91E63"

android:id="@+id/b1"

/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

G. P. CO6I [MAD-22617] 96
MIRAJ ( S.
B.
SHINTRE )
android:layout_centerInParent="true"

android:layout_marginRight="55dp"

android:layout_toLeftOf="@+id/b1"

android:backgroundTint="#FFEB3B"

android:text="Chip makers"

android:textColor="#E91E63"

android:textStyle="bold" />

<Button

android:layout_width="100dp"

android:layout_height="wrap_content"

android:layout_alignParentRight="true"

android:layout_centerInParent="true"

android:layout_marginRight="13dp"

android:layout_marginBottom="335dp"

android:backgroundTint="#FFEB3B"

android:text="Software Companies"

android:textColor="#E91E63"

android:textStyle="bold" />

<Button

android:layout_width="wrap_content

android:layout_height="wrap_content

android:layout_alignParentTop="true

android:layout_centerInParent="true"

G. P. CO6I [MAD-22617] 97
MIRAJ ( S.
B.
SHINTRE )
android:backgroundTint="#FFEB3B"

android:text="Handset Manufacturer"

android:layout_marginTop="180dp"

android:textColor="#E91E63"

android:textStyle="bold" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentBottom="true"

android:layout_marginBottom="180dp"

android:backgroundTint="#FFEB3B"

android:layout_centerInParent="true"

android:text="Commercialization companies"

android:textColor="#E91E63"

android:textStyle="bold" />

</RelativeLayout>

Output:

G. P. CO6I [MAD-22617] 98
MIRAJ ( S.
B.
SHINTRE )
HANDSET MANUFACTURER

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 99


6. Frame Layout:

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

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#FFEB3B"

tools:context=".MainActivity">

<TextView

android:layout_width="315dp"

android:layout_height="42dp"

android:layout_marginTop="30sp"

android:text=" SUBJECT:MAD"

android:textColor="#E71919"

android:textSize="20sp" />

<TextView

android:layout_width="match_parent"

android:layout_height="64dp"

android:layout_marginTop="80dp"

android:text="Question 1: OHA was formed inwhich year?"

android:textColor="#000000"

android:textSize="20sp" />

G. P. CO6I [MAD-22617] 100


MIRAJ ( S.
B.
SHINTRE )
<RadioButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="50sp"

android:layout_marginStart="30dp"

android:layout_marginTop="200dp"

android:text="November 2005"

/>

<RadioButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="October 2005"

android:layout_marginLeft="50dp"

android:layout_marginStart="30dp"

android:layout_marginTop="300dp"

/>

<RadioButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="November 2007"

android:layout_marginStart="250dp"

android:layout_marginTop="200dp"

android:layout_marginLeft="250dp"

G. P. CO6I [MAD-22617] 101


MIRAJ ( S.
B.
SHINTRE )
/>

<RadioButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="August 2007"

android:layout_marginLeft="250dp"

android:layout_marginStart="250dp"

android:layout_marginTop="300dp"

/>

<Button

android:layout_width="118dp"

android:layout_height="wrap_content"

android:layout_marginLeft="280dp"

android:layout_marginStart="260dp"

android:layout_marginTop="400dp"

android:background="#8CECDE"

android:text="Next"

android:textColor="#E71919"

android:textSize="16sp"

/>

<Button

G. P. CO6I [MAD-22617] 102


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="117dp"

android:layout_height="wrap_conte

nt"

android:layout_marginTop="400dp"

android:background="#8CECDE"

android:text="previous"

android:textColor="#E71919"

android:textSize="16sp"

/>

<Button

android:layout_width="15

3dp"

android:layout_height="wrap_conte

nt"android:layout_gravity="center"

android:layout_marginTop="200dp"

android:background="#82E70C"

android:text="SUBMIT TEST"

android:textSize="20sp"

/>

</FrameLayout>

Output:

G. P. 103
CO6I [MAD-22617]
MIRAJ ( S.
B.
SHINTRE )
SUBJECT:MAD

Question 1: OHA was formed in which year?

November
November 2005
2007

October 2005 August2007

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-2261 104


7]
CH - 4 : Designing User – Interface with View .

Syllabus :

4.1 Text View, Edit Text; Button, Image Button; Toggle


Button; Radio Button And Radio Group ; Checkbox ; Progress
Bar.

4.2 List View; Grid View; Image View; Scroll View; Custom
Toast Alert.

4.3 Time and Date Picker.

G. P. CO6I [MAD-22617] 105


MIRAJ ( S.
B.
SHINTRE )
INTRODUCTION
1] View class represents the basic building block for User Interface ( UI ) components.

2] A view occupies a rectangular area on the screen and is responsible for drawing and event
handling.

3] View is base class for widgets which are used to create UI Components ( Buttons, TextField etc. )

4] The ViewGroup subclass is the base class for layouts which are invisible containers that hold other

views (or other ViewGroup) and define their layout properties.

5] A ViewGroup is a special view that can contain other views (called children) .

6] The view is the component which Android provides us to design the layouts of the app

. A view is the superclass of all UI components.

7] View is also known as widget in android. Any visual(that we can see on screen)and interactive

(with which user can interact with) is called widget.

VIEW HIERARCHY :

G. P. CO6I [MAD-22617] 106


MIRAJ ( S.
B.
SHINTRE )
8] View occupies rectangular area on screen, the rectangle here is actually invisible but every view
Occupies the rectangle set.

9] What can be the size of this rectangle ?

the answer is we can set it manually by specifying exact size(with proper units) or by using some
pre-defined values

this pre-defined values are-

a] match_parent

It means it will occupy complete space available on display of device

B] wrap_content

Itwill occupyonly that much space as requiredfor its content todisplay.

XML syntax for creating a View

G. P. CO6I [MAD-22617] 107


MIRAJ ( S.
B.
SHINTRE )
Now,aswehaveexplainedearlieraswell,todrawanythingin yourandroidapplication,youwill
have to sepcify it in the design XML files. And to add functionality we will create Java files.

Every view in XML has the following format:

<ViewName

Attribute1=Value1

Attribute2=Value2

Attribute3=Value3

AttributeN=ValueN

/>

Italways start with anangle bracket, followed by the View name.Wewill introduce youtovarious
types of Views very soon.

Then we write attributes that will define how that view will look on the screen of the application
along with avalue for the attribute. Each view has its ownattributes which we will discuss in the
next few tutorials which will cover various typs of views.

In the end, it is closed by />

So, everyViewsubclassneedstofollowthisformatsothatitcanappearon thescreenof theapp.


And this format is nothing but default XML style. Right!

There are two attributes that are necessary for every View. These
are: android:layout_height and android:layout_width.

These attributes define the size of the invisible rectangle that a view makes. Using these attributes
we can easily control the size for every view in our android application.

Apart from the above mentioned attributes, attributes


like gravity, layout_gravity, padding and margin are some other commonly used attributes.

Programmatic and DeclarativeApproach

To create/define a View or a ViewGroup in your android application, there are two possible ways:

G. P. CO6I [MAD-22617] 108


MIRAJ ( S.
B.
SHINTRE )
The Programmatic Approach: In this we define/create our Views in the Java source file. We will
learn about this approach in details later, as of nowhere is a sample code toadda Button to our
view.

Button myButton = new Button(this);

myButton.setLayoutParams(new LinearLayout.LayoutParams(

LinearLayout.LayoutParams.MATCH_PARENT,

LinearLayout.LayoutParams.MATCH_PARENT));

myLayout.addView(myButton);

So addView() is the function used to add any View to the UI and setLayoutParams() function is used
to set the various attributes.

The Declarative Approach: In this we define the View and ViewGroups directly in the design XML
files, like we will be doing in the next couple of tutorials where we will study about various
commonly used views.

G. P. CO6I [MAD-22617] 109


MIRAJ ( S.
B.
SHINTRE )
EditTaxt
TextView Vie
This is our App
Studytonight.com

RadioButton
CheckBox ie
IB

ImageButton
MW

Button
ENTER ie

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 110


TEXT – VIEW
TextView refers to the widget which displays some text on the screen based on the layout, size,
colour, etc set for that particular TextView. It optionally allows us to modify or edit itself as well.
Attributes :

1] id :

Supply an identifier name of this view, to later retrive it with view. findViewById() or
Activity.findViewById()

Syntax :

android : id = ”@+id/b1” .

2] autoLink :

This attribute is used to control wether the url, phone number are automatically found and
converted to clickable links.

Syntax :

android : autolink = ”phone” .

3] alpha :

This property of view has value between 0 (Entirely transparent) and 1 (Completely Opaque).

4] gravity :

The gravity attribute is an optional attribute which is used to control the alignment of the text like
Left, Right, Center, Top, Bottom, Center_Vertical, Center_Horizontal.

Syntax :

android : gravity = “center_vertical” .

5] text :

G. P. CO6I [MAD-22617] 111


MIRAJ ( S.
B.
SHINTRE )
The attribute is used to set the text in textview. We can set text in xml as well as Java class.

Syntax :

android : text = “String”.

6] textColor :

The attribute is used to set the text Color in textview. Color values are of form “#argb”, “#rgb”
,”#rrggbb” or “#aarrggbb” .

Syntax :

android : textColor = “#222” .

7] textSize :

The attribute is used to set the size of the text in textview. We can set the size sp(Scale
independent Pixel) , dp(Density Pixel) or px(pixels) .

Syntax :

Android : textsize = “30dp” .

8] textStyle :

The attribute is used to set the textview. The possible text styles are Bold, Italic andnormal. If we
need to use two or more styles for textview then “ | ” operator is used.

Syntax :

Android : textStyle = “bold | italic” .

9] background :

The background attribute is used to set the background of a textview . we can set the color or a
drawable in the background of a component or view.

10] padding :

G. P. CO6I [MAD-22617] 112


MIRAJ ( S.
B.
SHINTRE )
The attribute is used to set the padding from Left, Right, Top and Bottom.

Example:

XML Code:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="#80FFEB3B">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="30dp"
android:autoLink="web"
android:text="www.google.com"
android:textSize="40sp"
android:background="#673AB7"
/>
<TextView
android:id="@+id/ph_no"
android:layout_width="198dp"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="100dp"
android:autoLink="phone"
android:alpha="1"
android:gravity="center"
android:text="8830288770"
android:textSize="30sp"
android:textColor="#F44336"
android:textStyle="bold|italic"
android:padding="10dp"
/>
<TextView

G. P. CO6I [MAD-22617] 113


MIRAJ ( S.
B.
SHINTRE )
android:id="@+id/mail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="100dp"
android:autoLink="email"
android:alpha="1"
android:gravity="center"
android:text="[email protected]"
android:textSize="30sp"
android:textColor="#F44336"
android:textStyle="bold|italic"
android:padding="10dp"
/>
</LinearLayout>

Output:

G. P. CO6I [MAD-22617] 114


MIRAJ ( S.
B.
SHINTRE )
EDIT - TEXT
It is an editable text entry box that accepts multiline entry, word wrapping and hint text.

A Edit Text is an overly over textview that configures itself to be editable. It is the predefined
subclass of textview that includes rich editing capabilities.

Attributes :

1] id :

It is an attribute used to uniquely identify an edit text. The type of id is reference.

Syntax :

android : id = “@+id/idnm”

2] text :

The text attribute is used to set the text (Statically) in edit text. We can set it from .xml or .java file
.

Syntax :

android : text = “String”

3] hint :

It is an attribute used to set the hint i.e when we want the user to enter in edit text, Whenever
user starts to type in edit text the hint will automatically disappear.

Syntax :

android : hint = “Enter Name.”

4] gravity :

The gravity attribute is an optional attribute which is used to control the alignment of the text like
Left, Right, Center, Top, Bottom, Center_Vertical, Center_Horizontal.

Syntax :

G. P. CO6I [MAD-22617] 115


MIRAJ ( S.
B.
SHINTRE )
android : gravity = “center”

5] textSize :

The attribute is used toset the size of the font in textview. We can set the size sp(Scale
independent Pixel) , dp(Density Pixel) or px(pixels) .

Syntax :

Android : textsize = “30dp” .

6] inputType :

The attribute specifies the input type of data/info i.e user going to enter, input type maybe
password, email, phone etc.

Syntax :

Android : inputType = “password” .

7] textColor :

The attribute is used to set the text Color in textview. Color values are of form “#argb”, “#rgb”
,”#rrggbb” or “#aarrggbb” .

Syntax :

android : textColor = “#222” .

8] padding :

The attribute is used to set the padding from Left, Right, Top and Bottom.

9] textStyle :

The attribute is used to set the textview. The possible text styles are Bold, Italic andnormal. If we
need to use two or more styles for EditText then “ | ” operator is used.

G. P. CO6I [MAD-22617] 116


MIRAJ ( S.
B.
SHINTRE )
Syntax :

Android : textStyle = “bold | italic” .

10] background :

Thebackground attribute is used to set the background of a EditText. we can set the color ora
drawable in the background of a component or view.

11] alpha :

This property of view has value between 0 (Entirely transparent) and 1 (Completely Opaque).

G. P. CO6I [MAD-22617] 117


MIRAJ ( S.
B.
SHINTRE )
Example:

Xml code:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity"

android:orientation="vertical"

android:background="@color/purple_200">

<EditText

android:layout_width="300dp"

android:layout_height="wrap_content"

android:id="@+id/t1"

android:hint="Email"

android:layout_marginTop="50dp"

android:layout_marginLeft="30dp"

android:gravity="left"

android:textStyle="bold"

android:textColor="@color/black"

android:textSize="20sp"

android:inputType="textEmailAddress"

android:fontFamily="sans-serif-condensed"

G. P. CO6I [MAD-22617] 118


MIRAJ ( S.
B.
SHINTRE )
android:padding="10dp"

android:background="@color/teal_200"

android:alpha="1"/>

<EditTextandroid:layout_width="30

0dp"

android:layout_height="wrap_content"

android:id="@+id/t2"

android:hint="Password"

android:layout_marginTop="50dp"

android:layout_marginLeft="30dp"

android:gravity="left"

android:textStyle="bold"

android:textColor="@color/black"

android:textSize="20sp"

android:inputType="textPassword"

android:padding="10dp"

android:background="@color/teal_200"

android:alpha="1"

android:fontFamily="sans-serif-

condensed"/>

<EditText

android:layout_width="300dp"

android:layout_height="wrap_content"

android:id="@+id/number"

android:hint="Phone Number"

G. P. CO6I [MAD-22617] 119


MIRAJ ( S.
B.
SHINTRE )
android:layout_marginTop="50dp"

android:drawablePadding="12dp"

android:layout_marginLeft="30dp"

android:gravity="left"

android:textStyle="bold"

android:textColor="@color/black"

android:textSize="20sp"

android:inputType="number"

android:padding="10dp"

android:background="@color/teal_200"

android:alpha="1"

android:fontFamily="sans-serif-

condensed"/>

<EditText

android:layout_width="300dp"

android:layout_height="wrap_content"

android:id="@+id/dob"

android:hint="Date of birth"

android:layout_marginTop="50dp"

android:drawablePadding="12dp"

android:layout_marginLeft="30dp"

android:gravity="left"

android:textStyle="bold"

android:textColor="@color/black"

G. P. CO6I [MAD-22617] 120


MIRAJ ( S.
B.
SHINTRE )
android:textSize="20sp"

android:inputType="datetime"

android:padding="10dp"

android:background="@color/teal_200"

android:alpha="1"

android:fontFamily="sans-serif-condensed"

/>

</LinearLayout>

Output:

G. P. CO6I [MAD-22617] 121


MIRAJ ( S.
B.
SHINTRE )
BUTTON
In Android Operating System Button represents the push Button that can be pressed, pushed or
clicked by the user to perform specific action.

Different types of buttons are used in Android such as ImageButton, ToggleButton, RadioButton
and CompoundButton.

Button is asubclass of textview class on button we can perform different actions orevents like,
ClickEvent, PressedEvent, TouchEvent etc.

Attributes :

1] onClick :

This attribute is used to specify the action that should be performed on click of that button, The
value of onclick is a method that should be written in the java file.

2] drawable :

Drawable_Bottom, Drawable_Top, Drawable_Left, Drawable_Right.

These are drawable resources that are to be drawn on specified alignment of text.

Syntax :

android : drawable_top = “@drawable/ic_launcher” .

3] android:visibility :

This attribute require Boolean value if it is true then this element is visible in activity otherwise
false.

android:visibility=””

4] android: id

Id is an attributes used to uniquely identify a text button.

android :id=“@+id/name”

G. P. CO6I [MAD-22617] 122


MIRAJ ( S.
B.
SHINTRE )
5] android:gravity

The gravity attributes is an optional attributes which is used to control alignment of the text like
left, right, center, top, bottom, center vertical, center horizontal etc.

6] android:Text

text attributes is used to set the text in a button. We can the text in xml as well as java class.

7] android:TextColor

The text color attributes is used to set color of a button. Color value is in the form of “#rgb”,
“#argb”, “rrggbb”.

9] android:TextSize:

Textsize attributes is used to set the size of the text on Button.

We can set text size in sp (scale independent pixel) or dp (density pixel)

10] android:TextStyle

Textstyle attributes is used to set the text style of a button.

The possible text style are bold, italic and normal.

11] android:Padding:

Padding attributes is used to set the padding from left, right,top,bottom.

G. P. CO6I [MAD-22617] 123


MIRAJ ( S.
B.
SHINTRE )
Sample Button:

Xml Code:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<Button

android:layout_width="300dp"

android:layout_height="wrap_content"

android:id="@+id/btn1"

android:layout_marginLeft="50dp"

android:text="Hello"

android:textSize="30sp"

android:textColor="@color/cardview_light_background"

android:textStyle="bold"

android:textAllCaps="false"

android:backgroundTint="@color/teal_200"

android:tooltipText="This is Button"

android:onClick="click"

android:layout_gravity="center"

/>

</LinearLayout>

G. P. CO6I [MAD-22617] 124


MIRAJ ( S.
B.
SHINTRE )
Output:

G. P. CO6I [MAD-22617] 125


MIRAJ ( S.
B.
SHINTRE )
IMAGE - BUTTON

In Android , ImageButton is used to display a normal Button with a custom image on the Button,
in simple words you can say imagebutton is abutton with animage that can be pressed or clicked
by the user.

By default, it looks like anormal button with standard button background that changes the color
during different button states.

Attributes :

1] android:src :

Src is an attribute used to set the source of image or we can say image in the ImageButton, to
make layout lookattractive , before using src the image should be saved in the drawable file.

Syntax :

android : src = “@drawable/home” .

2] android:padding:

Padding attribute is used to set the padding from Left, Right, Top or Bottom of the ImageButton.

i) padding_right : Padding from right side of the image button.

ii) padding_left : Padding from left side of the image button.

iii) padding_top : set padding from top side of the image button.

iv) padding_bottom : set padding from bottom side of the image button.

v) padding : set the padding from all the sides of the image button.

3] android:scaleType:

Controls how the image should be resized or moved to match the size of this ImageView.

G. P. CO6I [MAD-22617] 126


MIRAJ ( S.
B.
SHINTRE )
4] android:adjustViewBounds:

Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its
drawable.

5] android:alpha

This property of view has value between 0 (Entirely transparent) and 1 (Completely Opaque).

6] android:clickable

Defines whether this viewreacts to click events.

Maybeabooleanvalue, suchas"true" or"false".

7] android:baseline

This is the offset of the baseline within this view.

8] android:baselineAlignBottom

If true, the image view will be baseline aligned with based on its bottom edge.

9] android:cropToPadding

If true, the image will be cropped to fit within its padding.

10] android:onClick

This is the name of the method in this View's context to invoke when the view is clicked.

Example:

Xml Code:

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

G. P. CO6I [MAD-22617] 127


MIRAJ ( S.
B.
SHINTRE )
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity"

android:orientation="vertical">

<ImageButton

android:layout_width="wrap_content"

android:layout_height="300dp"

android:background="@drawable/doremon"

android:id="@+id/b1"

android:scaleType="centerCrop"

android:onClick="click1"

/>

<ImageButton

android:layout_width="wrap_content"

android:layout_height="300dp"

android:background="@drawable/nobita"

android:id="@+id/b2"

android:scaleType="centerCrop"

android:onClick="click2"

/>

</LinearLayout>

G. P. CO6I [MAD-22617] 128


MIRAJ ( S.
B.
SHINTRE )
Java Code:

package com.com.code.imagebutton;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.ImageButton;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

ImageButton b1,b2;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

b1=findViewById(R.id.b1);

b2=findViewById(R.id.b2);

public void click1(View view) {

Toast.makeText(this,"Doremon",Toast.LENGTH_LONG).show();

public void click2(View view) {

Toast.makeText(this,"Nobita",Toast.LENGTH_LONG).show();

Output:

G. P. CO6I [MAD-22617] 129


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 130
MIRAJ ( S.
B.
SHINTRE )
TOGGLE - BUTTON
In Android , ToggleButton is used to display checked and unchecked state of the Button.

Toggle Button isbasically an ON/OFF Button with a light indicator,Which indicatesthe current
state of ToggleButton.

The most simple example of Toggle Button is doing ON/OFF in Sound, Bluetooth, WiFi, HotSpot.

It is the subclass ofCompoundButton.

Attributes :

1] checked:

This attribute is used to set the current state of the ToggleButton, The value should be true or
false where Trueshows“CHECKED” state and False shows“UNCHECKED” state of ToggleButton.

Default value of Checked attribute is False.

Syntax :

android : Checked=”true”.

Attributes :

1] android:disabledAlpha

The alpha to apply to the indicator when disabled.

2] textON / textOFF :

TextOn attribute is used to set the textwhen ToggleButton is in Checked/On state, Wecan set the
textOn in xml as well as java class

Syntax :

android : textON = “ENABLE”

android : textOff = “DISABLE”

3] android:hint

Hint text to display when the text is empty.

G. P. CO6I [MAD-22617] 131


MIRAJ ( S.
B.
SHINTRE )
4] android:text

Text to display.

5] android:textAllCaps

Present the text in ALLCAPS.

6] android:textColor

Text color.

7] android:onClick

This is the name of the method in this View's context to invoke when the view is clicked.

8] android:tootipText:

A tooltip is a small descriptive message that appears near a view when users long press the view or
hover their mouse over it.

9] android:padding

Sets the padding, in pixels, of all four edges

10] android:textAlignment

Defines the alignment of the text

Example:

Xml Code:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

G. P. CO6I [MAD-22617] 132


MIRAJ ( S.
B.
SHINTRE )
xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" tools:context=".MainActivity"

<LinearLayout

android:layout_height="wrap_content"

android:layout_width="match_parent"

android:orientation="horizontal">

<ToggleButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/t1"

android:textOn="ON"

android:textOff="OFF"

android:layout_marginTop="200dp"

android:layout_marginLeft="100dp"

android:background="@color/purple_200"/>

<ToggleButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/t2"

G. P. CO6I [MAD-22617] 133


MIRAJ ( S.
B.
SHINTRE )
android:textOn="ON"

android:textOff="OFF"

android:layout_marginTop="200dp"

android:layout_marginLeft="50dp"

android:background="#FFF7AC"/>

</LinearLayout>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="onclickMethod"

android:id="@+id/b1"

android:text="SUBMIT."

android:background="#EF85A9"

android:layout_marginLeft="170dp"

android:layout_marginTop="200px"

/>

</LinearLayout>

Java Code:

package com.example.sample2;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

G. P. CO6I [MAD-22617] 134


MIRAJ ( S.
B.
SHINTRE )
import android.widget.Toast;

import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

ToggleButton t1,t2;

Button b1;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

t1 = findViewById(R.id.t1);

t2 = findViewById(R.id.t2);

b1 =findViewById(R.id.b1);

public void onclickMethod(View view) {

Stringstr ="ToggleButton1 "+t1.getText()+"\n"+ "ToggleButton2"+t2.getText();

Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();

Output:

G. P. CO6I [MAD-22617] 135


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 136
MIRAJ ( S.
B.
SHINTRE )
RADIO – BUTTON AND RADIOGROUP
A RadioButtonhas2 states, either checkedorunchecked. Thisallows theuserto selectone option
from a set of RadioButtons.

In Andriod , RadioButtons are mainly used together in a RadioGroup.

In RadioGroup , checking the radioButton out of several radiobuttons added in, it will
automatically uncheck all the others.

It means at one time we can check only one radiobutton from a group of radiobuttons which
belongs to same radiogroup.

Once , RadioButton is checked by user it cannot be unchecked by simply pressing on the same
button. It will automatically uncheck when we press any other RadioButton in the same
RadioGroup

Attributes :

1] android:checked :

This attribute is used to set the current state of the RadioButton, we can set it either True or
False. True shows Checked state and False shows Unchecked state.

Syntax :

Android : checked = “true” .

2] text :

The attribute is used to set the text in RadioButton. We can set text in xml as well as Java class.

2] android:textColor :

The attribute is used to set the text Color in textview. Color values are of form “#argb”, “#rgb”
,”#rrggbb” or “#aarrggbb” .

Syntax :

android : textColor = “#222” .

3] android:textSize :

G. P. CO6I [MAD-22617] 137


MIRAJ ( S.
B.
SHINTRE )
The attribute is used toset the size of the text in textview. We can set the size sp(Scale
independent Pixel) , dp(Density Pixel) or px(pixels) .

Syntax :

Android : textsize = “30dp” .

4] android:textStyle :

The attribute is used to set the textview. The possible text styles are Bold, Italic and normal. If we
need to use two or more styles for textview then “ | ” operator is used.

Syntax :

Android : textStyle = “bold | italic” .

5] android:background :

Thebackground attribute is used to set the background of a RadioButton. we can set the color or
a drawable in the background of a component or view.

6] android:padding :

The attribute is used to set the padding from Left, Right, Top and Bottom.

7] android:button

Drawable used for the button graphic (for example, checkbox and radio button).

Example:

Xml Code:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

G. P. CO6I [MAD-22617] 138


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context=".MainActivity">

<RadioGroup

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/rg1">

<RadioButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginTop="100dp"

android:layout_marginLeft="100dp"

android:textSize="25dp"

android:text="Mango"

android:textColor="#FF9800"/>

<RadioButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginTop="50dp"

android:layout_marginLeft="100dp"

android:textSize="25dp"

android:text="Apple"

android:textColor="#FF2323"/>

<Button

G. P. CO6I [MAD-22617] 139


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginTop="100dp"

android:text="Show Selected!"

android:layout_marginLeft="100dp"

android:id="@+id/b1"

android:onClick="onclickbuttonMethod"

/>

</RadioGroup>

</LinearLayout>

Java Code:

package com.com.code.radiobutton;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.RadioButton;

import android.widget.RadioGroup;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Button b1;

RadioButton rb1;

RadioGroup rgb;

@Override

protected void onCreate(Bundle savedInstanceState) {

G. P. CO6I [MAD-22617] 140


MIRAJ ( S.
B.
SHINTRE )
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

rgb = findViewById(R.id.rg1);

public void onclickbuttonMethod(View v) {

int sid = rgb.getCheckedRadioButtonId();

rb1 = findViewById(sid);

if(sid == -1)

Toast.makeText(this,"NOTHING SELECTED",Toast.LENGTH_LONG).show();

else

Toast.makeText(this,rb1.getText(), Toast.LENGTH_LONG).show();

Output:

G. P. CO6I [MAD-22617] 141


MIRAJ ( S.
B.
SHINTRE )
O

O Apple
O Apple

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 142


CHECKBOX.
ACheckboxisON/OFF.Switch that canbe Toggledbytheusera2 statebutton representedby
checked or unchecked box.

Like swing JCheckBox.

Inherits all of textview attributes and Button attributes.

Attributes :

1] android:onClick
This is the name of the method in this View's context to invoke when the view is clicked.

2] android:autoText
If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.

3] android:drawableBottom
This is the drawable to be drawn below the text.

4] android:drawableRight
This is the drawable to be drawn to the right of the text.

5] android:editable
If set, specifies that this TextView has an input method.

6] android:text
This is the Text to display.

7] android:background
This is a drawable to use as the background.

8] android:contentDescription

G. P. CO6I [MAD-22617] 143


MIRAJ ( S.
B.
SHINTRE )
This defines text that briefly describes content of the view.

9] android:id
This supplies an identifier name for this view.

10] android:visibility
This controls the initial visibility of the view.
Example:

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


<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/todo"
tools:context=".MainActivity">

<CheckBox
android:id="@+id/c1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="40dp"
android:layout_y="150dp" />

<CheckBox
android:id="@+id/c2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="40dp"
android:layout_y="250dp" />

<CheckBox
android:id="@+id/c3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="40dp"
android:layout_y="350dp" />

G. P. CO6I [MAD-22617] 144


MIRAJ ( S.
B.
SHINTRE )
<CheckBox
android:id="@+id/c4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="40dp"
android:layout_y="450dp" />

<TextView
android:layout_width="214dp"
android:layout_height="39dp"
android:layout_x="121dp"
android:layout_y="150dp"
android:text="Complete MAD assignment" />

<TextView
android:id="@+id/textView"
android:layout_width="214dp"
android:layout_height="39dp"
android:layout_x="121dp"
android:layout_y="250dp"
android:text="Complete python manual" />
<TextView
android:id="@+id/textView2"
android:layout_width="214dp"
android:layout_height="39dp"
android:layout_x="121dp"
android:layout_y="350dp"
android:text="php experiments" />
<TextView
android:id="@+id/textView3"
android:layout_width="214dp"
android:layout_height="39dp"
android:layout_x="121dp"
android:layout_y="450dp"
android:text="EDE complete 12,13 practicals" />

<Button
android:layout_width="103dp"
android:layout_height="39dp"
android:layout_x="139dp"

G. P. CO6I [MAD-22617] 145


MIRAJ ( S.
B.
SHINTRE )
android:layout_y="500dp"
android:background="#F8BBD0"
android:onClick="show"
android:id="@+id/b1"
android:text="Done"
/>

</AbsoluteLayout>

Java Code:

package com.example.checkbox;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

CheckBox c1,c2,c3,c4;
Button b1;

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

public void show(View view) {


c1 = findViewById(R.id.c1);
c2 = findViewById(R.id.c2);
c3 = findViewById(R.id.c3);
c4 = findViewById(R.id.c4);
b1 = findViewById(R.id.b1);

StringBuilder s1=new StringBuilder();

G. P. CO6I [MAD-22617] 146


MIRAJ ( S.
B.
SHINTRE )
s1.append("Review: ");
if(c1.isChecked())
{
s1.append("\nMAD: Complete");
}
if(c2.isChecked())
{
s1.append("\nPython: Complete");
}
if(c3.isChecked())
{
s1.append("\nPHP: Complete");
}
if(c4.isChecked())
{
s1.append("\nEDE: Complete");
}
Toast.makeText(getApplicationContext(),s1.toString(),Toast.LENGTH_LONG).show();
}
}

Output:

G. P. CO6I [MAD-22617] 147


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 148
MIRAJ ( S.
B.
SHINTRE )
PROGRESSBAR.
A ProgressBar is used to show the Progress of an operation. ProgressBar is usually indicator of
progress in a number of operations.

ProgressBars are used to show progress of a task

ex. When we are uploading or downloading something from the internet, it is better to show the
progress of download/upload to theuser.

In Android. There is a class called progressDialog that allows us to create ProgressBars.

In Android, there is a class called ProgressBar that allows properties like below.

Attributes:

1] max :

This attribute is used in Android todefine maximum value of the progress can take.It mustbean
integer value like 100,200 etc.

Syntax :

android : max =”100”

2] progress :

Theprogress is anattribute used in Android todefine thedefault ProgressValue between 0 and


Max. It must be an Integer value below we set the 100 max value and set 50 default progress.

Syntax :

<ProgressBar

android : layout_width = “fill_parent”

android : layout_height = “wrap_content”

android : max =“100”

android : progress = “50” /

3] progressDrawable :

G. P. CO6I [MAD-22617] 149


MIRAJ ( S.
B.
SHINTRE )
TheprogressDrawable is anattribute used in android toset the custom drawable for the progress
mode.

4] indeterminate :

The indeterminate attribute is used in android to enable the indeterminate mode. In this mode
the progressBar shows a cyclic animation without an indication of progress.

This mode is used in android applications when we don’t know the amount of work to be done.

Example:

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<Button

android:id="@+id/button"

android:text="Download"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true" />

</RelativeLayout>

Java code:

package com.example.progressdialog;

import androidx.appcompat.app.AppCompatActivit

G. P. CO6I [MAD-22617] 150


MIRAJ ( S.
B.
SHINTRE )
import android.app.ProgressDialog;

import android.os.Handler;

import android.os.Message;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button button;

ProgressDialog progressDoalog;

@Overrideprotected void

onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_mai

n);

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

button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

progressDoalog = new ProgressDialog(MainActivity.this);

progressDoalog.setMax(100);

progressDoalog.setMessage("Loading ... ");

progressDoalog.setTitle("ProgressDialog example");

G. P. CO6I [MAD-22617] 151


MIRAJ ( S.
B.
SHINTRE )
progressDoalog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

progressDoalog.show();

newThread(new Runnable() {

@Override

public void run() {

try {

while (progressDoalog.getProgress() <= progressDoalog

.getMax()) {

Thread.sleep(200);

handle.sendMessage(handle.obtainMessage());

if (progressDoalog.getProgress() == progressDoalog

.getMax()) {

progressDoalog.dismiss();

} catch (Exception e) {

e.printStackTrace();

}).start();

Handler handle = new Handler() {

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

G. P. CO6I [MAD-22617] 152


MIRAJ ( S.
B.
SHINTRE )
progressDoalog.incrementProgressBy(1);

};

});

G. P. CO6I [MAD-22617] 153


MIRAJ ( S.
B.
SHINTRE )
}

Output:

G. P. CO6I [MAD-22617] 154


MIRAJ ( S.
B.
SHINTRE )
LISTVIEW.

ListView Dispalys a vertically scrollable collection of views, where each view is positioned
immediately below the previous view in the list.

A ViewGroup that creates and managesavertical list of views display themas rows within the list.

Simple ListView display to the string value of each object in an array, use a textview for 11cm.

Android ListView is aview that groups several items anddisplay 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.

Attributes :

1] divider :

This is a drawable or color to draw between different list items

Ex:

<ListView
android : id = “@+id/l1”
android : layout_height = ”match_parent”
android : layout_width = “match-parent”
android : divider = “#f00”
android : divider_height = “1dp” />

2] dividerHeight :
This specifiesthe height of the divider between list items.This could be in dp(Density pixel), sp(Scale
Independent Pixel) or px(pixel).

3] listSelector :
The listSelector property is used to set the selector of the list view. It is generally of orange or sky blue
color mostly. But we can also define our custom color on image as a list selector as per our design.
Syntax :
android : listSelector = “#342”

Example:

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

G. P. CO6I [MAD-22617] 155


MIRAJ ( S.
B.
SHINTRE )
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/l1"/>

</LinearLayout>
<resources>
<string name="app_name">Listview</string>
<string-array name="Cartoon">
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
</string-array>
</resources>

Java code:

Package com.example.listview;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


ListView l1;
TextView t1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

G. P. CO6I [MAD-22617] 156


MIRAJ ( S.
B.
SHINTRE )
setContentView(R.layout.activity_main); l1=findViewById(R.id.l1);

String s[]=getResources().getStringArray(R.array.Cartoon);
ArrayAdapter a=new ArrayAdapter(this, android.R.layout.simple_selectable_list_item,s);
l1.setAdapter(a);
}
}

Output:

G. P. CO6I [MAD-22617] 157


MIRAJ ( S.
B.
SHINTRE )
ADAPTER USE IN LISTVIEW
Adapter is abridge between UIComponents and DataSource that helps ustofill data in UI
components.

It holds the data and sends the data to adapterView then view can take the data from the
adapterview and show the data on different views like listView, gridView, Spinner.

ListViewis the subclassof AdapterView and it can be populated bybinding anadapter, which
retrives the data from an external source and creates aview that represents each data entry.

In android commonly used adapters are array adapter and base adapter.

ARRAY ADAPTER :

1] Whenever we have list of single items, which is blocked byanarray.Wecan use ArrayAdapter.
For instance , list of phone contacts, countries or names.

2] By default, ArrayAdapter expects a layout with a single textview if we want to use more
complex view means more customisation in list items, please avoid array adapter and use custom
adapter.

3] The adapter code is :

< ArrayAdapter <string> adpt = new ArrayAdapter <string>


(this.R.layoutListView,R.id.textView,StringArray)

BASE ADAPTER :

1] Base Adapter can be extended to create custom Adapter for displaying a custom list item.
ArrayAdapter is also an implementation of BaseAdapter.

Example:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ListView
android:id="@+id/l1"
android:layout_width="match_parent"

G. P. CO6I [MAD-22617] 158


MIRAJ ( S.
B.
SHINTRE )
android:layout_height="match_parent"
android:divider="#45FFAE"
android:dividerHeight="1.0sp"
android:textSize="30sp" />

</LinearLayout>

Java code:

package com.example.prac14;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


ListView l1;
String[] sub = {"Android", "Java", "PHP", "Hadoop", "Sap", "Python", "Ajax", "C++", "Ruby",
"Rails","C","pearl"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
l1=findViewById(R.id.l1);
ArrayAdapter<String> arrayAdapter=new
ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,sub);
l1.setAdapter(arrayAdapter);

l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),""+sub[position],Toast.LENGTH_SHORT).show();
}
});
}
}

G. P. CO6I [MAD-22617] 159


MIRAJ ( S.
B.
SHINTRE )
output:

G. P. CO6I [MAD-22617] 160


MIRAJ ( S.
B.
SHINTRE )
GRIDVIEW
Android GridView shows items in 2 dimensional scrolling Grid (rows and columns) and Grid items
are not necessarily predetermined but they automatically inserted into the layout using a list
adapter.

GridView will fill the entire screen. It displays data in Grid-Form. Although we use the term data
here, cotent of GridView can be text,images and so on.

GridView is default Scrollable, so we donotneedtouse scrollview oranything else with gridview.

Ex. Our default Gallery where umber of images are displayed in GridView.

Attributes:

1] android:id
This is the ID which uniquely identifies the layout.

2] android:columnWidth
This specifies the fixed width for each column. This could be in px, dp, sp, in, or mm.

3] android:gravity
Specifies the gravity within each cell. Possible values are top, bottom, left, right, center,
center_vertical, center_horizontal etc.

4] android:horizontalSpacing
Defines the default horizontal spacing between columns. This could be in px, dp, sp, in, or
mm.

5] 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.

6] android:stretchMode
Defines how columns should stretch to fill the available empty space, if any. This must be
either of the values −
• none − Stretching is disabled.
• spacingWidth − The spacing between each column is stretched.

G. P. CO6I [MAD-22617] 161


MIRAJ ( S.
B.
SHINTRE )
• columnWidth − Each column is stretched equally.
• spacingWidthUniform − The spacing between each column is uniformly stretched..

7] android:verticalSpacing
Defines the default vertical spacing between rows. This could be in px, dp, sp, in, or mm.
Example:

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


<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView1"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity"
android:numColumns="3"
android:gravity="center"
android:columnWidth="50dp"
android:verticalSpacing="50sp"
android:horizontalSpacing="50sp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</GridView>

Java Code:

package com.example.gridbuttons;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


GridView gridView;
static final String[] numbers = new String[] {

G. P. CO6I [MAD-22617] 162


MIRAJ ( S.
B.
SHINTRE )
"1", "2", "3", "4", "5",
"6", "7", "8", "9", "10","11","12","13","14","15"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

gridView = (GridView) findViewById(R.id.gridView1);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,


android.R.layout.simple_list_item_1, numbers);

gridView.setAdapter(adapter);

gridView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getApplicationContext(),((TextView) view).getText(), Toast.LENGTH_LONG).show();

});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

menu/activity_main.xml file:

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


<menu xmlns:android="http://schemas.android.com/apk/res/android">

</menu>

Output:

G. P. CO6I [MAD-22617] 163


MIRAJ ( S.
B.
SHINTRE )
10

13 14

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 164


IMAGEVIEW
In Android, we can use “Android Widgets_ImageView” class todisplay an image file. Imagefile is
simpletousebuthard tomaster, becauseof various screensandAPI android devices. Androidwill
find image automatically.

Add image to “res/drawable”.


Give drawable file id to src attribute.
Attributes :

1] id:
id is an attribute used to uniquely identify a image view in android.

2] src:
src is an attribute used to set a source file or you can say image in your imageview to make your
layout attractive.

3] background:
background attribute is used to set the background of a ImageView. We can set acolor ora
drawable in the background of a ImageView.

4] padding:
padding attribute is used to set the padding from left, right, top or bottom of the Imageview.

5] scaleType:
scaleType is an attribute used to control how the image should be re-sized ormoved tomatch the
size of this image view. The value for scale type attribute can be fit_xy, center_crop, fitStart etc.

Example: program of change image using image view:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"

G. P. CO6I [MAD-22617] 165


MIRAJ ( S.
B.
SHINTRE )
android:layout_height="wrap_content"
android:text="This is an example of Image view"

/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/rabbit"
android:id="@+id/img1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Change Image"
android:id="@+id/b1"
/>
</LinearLayout>

Java file:

package com.example.myapplication4;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
Button b;
ImageView i1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton(){
b=(Button)findViewById(R.id.b1);
i1=(ImageView)findViewById(R.id.img1);
b.setOnClickListener(new OnClickListener() {
@Override

G. P. CO6I [MAD-22617] 166


MIRAJ ( S.
B.
SHINTRE )
public void onClick(View v) {

i1.setImageResource(R.drawable.india);
}
});
}
}

Output:

G. P. CO6I [MAD-22617] 167


MIRAJ ( S.
B.
SHINTRE )
SCROLLVIEW
A ViewGroup that allows the view hierarchy placed within it to be scrolled.

ScrollView may have only one direct child placed within it.

ScrollView supports vertical scrolling only for horizontal scrolling use horizontal ScrollView.

A ScrollView is a FrameLayout which puts onechild in it containing the whle contents to scroll,
This child may itself be a layout manager within a composite hierarchy of an object.
Attributes:

1] android:onClick:
Name of the method in this View’s context to invoke when the view is clicked.

2] android: scrollbars:
In android, scrollbars attribute is used to show the scrollbars in horizontal or vertical direction. The possible
Value of scrollbars is vertical, horizontal or none. By default scrollbars is shown in vertical direction in
scrollView and in horizontal direction in HorizontalScrollView.

3] android:fillViewport:
Defines whether the scrollview should stretch its content to fill the viewport.

4] android:padding:
Sets the padding, in pixels, of all four edges.

5] Android: alpha:
alpha property of the view, as a value between 0 (completely transparent) and 1 (completely opaque).

6] android:background :
A drawable to use as the background

7] android:clickable:
Defines whether this view reacts to click events

8] android:contentDescription:
Defines text that briefly describes content of the view

9] android:id
Supplyan identifier namefor this view, tolater retrieve it with View.findViewById() or
Activity.findViewById().

10] android:isScrollContainer
Set this if theviewwill serve as ascrolling container, meaningthat it canberesized to shrink itsoverall
window so that there will be space for an input method.

11] android:minHeight :

G. P. CO6I [MAD-22617] 168


MIRAJ ( S.
B.
SHINTRE )
Defines the minimum height of the view.

12] android:minWidth:
Defines the minimum width of the view.

Example:

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#414ADA"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="185dp"
android:layout_height="51dp"
android:layout_gravity="center_horizontal"
android:text="Contacts"
android:layout_marginLeft="150sp"
android:layout_marginStart="150sp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#F9A825"
android:textSize="30sp" />
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp">

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

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="John stephan 9876543770"

G. P. CO6I [MAD-22617] 169


MIRAJ ( S.
B.
SHINTRE )
android:textColor="#FAFAFA"
android:layout_marginTop="50dp"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Andrew Son 9996543210"
android:textColor="#FAFAFA"
android:layout_marginTop="50dp"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Diana Penty 9874443210"
android:textColor="#FAFAFA"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Willium Taylor 9800000210"
android:textColor="#FAFAFA"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Hailey Jefer 9876555210"
android:textColor="#FAFAFA"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Ken Steven 9890990910"
android:textColor="#FAFAFA"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content" "

G. P. CO6I [MAD-22617] 170


MIRAJ ( S.
B.
SHINTRE )
android:layout_marginTop="50dp"
android:text="Mason pery 9808808810"
android:textColor="#FAFAFA"
android:textSize="30sp" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Alisa Khan 9876743210"
android:textColor="#FAFAFA"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="John stephan2 9876543770"
android:textColor="#FAFAFA"
android:layout_marginTop="50dp"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Andrew Son2 9996543210"
android:textColor="#FAFAFA"
android:layout_marginTop="50dp"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Diana Penty2 9874443210"
android:textColor="#FAFAFA"
android:textSize="30sp" />
</LinearLayout>
</ScrollView>

</RelativeLayout>
Output:

G. P. CO6I [MAD-22617] 171


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 172
MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 173
MIRAJ ( S.
B.
SHINTRE )
Custom Toast Alert
In Android, Toast is used to display information for a period of time. It contains a message to be
displayed quickly and disappears after specified period of time. It does not block the user
interaction. Toast is a subclass of Object class. In this we use two constants for setting the duration
for the Toast. Toast notification in android always appears near the bottom of the screen. We can
also create our custom toast by using custom layout(xml file).

Important Methods Of Toast:


1. makeText(Context context, CharSequence text, int duration):
This method is used to initiate the Toast. This method take three parameters First is for the application
Context, Second is text message and last one is duration for the Toast.

Constants of Toast: Belowisthe constants of Toastthat areusedfor settingthedurationfortheToast.


1. LENGTH_LONG: It is used to display the Toast for a long period of time. When we set this duration the
Toast will be displayed for a long duration.
2. LENGTH_SHORT: It is used to display the Toast for short period of time. When we set this duration the
Toast will be displayed for short duration.

2. show():
This method is used to display the Toast on the screen. This method is display the text which we create using
makeText() method ofToast.

3. setGravity(int,int,int):
This method is used to set the gravity for the Toast. This method accepts three parameters:
a Gravity constant, an x-position offset, and a y-position offset.

4. setText(CharSequence s):
This methodis usedto set the text for theToast. If we use makeText() method and then we want to change
the text value for the Toast then we use this method.

5. nsetText(CharSequence s):
This methodis usedto set the text for theToast. If we use makeText() method and then we want to change
the text value for the Toast then we use this method.

6. setDuration(int duration):
This method is usedto set the durationfor the Toast. If we use makeText() method and then we want to
change the duration for the Toast then we use this method.
7. inflate(int, ViewGroup):
This method is used toinflate the layout from thexml. Inthis method first parameter is the layout resource
ID and the second is the root View.

8. setView(View):

G. P. CO6I [MAD-22617] 174


MIRAJ ( S.
B.
SHINTRE )
This method is used to set the viewfor the Toast. Inthismethod we pass the inflated layout which we inflate
using inflate() method.

Example:

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

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent" android:layout_height="match_parent"

tools:context=".MainActivity"

android:background="#8C6562">

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="10dp"

android:layout_marginTop="10dp" android:text="Score :

0" android:textColor="#000000" android:textSize="25dp"

/>

<TextView

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

G. P. CO6I [MAD-22617] 175


MIRAJ ( S.
B.
SHINTRE )
android:layout_marginLeft="10dp"

android:layout_marginTop="50dp"

android:text="Question : 1/5"

android:textColor="#000000" android:textSize="25dp" />

<TextView

android:id="@+id/textView2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="210dp"

android:text="00:16"

android:textColor="#000000"

android:textSize="60dp"

android:layout_marginTop="10dp"/>

<TextView

android:id="@+id/textView3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="What is 2+2?"

android:layout_gravity="center|top"

android:layout_marginTop="200dp"

android:textSize="25dp"

G. P. CO6I [MAD-22617] 176


MIRAJ ( S.
B.
SHINTRE )
android:textColor="#000000"/>

<RadioButton

android:id="@+id/r1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="4"

android:textColor="#000000"

android:textSize="20dp"

android:layout_marginTop="250dp"/>

<RadioButton

android:id="@+id/r2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="6"

android:textColor="#000000"

android:textSize="20dp"

android:layout_marginTop="300dp"/>

<RadioButton

android:id="@+id/r3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

G. P. CO6I [MAD-22617] 177


MIRAJ ( S.
B.
SHINTRE )
android:text="17"

android:textColor="#000000"

android:textSize="20dp"

android:layout_marginTop="350dp"/>

</FrameLayout>

Java code:

package com.example.framelayout1;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.view.WindowManager;

import android.widget.Button;

import android.widget.RadioButton;

import android.widget.RadioGroup;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

RadioButton r1,r2,r3;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

getSupportActionBar().hide();

G. P. CO6I [MAD-22617] 178


MIRAJ ( S.
B.
SHINTRE )
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager
.LayoutParams.FLAG_FULLSCREEN);

addListenerOnButton();

private void addListenerOnButton() {

r1=findViewById(R.id.r1);

r2=findViewById(R.id.r2);

r3=findViewById(R.id.r3);

r1.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Toast.makeText(MainActivity.this, "CORRECT ANSWER",


Toast.LENGTH_LONG).show();

});

r2.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Toast.makeText(MainActivity.this, "WRONG ANSWER",


Toast.LENGTH_LONG).show();

});

G. P. CO6I [MAD-22617] 179


MIRAJ ( S.
B.
SHINTRE )
r3.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Toast.makeText(MainActivity.this, "WRONG ANSWER",


Toast.LENGTH_LONG).show();

});

Output:

G. P. CO6I [MAD-22617] 180


MIRAJ ( S.
B.
SHINTRE )
TimePicker

Android Time Picker allows you to select the time of day in either 24 hour or AM/PM mode. The
time consists of hours, minutes and clock format. Android provides this functionality through
TimePicker class.

Methods :

1. is24HourView()
This method returns true if this is in 24 hour view else false
2. isEnabled()
This method returns the enabled status for this view
3. setCurrentHour(Integer currentHour)
This method sets the current hour

4. setCurrentMinute(Integer currentMinute)
This method sets the current minute

5. setEnabled(boolean enabled)
This method set the enabled state of this view

6. setIs24HourView(Boolean is24HourView)
This method set whether in 24 hour or AM/PM mode

7. setOnTimeChangedListener(TimePicker.OnTimeChangedListener
onTimeChangedListener)
This method Set the callback that indicates the time has been adjusted by the user

Example:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

G. P. CO6I [MAD-22617] 181


MIRAJ ( S.
B.
SHINTRE )
android:layout_height="match_parent"
android:background="#C0CA33"
tools:context=".MainActivity">

<Button
android:id="@+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10sp"
android:layout_x="8dp"
android:layout_y="469dp"
android:background="#C51162"
android:text="-2hr:15min"
android:textColor="#ffffff" />

<TimePicker
android:id="@+id/tp1"
android:layout_width="match_parent"
android:layout_height="366dp"
android:layout_x="0dp"
android:layout_y="0dp"
android:background="#C0CA33" />

<Button
android:id="@+id/b1"
android:layout_width="122dp"
android:layout_height="wrap_content"
android:layout_marginTop="10sp"
android:layout_x="110dp"
android:layout_y="469dp"
android:background="#C51162"
android:text="Current Time"
android:textColor="#ffffff" />

<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10sp"
android:layout_x="250dp"
android:layout_y="472dp"
android:background="#C51162"
android:text="+2:15min"
android:textColor="#ffffff" />

<TextView
android:id="@+id/t1"

G. P. CO6I [MAD-22617] 182


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="253dp"
android:layout_height="83dp"
android:layout_x="37dp"
android:layout_y="372dp"
android:text="00:00"
android:textAlignment="center"
android:textColor="#ffffff"
android:textSize="50sp" />

</AbsoluteLayout>

Java file:

package com.example.prac161;

import androidx.appcompat.app.AppCompatActivity;

import android.icu.text.TimeZoneFormat;
import android.widget.Toast;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.TimeZone;

import static android.widget.Toast.LENGTH_LONG;

public class MainActivity extends AppCompatActivity {


Button b1,b2,b3;
TextView t1;
TimePicker tp1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1=findViewById(R.id.b1);
b2=findViewById(R.id.b2);
b3=findViewById(R.id.b3);
t1=findViewById(R.id.t1);
tp1=findViewById(R.id.tp1);

tp1.setIs24HourView(false);

G. P. CO6I [MAD-22617] 183


MIRAJ ( S.
B.
SHINTRE )
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
t1.setText(getCurrentTime());
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String a=""+ (tp1.getCurrentHour()+2);
String b=""+ (tp1.getCurrentMinute()+15);
String c=a+":"+b;
t1.setText(c);
}
});
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String a=""+ (tp1.getCurrentHour()-2);
String b=""+ (tp1.getCurrentMinute()-15);
String c=a+":"+b;
t1.setText(c);
}
});

private String getCurrentTime() {


String s2=""+tp1.getCurrentHour()+":"+tp1.getCurrentMinute();
return s2;
}
}

Output:

G. P. CO6I [MAD-22617] 184


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 185
MIRAJ ( S.
B.
SHINTRE )
Date Picker
Android Date Picker allows you to select the date consisting of day, month and year in your
custom user interface. For this functionality android provides DatePicker and DatePickerDialog
components.

Methods :

1. getDayOfMonth()
This method gets the selected day of month

2. getMonth()
This method gets the selected month

3. getYear()
This method gets the selected year

4. setMaxDate(long maxDate)
This method sets the maximal date supported by this DatePicker in milliseconds since January
1, 1970 00:00:00 in getDefault() time zone

5. setMinDate(long minDate)
This method sets the minimal date supported by this NumberPicker in milliseconds since
January 1, 1970 00:00:00 in getDefault() time zone

6. setSpinnersShown(boolean shown)
This method sets whether the spinners are shown

7. updateDate(int year, int month, int dayOfMonth)


This method updates the current date

8. getCalendarView()

G. P. CO6I [MAD-22617] 186


MIRAJ ( S.
B.
SHINTRE )
This method returns calendar view

9. getFirstDayOfWeek()
This Method returns first day of the week

Example:

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


<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#26A69A"
tools:context=".MainActivity">

<DatePicker
android:id="@+id/t1"
android:layout_width="340dp"
android:layout_height="wrap_content"
android:layout_x="5dp"
android:layout_y="0dp"
android:background="#FFF9C4" />

<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="36dp"
android:layout_marginTop="10sp"
android:layout_x="100dp"
android:layout_y="450dp"
android:background="#EC407A"
android:text="SHOW"
android:textColor="#ffffff" />

</AbsoluteLayout>

Java Code:

package com.example.calender;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

G. P. CO6I [MAD-22617] 187


MIRAJ ( S.
B.
SHINTRE )
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {


DatePicker t1;
Button b1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=findViewById(R.id.b1);
t1=findViewById(R.id.t1);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

String day="Day= "+t1.getDayOfMonth();


String month="Month= "+ t1.getMonth();
String year="Year= "+t1.getYear();

Toast.makeText(getApplicationContext(),day+"\n"+month+"\n"+year,
Toast.LENGTH_SHORT).show();
}
});

}
Output:

G. P. CO6I [MAD-22617] 188


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 189
MIRAJ ( S.
B.
SHINTRE )
Extra Examples (Related to CH:4) :

WriteaprogramtodesignaSimpleCalculatorusingEditText

.xml file :

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent" android:layout_height="match_parent"

tools:context=".MainActivity"

android:orientation="vertical"

android:background="@drawable/backgroundim">

<LinearLayout android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#A3FFFFFF"

android:orientation="vertical">

<ScrollView android:layout_width="match_parent"

android:layout_height="match_parent">

<LinearLayout android:layout_width="match_parent"

android:layout_height="wrap_content"

G. P. CO6I [MAD-22617] 190


MIRAJ ( S.
B.
SHINTRE )
android:orientation="vertical" >

<ImageView android:id="@+id/imageView"

android:layout_width="120dp"

android:layout_height="120dp"

android:layout_gravity="center"

android:layout_marginTop="40dp"

app:srcCompat="@drawable/imgview" />

<EditText android:id="@+id/t1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginLeft="50dp"

android:layout_marginTop="30dp"

android:layout_marginRight="50dp"

android:ems="10"

android:hint="Enter First Number"

android:inputType="number" />

<EditText android:id="@+id/t2"

android:layout_width="match_parent" android:layout_height="wrap_content"

G. P. CO6I [MAD-22617] 191


MIRAJ ( S.
B.
SHINTRE )
android:layout_marginLeft="50dp"

android:layout_marginTop="10dp"

android:layout_marginRight="50dp"

android:ems="10" android:hint="Enter

Second Number"

android:inputType="number" />

<EditText android:id="@+id/t3"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginLeft="50dp"

android:layout_marginRight="50dp"

android:clickable="false"

android:editable="false" android:ems="10"

android:focusable="false"

android:hint="Answer" />

<Button android:id="@+id/b1"

android:layout_width="match_parent" android:layout_height="wrap_content"

android:layout_marginLeft="70dp" android:layout_marginTop="30dp"

G. P. CO6I [MAD-22617] 192


MIRAJ ( S.
B.
SHINTRE )
android:layout_marginRight="70dp" android:background="@drawable/round"

android:text="ADDITION" />

<Button android:id="@+id/b2"

android:layout_width="match_parent"

android:layout_height="wrap_content" android:layout_marginLeft="70dp"

android:layout_marginTop="20dp" android:layout_marginRight="70dp"

android:background="@drawable/round" android:text="SUBTRACTION" />

<Button android:id="@+id/b3"

android:layout_width="match_parent"

android:layout_height="wrap_content" android:layout_marginLeft="70dp"

android:layout_marginTop="20dp" android:layout_marginRight="70dp"

android:background="@drawable/round" android:text="MULTIPLICATION" />

<Button

G. P. CO6I [MAD-22617] 193


MIRAJ ( S.
B.
SHINTRE )
android:id="@+id/b4"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginLeft="70dp"

android:layout_marginTop="20dp"

android:layout_marginRight="70dp"

android:background="@drawable/round"

android:text="DIVISION" />

<Button android:id="@+id/b5"

android:layout_width="match_parent"

android:layout_height="wrap_content" android:layout_marginLeft="70dp"

android:layout_marginTop="20dp" android:layout_marginRight="70dp"

android:background="@drawable/round" android:text="MODULUS" />

</LinearLayout>

</ScrollView>

</LinearLayout>

</LinearLayout>

G. P. CO6I [MAD-22617] 194


MIRAJ ( S.
B.
SHINTRE )
.java file

package com.example.utkscalculator;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle; import

android.view.View;

import android.view.WindowManager; import

android.widget.Button;

import android.widget.EditText;

public class MainActivity extends AppCompatActivity { EditText

t1,t2,t3;

Button b1,b2,b3,b4,b5; String

s1,s2; @Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

getSupportActionBar().hide();

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.Layout
Params.FLAG_FULLSCREEN);

t1=findViewById(R.id.t1);

t2=findViewById(R.id.t2);

G. P. CO6I [MAD-22617] 195


MIRAJ ( S.
B.
SHINTRE )
t3=findViewById(R.id.t3);

b1=findViewById(R.id.b1);

b2=findViewById(R.id.b2);

b3=findViewById(R.id.b3);

b4=findViewById(R.id.b4);

b5=findViewById(R.id.b5);

b1.setOnClickListener(new View.OnClickListener() { @Override

public void onClick(View v) { int

a,b,ans;

a=Integer.parseInt(String.valueOf(t1.getText()));

b=Integer.parseInt(String.valueOf(t2.getText())); ans=a+b;

t3.setText("Addition : "+ans);

});

b2.setOnClickListener(new View.OnClickListener() { @Override

public void onClick(View v) { int

a,b,ans;

a=Integer.parseInt(String.valueOf(t1.getText())); b=Integer.parseInt(String.valueOf(t2.getText()));

G. P. CO6I [MAD-22617] 196


MIRAJ ( S.
B.
SHINTRE )
ans=a-b; t3.setText("Subtraction :

"+ans);

});

b3.setOnClickListener(new View.OnClickListener() { @Override

public void onClick(View v) { int

a,b,ans;

a=Integer.parseInt(String.valueOf(t1.getText()));

b=Integer.parseInt(String.valueOf(t2.getText())); ans=a*b;

t3.setText("Multiplication : "+ans);

});

b4.setOnClickListener(new View.OnClickListener() { @Override

public void onClick(View v) { int

a,b,ans;

a=Integer.parseInt(String.valueOf(t1.getText()));

b=Integer.parseInt(String.valueOf(t2.getText())); ans=a/b;

t3.setText("Division : "+ans);

G. P. CO6I [MAD-22617] 197


MIRAJ ( S.
B.
SHINTRE )
});

b5.setOnClickListener(new View.OnClickListener() { @Override

public void onClick(View v) { int

a,b,ans;

a=Integer.parseInt(String.valueOf(t1.getText()));

b=Integer.parseInt(String.valueOf(t2.getText())); ans=a%b;

t3.setText("Modulus : "+ans);

});

G. P. CO6I [MAD-22617] 198


MIRAJ ( S.
B.
SHINTRE )
Enter First Number 24
E n1e r 5 ecoild Number

Answe

20

10a

Multiplication: 200

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 199


Bakery Card

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

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent" android:layout_height="match_parent"

android:background="@drawable/cake"

tools:context=".MainActivity">

<TextView android:layout_width="410sp"

android:layout_height="102dp"

android:paddingTop="30sp"

android:background="#FBE9E7"

android:textAlignment="center"

android:text="THE BELL BAKERS"

android:textStyle="italic"

android:textAppearance="@style/TextAppearance.AppCompat"

android:textColor="#8E24AA"

android:textSize="40sp"

android:layout_x="0sp"

android:layout_y="0sp"

/>

G. P. CO6I [MAD-22617] 200


MIRAJ ( S.
B.
SHINTRE )
<TextView

android:layout_width="203dp"

android:layout_height="53dp"

android:layout_marginTop="300sp"

android:layout_x="31dp"

android:layout_y="204dp"

android:text="Do Visit Again"

android:textAlignment="center"

android:textColor="#8E24AA"

android:textSize="30sp"

android:textStyle="italic"/>

<TextView android:layout_width="209dp"

android:layout_height="58dp"

android:layout_marginTop="300sp"

android:layout_x="21dp"

android:layout_y="136dp"

android:text="Thank you"

android:textAlignment="center"

android:textColor="#8E24AA"

android:textSize="30sp"

android:textStyle="italic"/>

<TextView

G. P. CO6I [MAD-22617] 201


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="206dp"

android:layout_height="42dp"

android:layout_marginTop="300sp" android:layout_x="8dp"

android:layout_y="443dp" android:text="Contact us via:"

android:textAlignment="center"

android:textAppearance="@style/TextAppearance.AppCompat"

android:textColor="#8E24AA"

android:textSize="20sp"

android:textStyle="italic" />

<ImageView android:layout_width="67dp"

android:layout_height="70dp"

android:layout_marginTop="300sp"

android:layout_x="4dp"

android:layout_y="495dp"

android:src="@drawable/calling" />

<ImageView android:layout_width="80dp"

android:layout_height="68dp"

android:layout_marginStart="8dp"

android:layout_marginLeft="8dp"

G. P. CO6I [MAD-22617] 202


MIRAJ ( S.
B.
SHINTRE )
android:layout_marginTop="350sp" android:layout_x="3dp"

android:layout_y="570dp"

android:src="@drawable/msg_two" />

<ImageView android:layout_width="70dp"

android:layout_height="74dp"

android:layout_marginStart="8dp"

android:layout_marginLeft="8dp"

android:layout_marginTop="350sp"

android:layout_x="5dp"

android:layout_y="651dp"

android:src="@drawable/world" />

<TextView

android:layout_width="167dp"

android:layout_height="50sp"

android:layout_marginStart="8dp"

android:layout_marginLeft="8dp"

android:layout_marginTop="300sp" android:layout_x="119dp"

android:layout_y="502dp" android:autoLink="phone"

G. P. CO6I [MAD-22617] 203


MIRAJ ( S.
B.
SHINTRE )
android:text="9876543210" android:textColor="#8E24AA" />

<TextView android:layout_width="214dp"

android:layout_height="50sp"

android:layout_marginStart="8dp"

android:layout_marginLeft="8dp"

android:layout_marginTop="350sp"

android:layout_x="119dp"

android:layout_y="565dp"

android:autoLink="email"

android:text="[email protected]" android:textColorLink="#8E24AA"/>

<TextView android:layout_width="185dp"

android:layout_height="50sp"

android:layout_marginStart="8dp"

android:layout_marginLeft="8dp"

android:layout_marginTop="350sp"

android:layout_x="121dp"

android:layout_y="653dp"

android:autoLink="web"

android:text="www.bellbakers.com"

android:textColorLink="#8E24AA" />

</AbsoluteLayout>

G. P. CO6I [MAD-22617] 204


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 205
MIRAJ ( S.
B.
SHINTRE )
Student form

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

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent" android:layout_height="match_parent"

android:background="@drawable/img"

android:orientation="vertical"

tools:context=".MainActivity">

<TextView android:layout_width="match_parent"

android:layout_height="77dp"

android:text="Student Form"

android:textAlignment="center"

android:textStyle="bold"

android:textColor="#ffffff"

android:fontFamily="monospace"

android:textSize="40sp" />

<TableRow

android:layout_width="350dp"

android:layout_height="70dp">

G. P. CO6I [MAD-22617] 206


MIRAJ ( S.
B.
SHINTRE )
<TextView android:layout_width="117dp"

android:layout_height="65dp"

android:fontFamily="monospace"

android:text=" Name:"

android:textColor="#ffffff"

android:textSize="20sp"

android:textStyle="bold" />

<EditText android:layout_width="180dp"

android:layout_height="65dp"

android:textColor="#ffffff" />

</TableRow>

<TableRow

android:layout_width="120dp"

android:layout_height="70dp">

<TextView android:layout_width="wrap_content"

android:layout_height="65dp"

android:fontFamily="monospace" android:text="

Phone no:" android:layout_marginTop="20sp"

android:textColor="#ffffff"

G. P. CO6I [MAD-22617] 207


MIRAJ ( S.
B.
SHINTRE )
android:textSize="20sp"

android:textStyle="bold" />

<EditText android:layout_width="241dp"

android:layout_height="65dp"

android:inputType="phone"

android:layout_marginTop="20sp"

android:textColor="#ffffff" />

</TableRow>

<TableRow

android:layout_width="120dp"

android:layout_height="70dp">

<TextView android:layout_width="wrap_content"

android:layout_height="65dp"

android:fontFamily="monospace" android:text="

Birth Date:" android:layout_marginTop="20sp"

android:textColor="#ffffff" android:textSize="20sp"

android:textStyle="bold" />

<EditText

G. P. CO6I [MAD-22617] 208


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="241dp"

android:layout_height="65dp"

android:layout_marginTop="20sp"

android:textColor="#ffffff" />

</TableRow>

<TableRow

android:layout_width="120dp"

android:layout_height="70dp">

<TextView android:layout_width="wrap_content"

android:layout_height="65dp"

android:fontFamily="monospace" android:text="

Address:" android:layout_marginTop="20sp"

android:textColor="#ffffff" android:textSize="20sp"

android:textStyle="bold" />

<EditText android:layout_width="241dp"

android:layout_height="65dp"

android:layout_marginTop="20sp"

android:textColor="#ffffff" />

</TableRow>

<TableRow android:layout_width="120dp"

G. P. CO6I [MAD-22617] 209


MIRAJ ( S.
B.
SHINTRE )
android:layout_height="70dp">

<Button android:layout_width="165dp"

android:layout_height="61dp"

android:fontFamily="monospace"

android:text="Submit"

android:textSize="20sp"

android:background="@drawable/round"

android:layout_marginTop="30sp"

android:textStyle="bold" />

<Button android:layout_width="wrap_content"

android:layout_height="65dp"

android:fontFamily="monospace"

android:text="Cancel"

android:background="@drawable/round"

android:layout_marginTop="30sp"

android:textSize="20sp"

android:layout_marginLeft="30sp"

android:layout_marginStart="30sp"

android:layout_marginRight="50sp"

android:layout_marginEnd="50sp"

android:textStyle="bold" />

</TableRow>

</TableLayout>

G. P. CO6I [MAD-22617] 210


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 211
MIRAJ ( S.
B.
SHINTRE )
Toggle Button

.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<ImageView android:id="@+id/i1"
android:layout_width="match_parent"
android:layout_height="385dp"
android:src="@drawable/offbulb" />
<ToggleButton android:id="@+id/tb1"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginTop="10sp"
android:layout_marginStart="150sp"
android:layout_marginLeft="150sp" android:text="OFF"
/>
</LinearLayout>

.java file
package com.example.prac91;

import androidx.appcompat.app.AppCompatActivity; import

android.os.Bundle;
import android.view.View;
import android.widget.Button; import
android.widget.ImageView; import
android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

G. P. CO6I [MAD-22617] 212


MIRAJ ( S.
B.
SHINTRE )
ImageView i1; ToggleButton tb1;

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

private void addListenerOnButton() { tb1=findViewById(R.id.tb1);


i1=(ImageView)findViewById(R.id.i1); tb1.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) { String s1;
s1= (String) tb1.getText(); if(s1.equals("OFF"))
i1.setImageResource(R.drawable.onbulb); else
i1.setImageResource(R.drawable.offbulb);
}
});
}
}

G. P. CO6I [MAD-22617] 213


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 214
MIRAJ ( S.
B.
SHINTRE )
Image Button

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


<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#EE000000" tools:context=".MainActivity">

<ImageButton android:layout_width="731dp"
android:layout_height="51dp"
android:layout_x="5dp" android:layout_y="4dp"
android:background="@drawable/round"
android:src="@drawable/top" />

<TextView android:id="@+id/t1"
android:layout_width="436dp"
android:layout_height="44dp"
android:layout_x="90dp" android:layout_y="97dp"
android:text="Ankita is presenting screen"
android:textAlignment="center"
android:textColor="#ffffff" android:textSize="20sp"
/>

<ImageButton android:id="@+id/b1"
android:layout_width="132dp"
android:layout_height="104dp"
android:layout_x="0dp"
android:layout_y="169dp"
android:background="@drawable/round"
android:onClick="end" android:src="@drawable/end"/>

G. P. CO6I [MAD-22617] 215


MIRAJ ( S.
B.
SHINTRE )
<ImageButton android:id="@+id/b2"
android:onClick="vedio"
android:layout_width="104dp"
android:layout_height="108dp"
android:layout_x="137dp"
android:layout_y="170dp"
android:background="@drawable/round" android:src="@drawable/vedio" />

<ImageButton android:id="@+id/b3"
android:onClick="mic"
android:layout_width="110dp"
android:layout_height="103dp"
android:layout_x="244dp"
android:layout_y="170dp"
android:background="@drawable/round" android:src="@drawable/mic"/>

<ImageButton android:id="@+id/b4"
android:onClick="hand"
android:layout_width="116dp"
android:layout_height="104dp"
android:layout_x="373dp"
android:layout_y="172dp"
android:background="@drawable/round" android:src="@drawable/hand" />

<ImageButton android:onClick="dots"
android:id="@+id/b5"
android:layout_width="128dp"
android:layout_height="113dp"
android:layout_x="506dp"
android:layout_y="165dp"

G. P. CO6I [MAD-22617] 216


MIRAJ ( S.
B.
SHINTRE )
android:background="@drawable/round" android:src="@drawable/dots"/>

</AbsoluteLayout>

.java file
package com.example.prac92;

import androidx.appcompat.app.AppCompatActivity; import

android.os.Bundle;
import android.view.View;
import android.widget.ImageButton; import
android.widget.TextView; import
android.widget.Toast;

public class MainActivity extends AppCompatActivity { ImageButton


b1,b2,b3,b4,b5;
TextView t1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); b1=findViewById(R.id.b1);
b2=findViewById(R.id.b2); b3=findViewById(R.id.b3);
b4=findViewById(R.id.b4); b5=findViewById(R.id.b5);
t1=findViewById(R.id.t1);

public void end(View view) {


Toast.makeText(this, "Ending Meet!", Toast.LENGTH_SHORT).show();
}

public void vedio(View view) { t1.setText("Ankita


turned vedio on");

G. P. CO6I [MAD-22617] 217


MIRAJ ( S.
B.
SHINTRE )
Toast.makeText(this, "You turned vedio on", Toast.LENGTH_SHORT).show();

public void mic(View view) { t1.setText("Ankita


turned mic on");
Toast.makeText(this, "You turned mic on", Toast.LENGTH_SHORT).show();
}

public void hand(View view) { t1.setText("Ankita


raised her hand");
Toast.makeText(this,"You raised your hand",Toast.LENGTH_SHORT).show();
}

public void dots(View view) {


Toast.makeText(this, "In call messages started", Toast.LENGTH_SHORT).show();
}

G. P. CO6I [MAD-22617] 218


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 219
MIRAJ ( S.
B.
SHINTRE )
ImageButton
XML code
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity"
>

<ImageButton
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_y="50dp"
android:layout_x="100dp"
android:src="@drawable/b1"
android:scaleType="centerCrop"
android:onClick="p1"
android:id="@+id/i1"
/>
<ImageButton
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_y="250dp"
android:layout_x="100dp"
android:src="@drawable/b2"
android:scaleType="centerCrop"
android:onClick="b1"
android:id="@+id/i2"
/>
<ImageButton
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_y="450dp"
android:layout_x="100dp"
android:src="@drawable/b3"
android:scaleType="centerCrop"
android:onClick="f1"

G. P. CO6I [MAD-22617] 220


MIRAJ ( S.
B.
SHINTRE )
android:id="@+id/i3"
/>

</AbsoluteLayout>

Java File
package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity; import

android.os.Bundle;
import android.view.View;
importandroid.widget.ImageButton; import
android.widget.Toast;

public class MainActivity extends AppCompatActivity {

ImageButton i1,i2,i3;

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

i1=findViewById(R.id.i1);
i2=findViewById(R.id.i2);
i3=findViewById(R.id.i3);
}

public void p1(Viewview){


Toast.makeText(this, "You Ordered Pizza ",Toast.LENGTH_LONG).show();
}

public void b1(View view) {


Toast.makeText(this, "You Ordered Burger ",Toast.LENGTH_LONG).show();
}

public void f1(View view) {


Toast.makeText(this, "You Ordered Fries ",Toast.LENGTH_LONG).show();
}
}
Output:

G. P. CO6I [MAD-22617] 221


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 222
MIRAJ ( S.
B.
SHINTRE )
ImageButton
Xml code

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical" android:gravity="center"
android:background="@drawable/b">

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

<TextView android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="50dp"
android:text="What's Your Hobby ?"
android:gravity="center"
android:textStyle="bold"
android:textSize="20dp"
android:textColor="@color/black"
android:fontFamily="serif"
/>

</LinearLayout>

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

<ImageButton android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="@drawable/b1"
android:onClick="bg1" android:id="@+id/bt1"
/>

G. P. CO6I [MAD-22617] 223


MIRAJ ( S.
B.
SHINTRE )
<ImageButton android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="20dp"
android:background="@drawable/b2"
android:onClick="bg2" android:id="@+id/bt2"
/>

</LinearLayout>

<LinearLayout android:layout_width="wrap_content"

android:layout_height="wrap_content">

<ImageButton android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="@drawable/b3"
android:onClick="bg3" android:id="@+id/bt3"
/>
<ImageButton android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="20dp"
android:background="@drawable/b4"
android:onClick="bg4" android:id="@+id/bt4"
/>

</LinearLayout>

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

<ImageButton android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="@drawable/b5"
android:onClick="bg5" android:id="@+id/bt5"
/>

G. P. CO6I [MAD-22617] 224


MIRAJ ( S.
B.
SHINTRE )
<ImageButton android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="100dp"

android:background="@drawable/b6"
android:onClick="bg6" android:id="@+id/bt6"
/>

</LinearLayout>
</LinearLayout>

Java Code

package com.example.imagebuttonprac4;

import androidx.appcompat.app.AppCompatActivity; import

android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity { @Override


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

public void bg1(View view) { Toast.makeText(this,"Gaming",Toast.LENGTH_LONG).show();


}

public void bg2(View view) { Toast.makeText(this,"Art",Toast.LENGTH_LONG).show();


}

public void bg3(View view) { Toast.makeText(this,"Coding",Toast.LENGTH_LONG).show();


}

public void bg4(View view) { Toast.makeText(this,"Shopping",Toast.LENGTH_LONG).show();

public void bg5(View view) { Toast.makeText(this,"Reading",Toast.LENGTH_LONG).show();


}

public void bg6(View view) { Toast.makeText(this,"Travelling",Toast.LENGTH_LONG).show();

G. P. CO6I [MAD-22617] 225


MIRAJ ( S.
B.
SHINTRE )
}
}

Output:

G. P. CO6I [MAD-22617] 226


MIRAJ ( S.
B.
SHINTRE )
Calci
Xml code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical" android:gravity="center"
android:background="@drawable/i2"
>

<EditText android:layout_width="100dp"
android:layout_height="100dp"
android:background="#E91E63"
android:layout_margin="10dp"
android:id="@+id/t1"
android:gravity="center"
/>

<Button android:layout_width="100dp"
android:layout_height="100dp"
android:text="+"
android:textSize="50dp"
android:layout_margin="10dp"
android:gravity="center"
/>

<EditText android:layout_width="100dp"
android:layout_height="100dp"
android:background="#E91E63"
android:layout_margin="10dp"
android:id="@+id/t2"
android:gravity="center"

G. P. CO6I [MAD-22617] 227


MIRAJ ( S.
B.
SHINTRE )
/>

<Button android:layout_width="100dp"
android:layout_height="100dp"
android:text="="
android:textSize="50dp"
android:layout_margin="10dp"
android:gravity="center"
android:id="@+id/b1"
android:onClick="add"
/>

<EditText android:layout_width="100dp"
android:layout_height="100dp"
android:background="#E91E63"
android:layout_margin="10dp"
android:id="@+id/t3"
android:gravity="center"
/>

</LinearLayout>

Java Code

package com.example.buttonprac1;

import androidx.appcompat.app.AppCompatActivity; import

android.os.Bundle;
import android.view.View; import
android.widget.EditText;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity { EditText


t1,t2,t3;

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

G. P. CO6I [MAD-22617] 228


MIRAJ ( S.
B.
SHINTRE )
t1=findViewById(R.id.t1);
t2=findViewById(R.id.t2);
t3=findViewById(R.id.t3);

}
public void add(View view) { int

s1,s2,s3;

s1=Integer.parseInt(t1.getText().toString());
s2=Integer.parseInt(t2.getText().toString()); s3=s1+s2;

t3.setText(Integer.toString(s3));
}
}

Output:

G. P. CO6I [MAD-22617] 229


MIRAJ ( S.
B.
SHINTRE )
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center"
android:id="@+id/l1"
>

<TextView android:layout_width="300dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:id="@+id/t1"
android:gravity="center"
android:text="Choose Background Color :"
android:textSize="20dp"
android:textColor="@color/black"
android:textStyle="bold"
android:fontFamily="casual"
/>

<Button android:layout_width="250dp"
android:layout_height="60dp"
android:text="1) GREEN"
android:textSize="30dp"
android:layout_margin="10dp"
android:gravity="center"
android:textStyle="bold"
android:fontFamily="casual"
android:backgroundTint="#FFC107"
android:onClick="g"
/>

<Button android:layout_width="250dp"

G. P. CO6I [MAD-22617] 230


MIRAJ ( S.
B.
SHINTRE )
android:layout_height="60dp" android:text="2)
YELLOW" android:textSize="30dp"
android:layout_margin="10dp" android:gravity="center"
android:textStyle="bold" android:fontFamily="casual"
android:backgroundTint="#FFC107" android:onClick="y"
/>

<Button android:layout_width="250dp"
android:layout_height="60dp"
android:text="3) RED"
android:textSize="30dp"
android:layout_margin="10dp"
android:gravity="center"
android:textStyle="bold"
android:fontFamily="casual"
android:backgroundTint="#FFC107"
android:onClick="r"
/>

<Button android:layout_width="250dp"
android:layout_height="60dp"
android:text="4) CYAN"
android:textSize="30dp"
android:layout_margin="10dp"
android:gravity="center"
android:textStyle="bold"
android:fontFamily="casual"
android:backgroundTint="#FFC107"
android:onClick="c"
/>

</LinearLayout>

Java Code

package com.example.buttonprac4;

G. P. CO6I [MAD-22617] 231


MIRAJ ( S.
B.
SHINTRE )
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color; import


android.os.Bundle; import
android.view.View;
import android.widget.AbsoluteLayout; import
android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

LinearLayout l1;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

l1 = (LinearLayout)findViewById(R.id.l1);
}

public void g(View view) {


l1.setBackgroundColor(Color.GREEN);
}

public void y(View view) {


l1.setBackgroundColor(Color.YELLOW);
}

public void r(View view) { l1.setBackgroundColor(Color.RED);


}

public void c(View view) { l1.setBackgroundColor(Color.CYAN);


}
}

Output:

G. P. CO6I [MAD-22617] 232


MIRAJ ( S.
B.
SHINTRE )
Choose Background Color

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 233


XOXO Game

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@drawable/b1"
android:orientation="vertical"
>

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

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#E91E63"
android:layout_marginTop="50dp"
android:background="#05BB86FC"
android:layout_marginLeft="10dp"
/>

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#9C27B0"
android:background="#05BB86FC"
android:layout_marginTop="50dp"
android:layout_marginLeft="20dp"
/>

</LinearLayout>

G. P. CO6I [MAD-22617] 234


MIRAJ ( S.
B.
SHINTRE )
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#E91E63"
android:background="#05BB86FC"
android:layout_marginTop="50dp"
android:layout_marginLeft="120dp"
/>

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#9C27B0"
android:background="#05BB86FC"
android:layout_marginTop="50dp"
android:layout_marginLeft="40dp"
/>

</LinearLayout>

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

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" android:textStyle="bold"

G. P. CO6I [MAD-22617] 235


MIRAJ ( S.
B.
SHINTRE )
android:textSize="100dp"
android:textColor="#9C27B0"
android:background="#05BB86FC"
android:layout_marginTop="40dp"
android:layout_marginLeft="10dp"
/>

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#E91E63"
android:background="#05BB86FC"
android:layout_marginTop="40dp"
android:layout_marginLeft="20dp"
/>

</LinearLayout>

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@drawable/b1"
android:orientation="vertical"
>

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

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"

G. P. CO6I [MAD-22617] 236


MIRAJ ( S.
B.
SHINTRE )
android:textSize="100dp"
android:textColor="#E91E63"
android:layout_marginTop="50dp"
android:background="#05BB86FC"
android:layout_marginLeft="10dp"
/>

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#9C27B0"
android:background="#05BB86FC"
android:layout_marginTop="50dp"
android:layout_marginLeft="20dp"
/>

</LinearLayout>

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

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#E91E63"
android:background="#05BB86FC"
android:layout_marginTop="50dp"
android:layout_marginLeft="120dp"
/>

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O"

G. P. CO6I [MAD-22617] 237


MIRAJ ( S.
B.
SHINTRE )
android:textStyle="bold"
android:textSize="100dp"
android:textColor="#9C27B0"
android:background="#05BB86FC"
android:layout_marginTop="50dp"
android:layout_marginLeft="40dp"
/>

</LinearLayout>

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

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#9C27B0"
android:background="#05BB86FC"
android:layout_marginTop="40dp"
android:layout_marginLeft="10dp"
/>

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#E91E63"
android:background="#05BB86FC"
android:layout_marginTop="40dp"
android:layout_marginLeft="20dp"
/>

</LinearLayout>

</LinearLayout>

G. P. CO6I [MAD-22617] 238


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 239
MIRAJ ( S.
B.
SHINTRE )
Menu Card
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#0D5287">

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

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Menu card"
android:textSize="50dp"
android:layout_marginTop="30dp"
android:layout_gravity="center_horizontal"
android:textColor="#00BCD4"
android:fontFamily="sans-serif-smallcaps"
/>
</LinearLayout>

<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:background="#607D9A">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:textStyle="bold"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="20dp"
android:text="Sr no"/>
<TextView

G. P. CO6I [MAD-22617] 240


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:textStyle="bold"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="30dp"
android:text="Name"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:textStyle="bold"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="Cost"
/>
</TableRow>

<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="1"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Veg Pizza"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"

G. P. CO6I [MAD-22617] 241


MIRAJ ( S.
B.
SHINTRE )
android:text="100/-"
/>

</TableRow>
<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="2"
android:textAlignment="center"/>

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Aloo Tikki Burger"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="75/-"
/>
</TableRow><TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="3"
android:textAlignment="center"/>

G. P. CO6I [MAD-22617] 242


MIRAJ ( S.
B.
SHINTRE )
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"

G. P. CO6I [MAD-22617] 243


MIRAJ ( S.
B.
SHINTRE )
android:layout_marginLeft="30dp"
android:text="Sizzling Brownie"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="99/-"
/>
</TableRow><TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="4"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="French Sandwitch"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="85/-"
/>
</TableRow><TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView

G. P. CO6I [MAD-22617] 244


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="5"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Blue Lagoon"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="90/-"
/>
</TableRow>
<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="6"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Cold Coffee"/>
<TextView android:layout_width="wrap_content"

G. P. CO6I [MAD-22617] 245


MIRAJ ( S.
B.
SHINTRE )
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="80/-"
/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="7"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Fruit Mojito"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="70/-"
/>
</TableRow>
<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"

G. P. CO6I [MAD-22617] 246


MIRAJ ( S.
B.
SHINTRE )
android:layout_marginLeft="10dp"
android:text="8"
android:textAlignment="center"/>

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Cappuccino"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="105/-"
/>
</TableRow>
<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="9"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Peri Peri fries"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"

G. P. CO6I [MAD-22617] 247


MIRAJ ( S.
B.
SHINTRE )
android:text="95/-"
/>
</TableRow>
<TableRow

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="10"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Cad B"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="120/-"
/>
</TableRow>
</TableLayout>.

G. P. CO6I [MAD-22617] 248


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 249
MIRAJ ( S.
B.
SHINTRE )
Compass:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@color/black">

<ImageView android:layout_width="wrap_content"
android:layout_height="400dp"
android:src="@drawable/compass"/>

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="147°\nSoutheast"
android:textColor="@color/design_default_color_surface" android:textSize="40sp"
android:textAlignment="center"
android:layout_x="110dp"
android:layout_y="430dp"/>

</AbsoluteLayout>

G. P. CO6I [MAD-22617] 250


MIRAJ ( S.
B.
SHINTRE )
Wallpaper:

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


<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/bc"
tools:context=".MainActivity">

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2:05" android:textSize="60dp"
android:textColor="@color/design_default_color_surface" android:layout_x="10dp"
android:layout_y="10dp"

G. P. CO6I [MAD-22617] 251


MIRAJ ( S.
B.
SHINTRE )
/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PM"
android:textColor="@color/design_default_color_surface" android:textSize="23dp"
android:layout_x="133dp" android:layout_y="52dp"
/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Thursday, 29 April"
android:textColor="@color/design_default_color_surface" android:textSize="20dp"
android:layout_x="10dp" android:layout_y="85dp"
/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Airtel" android:textSize="30dp"
android:textColor="@color/design_default_color_surface" android:layout_x="20dp"
android:layout_y="550dp"
/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="|" android:textSize="40dp"
android:textColor="@color/design_default_color_surface" android:layout_x="100dp"
android:layout_y="540dp"
/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Swipe to unlock"
android:textSize="25dp"

G. P. CO6I [MAD-22617] 252


MIRAJ ( S.
B.
SHINTRE )
android:textColor="@color/design_default_color_surface" android:layout_x="120dp"
android:layout_y="560dp"
/>
</AbsoluteLayout>

G. P. CO6I [MAD-22617] 253


MIRAJ ( S.
B.
SHINTRE )
Social media request list:

Code:
<?xml version="1.0" encoding="utf-8"?> xmlns:app="http://schemas.android.co
m/apk/res-auto"
<RelativeLayout
xmlns:android="http://schemas.android.
com/apk/res/android" xmlns:tools="http://schemas.android.co
m/tools"

G. P. CO6I [MAD-22617] 254


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_height="match_parent"
android:text="Confirm"
tools:context=".MainActivity">
android:textSize="20dp"
android:textStyle="normal"
<ImageView android:id="@+id/img1"
android:backgroundTint="#2196F3"
android:layout_width="100dp"
android:textColor="#FFFF"
android:layout_height="100dp"

android:layout_toRightOf="@+id/img1"
android:layout_alignParentLeft="true"
android:layout_marginTop="60dp"

android:layout_alignParentTop="true" android:id="@+id/btn1"

android:layout_marginLeft="4dp" />

android:layout_marginTop="15dp" <Button
android:src="@drawable/pro5" />
android:layout_width="wrap_content"
<TextView

android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Delete"

android:layout_height="wrap_content" android:textSize="20dp"

android:text="John Martin" android:textStyle="normal"

android:textSize="20dp" android:backgroundTint="#BEBFBF"
android:textColor="#151515"
android:layout_toEndOf="@+id/img1"
android:layout_marginTop="25dp" android:layout_toRightOf="@+id/btn1"

/> android:layout_marginTop="60dp"

<Button android:id="@+id/btn2"
/>
android:layout_width="wrap_content"

<ImageView

G. P. CO6I [MAD-22617] 255


MIRAJ ( S.
B.
SHINTRE )
android:id="@+id/img2" android:layout_height="wrap_content"
android:layout_width="100dp" android:text="Confirm"
android:layout_height="100dp" android:textSize="20dp"
android:textStyle="normal"
android:layout_alignParentLeft="true" android:backgroundTint="#2196F3"
android:textColor="#FFFF"
android:layout_alignParentBottom="true
"
android:layout_toRightOf="@+id/img2"
android:layout_marginLeft="4dp"
android:layout_below="@+id/text5"

android:layout_marginBottom="16dp" android:layout_marginTop="10dp"

android:src="@drawable/pro3" android:id="@+id/bt9"

/> />

<TextView <Button

android:layout_width="wrap_content" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:layout_height="wrap_content"

android:text="Lilly" android:text="Delete"

android:textSize="20dp" android:textSize="20dp"
android:textStyle="normal"
android:layout_toEndOf="@+id/img2" android:backgroundTint="#BEBFBF"
android:layout_below="@+id/btn7" android:textColor="#151515"
android:layout_marginTop="55dp"
android:id="@+id/text5" android:layout_toRightOf="@+id/bt9"

/> android:layout_below="@+id/text5"

<Button android:layout_marginTop="10dp"
android:id="@+id/btn10"
android:layout_width="wrap_content" />

G. P. CO6I [MAD-22617] 256


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="wrap_content"
<ImageView android:id="@+id/img3"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_height="100dp"
android:text="Confirm"
android:textSize="20dp"
android:layout_alignParentLeft="true"
android:textStyle="normal"

android:layout_centerInParent="true" android:backgroundTint="#2196F3"
android:textColor="#FFFF"

android:layout_centerHorizontal="true"
android:layout_toRightOf="@+id/img3"
android:layout_marginLeft="4dp"
android:layout_below="@+id/text3"
android:src="@drawable/pro4" />
android:id="@+id/btn5"
<TextView
/>

android:layout_width="wrap_content" <Button

android:layout_height="wrap_content" android:layout_width="wrap_content"
android:text="Dragon"
android:textSize="20dp" android:layout_height="wrap_content"
android:layout_marginLeft="10dp" android:text="Delete"
android:textSize="20dp"
android:layout_toEndOf="@+id/img3"
android:textStyle="normal"
android:layout_below="@+id/btn3"
android:backgroundTint="#BEBFBF"
android:layout_marginTop="50dp"
android:textColor="#151515"
android:id="@+id/text3"
/> android:layout_toRightOf="@+id/btn5"
android:layout_below="@+id/text3"
<Button android:id="@+id/btn6"
/>

G. P. CO6I [MAD-22617] 257


MIRAJ ( S.
B.
SHINTRE )
<ImageView android:id="@+id/img4" android:text="Confirm"
android:layout_width="100dp" android:textSize="20dp"
android:layout_height="100dp" android:textStyle="normal"
android:layout_above="@+id/img3" android:backgroundTint="#2196F3"
android:textColor="#FFFF"
android:layout_alignParentLeft="true"

android:layout_toRightOf="@+id/img3"
android:layout_centerInParent="true"
android:layout_below="@+id/text2"
android:layout_marginLeft="4dp"
android:id="@+id/btn3"
/>
android:layout_marginBottom="23dp"
android:src="@drawable/pro6" /> <Button

<TextView
android:layout_width="wrap_content"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_height="wrap_content" android:text="Delete"
android:textSize="20dp"
android:text="Shinchan"
android:textStyle="normal"
android:textSize="20dp"
android:backgroundTint="#BEBFBF"
android:id="@+id/text2"
android:textColor="#151515"
android:layout_toEndOf="@+id/img3"
android:layout_toRightOf="@+id/btn3"
android:layout_marginTop="150dp"
android:layout_below="@+id/text2"
/>
android:id="@+id/btn4"
<Button
/>
android:layout_width="wrap_content"

<ImageView android:id="@+id/img5"
android:layout_height="wrap_content"

G. P. CO6I [MAD-22617] 258


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_height="100dp"
android:text="Confirm"
android:layout_above="@+id/img2"
android:textSize="20dp"
android:layout_alignParentLeft="true" android:textStyle="normal"
android:backgroundTint="#2196F3"
android:layout_centerInParent="true" android:textColor="#FFFF"
android:layout_marginLeft="4dp"
android:layout_toRightOf="@+id/img5"
android:layout_marginBottom="26dp" android:layout_below="@+id/text4"
android:src="@drawable/pro7" /> android:id="@+id/btn7"
<TextView />

<Button
android:layout_width="wrap_content"

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Doremon"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="Delete"
android:layout_marginLeft="10dp"
android:textSize="20dp"
android:textStyle="normal"
android:layout_toEndOf="@+id/img5"
android:backgroundTint="#BEBFBF"
android:layout_below="@+id/btn5"
android:textColor="#151515"
android:layout_marginTop="25dp"
android:id="@+id/text4"
android:layout_toRightOf="@+id/btn7"
/>
android:layout_below="@+id/text4"
android:id="@+id/btn8"
<Button />
</RelativeLayout>
android:layout_width="wrap_content"

G. P. CO6I [MAD-22617] 259


MIRAJ ( S.
B.
SHINTRE )
Wheather app:

G. P. CO6I [MAD-22617] 260


MIRAJ ( S.
B.
SHINTRE )
android:layout_x="100dp"

android:layout_y="100dp"
<?xml version="1.0" encoding="utf-8"?>
android:src="@drawable/sun"/>
<AbsoluteLayout
xmlns:android="http://schemas.android.com/
apk/res/android"

xmlns:app="http://schemas.android.com/apk
/res-auto"

xmlns:tools="http://schemas.android.com/to
ols"

android:layout_width="match_parent"
android:layout_height="match_parent"

android:background="@drawable/gradient_
background"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:fontFamily="sans-serif-
smallcaps"
android:textColor="#0E87C4"
android:layout_x="10dp"
android:layout_y="20dp"
android:text="Sangli-Miraj-Kupwad"

android:textSize="35sp"
android:drawablePadding="10dp"/>
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"

G. P. CO6I [MAD-22617] 261


MIRAJ ( S.
B.
SHINTRE )
<TextView android:layout_height="wrap_content"

android:layout_width="wrap_co android:fontFamily="sans-serif-smallcaps"

ntent"
android:textColor="@color/design_default_color
android:layout_height="wrap_c _surface"

ontent" android:layout_x="310dp"

android:fontFamily="sans-serif- android:layout_y="150dp"

smallcaps" android:text="F"

android:textColor="#FFFFFF" android:textSize="30sp"/>

android:layout_x="190dp"
android:layout_y="100dp"
android:text="37°"
android:textSize="80sp"/>

<TextView
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_c
ontent"
android:fontFamily="sans-serif-
smallcaps"
android:textColor="#FFFFFF"
android:layout_x="310dp"
android:layout_y="110dp"
android:text="C"

android:textSize="30sp"/>

<TextView
android:layout_width="wrap_co
ntent"

G. P. CO6I [MAD-22617] 262


MIRAJ ( S.
B.
SHINTRE )
<TextView smallcaps"

android:layout_width="wrap_content"
android:textColor="@color/design_default_c
android:layout_height="wrap_content" olor_surface"

android:fontFamily="sans-serif-
smallcaps"

android:textColor="@color/design_default_c
olor_surface"

android:layout_x="100dp"
android:layout_y="200dp"
android:text="Hazy Sunshine"
android:textSize="35sp"/>

<TextView
android:layout_width="370dp"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-
smallcaps"

android:textColor="@color/design_default_c
olor_surface"
android:layout_x="20dp"
android:layout_y="260dp"

android:text="Expect partly sunny


skies. The high will be 38°."
android:textAlignment="center"
android:textSize="20sp"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-

G. P. CO6I [MAD-22617] 263


MIRAJ ( S.
B.
SHINTRE )
android:layout_x="20dp" android:textSize="20sp"

android:layout_y="350dp" android:textStyle="bold"/>

android:text="Today"

android:textSize="20sp"/> <TextView
android:layout_width="wrap_content"

<ImageView android:layout_height="wrap_content"

android:layout_width="50d android:fontFamily="sans-serif-smallcaps"

p"
android:textColor="@color/design_default_color
android:layout_height="45d _surface"

p" android:layout_x="20dp"

android:layout_y="390dp"
android:src="@drawable/s
un"/>

<TextView
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_c

ontent"
android:fontFamily="sans-serif-
smallcaps"

android:textColor="@color/design_default_color
_surface"

android:layout_

x="30dp"
android:layout_

y="450dp"
android:text="3
7°"

G. P. CO6I [MAD-22617] 264


MIRAJ ( S.
B.
SHINTRE )
android:layout_x="30dp" android:textColor="@color/design_default_c
olor_surface"
android:layout_y="490dp"

android:text="24°"

android:textSize="20sp"/>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:fontFamily="sans-serif-
smallcaps"

android:textColor="@color/design_default_c
olor_surface"

android:layout_x="100dp"
android:layout_y="350dp"
android:text="Tue 27"
android:textSize="20sp"/>

<ImageView
android:layout_width="50dp"

android:layout_height="45dp"
android:layout_x="100dp"
android:layout_y="390dp"
android:src="@drawable/sun"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-
smallcaps"

G. P. CO6I [MAD-22617] 265


MIRAJ ( S.
B.
SHINTRE )
android:layout_ ontent" android:fontFamily="sans-serif-

x="110dp" smallcaps"

android:layout_
android:textColor="@color/design_default_color
y="450dp" _surface"

android:text="3 android:layout_x="180dp"

9°" android:layout_y="350dp"

android:textSiz android:text="Wed 28"


e="20sp" android:textSize="20sp"/>

android:textSty
le="bold"/> <ImageView
android:layout_width="50dp"

<TextView android:layout_height="45dp"
android:layout_width="wrap_co

ntent"
android:layout_height="wrap_c
ontent"
android:fontFamily="sans-serif-
smallcaps"

android:textColor="@color/design_default_color
_surface"
android:layout_x="110dp"
android:layout_y="490dp"

android:text="24°"

android:textSize="20sp"/>

<TextView
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_c

G. P. CO6I [MAD-22617] 266


MIRAJ ( S.
B.
SHINTRE )
android:layout_x="180dp" <TextView android:layout_width="wrap_content"

android:layout_y="390dp" android:layout_height="wrap_content"

android:src="@drawable/sun"/>

<TextView

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-
smallcaps"

android:textColor="@color/design_default_c
olor_surface"
android:layout_x="190dp"
android:layout_y="450dp"
android:text="39°"
android:textSize="20sp"
android:textStyle="bold"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:fontFamily="sans-serif-
smallcaps"

android:textColor="@color/design_default_c
olor_surface"
android:layout_x="190dp"
android:layout_y="490dp"

android:text="25°"
android:textSize="20sp"/>

G. P. CO6I [MAD-22617] 267


MIRAJ ( S.
B.
SHINTRE )
android:fontFamily="sans-serif-smallcaps" android:fontFamily="sans-serif-smallcaps"

android:textColor="@color/design_default_color android:textColor="@color/design_default_color
_surface" _surface"

android:layout_x="26 android:layout_x="270dp"

0dp" android:layout_y="450dp"

android:layout_y="35 android:text="40°"

0dp" android:textSize="20sp"

android:text="Thu android:textStyle="bold"/>

29"
android:textSize="20 <TextView

sp"/> android:layout_width="wrap_content"

android:layout_height="wrap_content"

<ImageView android:fontFamily="sans-serif-smallcaps"

android:layout_width
="50dp"
android:layout_heigh

t="45dp"
android:layout_x="26
0dp"
android:layout_y="39
0dp"
android:src="@draw

able/sun"/>

<TextView
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_c
ontent"

G. P. CO6I [MAD-22617] 268


MIRAJ ( S.
B.
SHINTRE )
android:textColor="@color/design_default_c android:layout_height="wrap_content"
olor_surface" android:layout_x="170dp"
android:layout_x="270dp"
android:layout_y="490dp"

android:text="26°"

android:textSize="20sp"/>

<ImageView

android:layout_width="50dp"
android:layout_height="50dp"
android:layout_x="340dp"

android:layout_y="410dp"
android:rotation="270"

android:src="@android:drawable/arrow_dow
n_float"
app:tint="#FFFEFA"/>

<Button
android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="530dp"
android:backgroundTint="#23F4EEEE"
android:padding="10dp"
android:text="Daily Summary"
app:cornerRadius="10dp" />

<Button
android:layout_width="wrap_content"

G. P. CO6I [MAD-22617] 269


MIRAJ ( S.
B.
SHINTRE )
android:layout_y="530dp"
android:backgroundTint="#2

3F4EEEE"
android:padding="10dp"
android:text="Hourly"

app:cornerRadius="10dp" />

<Button

android:layout_width="wrap_
content"
android:layout_height="wrap
_content"
android:layout_x="265dp"
android:layout_y="530dp"
android:backgroundTint="#2
3F4EEEE"
android:padding="10dp"
android:text="Details"
app:cornerRadius="10dp" />

</AbsoluteLayout>

G. P. CO6I [MAD-22617] 270


MIRAJ ( S.
B.
SHINTRE )
Chapter 5
Intent:
AndroidusesIntent for communicating between thecomponents ofan Application andalso from one
application to another application.
Intentaretheobjectswhichisusedinandroidforpassingtheinformationamong Activitiesinan
Applicationandfromoneapptoanotheralso.Intentareusedforcommunicating between the Application
componentsanditalsoprovidestheconnectivitybetweentwoapps.
Example-
Intent intent = new Intent(getApplicationContext(), SecondActivity.class); startActivity(intent);
getApplicationContext() returns the context for your foreground activity.
Types of intent:

Explicit Intent:
Explicit Intents are used to connect the application internally.
ExplicitIntentworkinternallywithinanapplicationto performnavigationanddata transfer.
Example-
Intent intent = new Intent(getApplicationContext(), SecondActivity.class); startActivity(intent);

G. P. CO6I [MAD-22617] 271


MIRAJ ( S.
B.
SHINTRE )
Implicit Intent:
In Implicit Intents we do need to specify the name of the component. We just specify the Actionwhich
hastobeperformedandfurtherthisactionishandledbythecomponentofanother application.
The basic example of implicit Intent is to open any web page
Example-
Intent intentObj = new Intent(Intent.ACTION_VIEW); intentObj.setData(Uri.parse("https://www.abhiandroid.com"));
startActivity(intentObj);

Intent Uses in android:


Intent for an Activity:
Everyscreenin Androidapplicationrepresentsanactivity. To startanew activityyou needtopass
an Intent object to startActivity() method. This Intentobjecthelps tostart anew activity and passing data
to the second activity.
Intent for Services:
Services work in background of an Android application and it does not require any user Interface.
Intents could be used to start a Service thatperforms one-time task(for example: Downloading some file)
Intent for Broadcast Receivers:
Therearevariousmessagethatanappreceives,thesemessagesarecalledasBroadcast
Receivers. (For example, a broadcast message could be initiated to intimate that the file downloading
iscompletedandreadytouse). Androidsysteminitiates somebroadcastmessage onseveralevents,such
as System Reboot, Low Battery warning message etc.

Intent Filter:
-decide the behavior of an intent.
-Intentaboutthenavigation ofoneactivitytoanother,thatcanbeachieveby declaring
intent filter.
-We can declare an Intent Filter for an Activity in manifest file.
- IntentfiltersspecifythetypeofintentsthatanActivity,serviceorBroadcastreceivercanrespond to.

G. P. CO6I [MAD-22617] 272


MIRAJ ( S.
B.
SHINTRE )
• Syntax of Intent Filters:
<activity android:name=".MainActivity">
<intent-filter
android:icon="@drawable/icon" android:label="@string/label" >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /></intent-filter>
</activity>
• icon: This is displayed as icon for activity. You can check or save png image of name icon in
drawable folder.
android:icon="@drawable/icon"
• label:The label / title that appears at top in Toolbar of thatparticular Activity. You can checkoredit
labelnamebyopening StringXMLfilepresentinsideValuesfolder
android:label = "@string/label“ or
android:label = "New Activity“
Just like icon attribute,ifyou have not declared any label for your activity then it will be
same as your parent activity.
• Elements In IntentFilter:
Thereare following three elementsinanintentfilter:
1.Action
2.Data
3.Category

Activity Lifecycle:
Activityis ascreen thatuserinteractwith. Every Activityinandroidhaslifecycle like created,
started, resumed, paused, stopped or destroyed. These different states are known as Activity
Lifecycle.
onCreate() – Called when the activity is first created
onStart()– Calledjustafterit’screationorbyrestartmethodafteronStop().Here Activity
start becoming visible to user

G. P. CO6I [MAD-22617] 273


MIRAJ ( S.
B.
SHINTRE )
onResume() –
Called when Activity is visible to user and user can interact with it
onPause() –Called when Activity content is not visible because user resume previous activity
onStop()–Called when activity is notvisible to user because some other activity takes place ofit
onRestart() – Called when user comes on screen or resume the activity which was stopped
onDestroy – Called when Activity is not in background

Diagram:

G. P. CO6I [MAD-22617] 274


MIRAJ ( S.
B.
SHINTRE )
Broadcast Receiver
Broadcast Receiver is a component which will allow android system or other apps to deliver events
to the app like sending a low battery message or screen turned off message to the app. The apps can also
initiate broadcasts to let other apps know that required data available in a device to useit.
Generally, we use Intents to deliver broadcast events to other apps and Broadcast Receivers
use status bar notifications tolet user know that broadcast event occurs.
is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as an Intent
object.

two important steps to make BroadcastReceiver:


• Registering Broadcast Receiver
• Creating the BroadcastReceiver
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding
the onReceive() method where each message is received as a Intent object parameter.
Example-
public class MyReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show(); } }

System generated eventsare:


• android.intent.action.BATTERY_CHANGED
• android.intent.action.BATTERY_LOW
• android.intent.action.BATTERY_OKAY
• android.intent.action.BOOT_COMPLETED
• android.intent.action.BUG_REPORT
• android.intent.action.CALL
• android.intent.action.CALL_BUTTON
• android.intent.action.DATE_CHANGED

G. P. CO6I [MAD-22617] 275


MIRAJ ( S.
B.
SHINTRE )
• android.intent.action.REBOOT

Content Provider:
Content Provider will act as a central repository to store the applications data in one place and
make that data available for different applications to access whenever it’srequired.
theContentProviderisapartofanandroidapplicationanditwillactasmorelike relational
database to store the app data. We can perform a multiple operations like insert, update, delete and
edit on the data stored in content provider
using insert(), update(), delete() and query() methods.
contentproviderishaving differentwaystostoreapp data.Theapp datacanbestoredin aSQLite
databaseor in files or even over anetworkbased onourrequirements. By using content providers wecan
managedatasuchasaudio,video,imagesandpersonalcontactinformation.

G. P. CO6I [MAD-22617] 276


MIRAJ ( S.
B.
SHINTRE )
• ContentResolver-
To access a data from content provider, we
need to use ContentResolver
• CursorLoader-
isusedtorunthequeryasynchronouslyin
background
• ContentProvider-
receive a data requests from client,
performs the requested actions
(create,update,delete, retrieve) and
return the result.

• Content URIs:
To query a content provider, you specify the query string in the form of a URI which has following
format −content://authority/path
content:// - The string content:// is always present in the URI
authority - It represents the name of content provider
path - It represents the table’s path.
The ContentResolver objectusetheURI’s authority to findthe appropriate provider and send the
query objects to the correct provider. After that ContentProvider uses the path of content URI to
choose the right table to access.

G. P. CO6I [MAD-22617] 277


MIRAJ ( S.
B.
SHINTRE )
Tocreateacontentproviderinandroidapplicationsweshouldfollowbelow steps.
1. WeneedtocreateacontentproviderclassthatextendstheContentProviderbaseclass.
2. Weneed to define our content provider URI to access the content.
3. The ContentProvider class defines a six abstract methods (insert(), update(), delete(), query(),
getType())whichweneedtoimplementallthesemethodsasapartofour subclass.
4. WeneedtoregisterourcontentproviderinAndroidManifest.xmlusing<provider>tag.

Methods:
1. query()-Itreceives arequestfromtheclient.Byusingargumentsitwillgetadata from
requested table and return the data as a Cursor object.
2. insert() - This method will insert a new row into our content provider and it will return the
content URI for newly inserted row.
3. update()-This methodwillupdateanexistingrowsinour contentproviderandit return the
number of rows updated.
4. delete()- Thismethodwilldeletetherowsinourcontentprovideranditreturnthe number of
rows deleted.
5. getType() - This method will return the MIME type of data to given content URI.
6. onCreate() - This method will initialize our provider. The android system will call this
method immediately after it creates our provider.

Fragment:
Fragmentis a part ofan activity which enable more modular activity design. Itwill not be wrong if we say a
fragment is a kind of sub-activity.
We can combine multiple Fragments in Single Activity to build a multi panel UI and reuse a
Fragment in multiple Activities.
• A fragment has its own layout and its own behaviour with its own life cycle callbacks.
• You can add or remove fragments in anactivity while the activity is running.
• You can combine multiple fragments in a single activity tobuild amulti-pane UI.
• A fragment can be used in multiple activities.

G. P. CO6I [MAD-22617] 278


MIRAJ ( S.
B.
SHINTRE )
• Fragmentlife cycle is closely related to the life cycle ofits hostactivity which means when the
activityispaused,allthefragmentsavailableintheactivitywillalsobe stopped.

Need of Fragment:
• BeforetheintroductionofFragment’swecanonlyshowasingleActivity on the screen at one given point of
timesowewerenotabletodividethescreenandcontroldifferentpartsseparately.Withthehelpof
Fragment’swecandividethescreensindifferentparts and controls different parts separately.
• Byusing FragmentswecancomprisemultipleFragmentsina singleActivity.Fragments have their
own events, layouts and complete life cycle. It provide flexibility and also removed the limitation
of single Activity on the screen at a time.

Fragment code example in XML:


<fragment
android:id="@+id/fragments"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Fragment Life cycle:

G. P. CO6I [MAD-22617] 279


MIRAJ ( S.
B.
SHINTRE )
Description:
• onAttach() is called when a fragment is connected to an activity.
• onCreate() is called to do initial creation of the fragment.
• onCreateView() is called by Android once the Fragment should inflate aview.
• onViewCreated() is called after onCreateView() and ensures that the fragment's root view is non-null.
Anyview setup should happenhere. E.g., viewlookups, attachinglisteners.
• onActivityCreated() iscalledwhenhost activityhascompletedits onCreate()method.
• onStart() is called once the fragment is ready to be displayed on screen.
• onResume() - Allocate “expensive” resources such as registering for location, sensor updates, etc.
• onPause() - Release“expensive” resources. Commit anychanges.
• onDestroyView() is called when fragment's view is being destroyed, but the fragmentis still kept
around.
• onDestroy() is called when fragment is no longer in use.
• onDetach() is called when fragment is no longer connected to the activity.

Types of Fragment:
• Single frame fragments−Singleframefragmentsareusingforhand holddeviceslike mobiles,here
we can show only one fragment as a view.
• List fragments −fragmentshavingspeciallistviewiscalled as listfragment
• Fragments transaction −Usingwithfragmenttransaction.wecanmoveonefragmentto another fragment

Services:
Androidserviceisacomponentthatisusedtoperformoperationsonthe background
such as playing music, handle network transactions, interacting content providers etc. It
doesn't has any UI (user interface).
The service runs in the background indefinitely even if application is destroyed.
• threedifferent types of services:
1. Foreground- A foreground service performs some operation that is noticeable to the
user.
2. Background- Abackgroundserviceperformsanoperationthatisn'tdirectlynoticed by
the user.

G. P. CO6I [MAD-22617] 280


MIRAJ ( S.
B.
SHINTRE )
3. Bound- A service is bound when anapplication component binds to it by
callingbindService(). Aboundserviceoffersaclient-serverinterfacethatallows components tointeract
withtheservice,sendrequests,receive results,andevendoso acrossprocesses withinterprocess
communication (IPC). A bound service runs only aslong as another application component is bound
toit.Multiplecomponentscanbindtotheserviceatonce, but when all of them unbind, the service is
destroyed.
A service can essentially take two states −
• Started
Aserviceisstartedwhenanapplicationcomponent,suchasanactivity,startsitby calling
startService().Once started, a service can run in the background indefinitely, even if the component
that started it is destroyed.
• Bound
A serviceis boundwhen an application component binds toitby calling bindService(). A bound
service offers a client-server interface that allows components to interact with the service,send
requests, get results, and even do so across processes with interprocess communication (IPC).

Life cycle of service:

G. P. CO6I [MAD-22617] 281


MIRAJ ( S.
B.
SHINTRE )
• onStartCommand()
The system calls this method when another component, such as an activity, requests that the service
bestarted, bycallingstartService().Ifyouimplementthismethod,itisyour responsibilitytostopthe
service when its work is done, by
calling stopSelf() or stopService() methods.
• onBind()
Thesystemcallsthismethodwhenanothercomponentwantstobindwiththeservicebycalling
bindService(). If you implement this method, you must provide an interface that clientsuseto
communicatewiththeservice,byreturninganIBinderobject.Youmust alwaysimplementthis
method, but if youdon't want toallowbinding, then youshould return null.
• onUnbind()
The system calls this method when all clients have disconnected from a particular interface
published by the service.
• onRebind()
The system calls this methodwhen new clients have connected to the service, afterit had previously
been notified that all had disconnected inits onUnbind(Intent).
• onCreate()
The system calls this method when the service is first created
using onStartCommand() or onBind(). This call is required to perform one-time set-up.
• onDestroy()
The system calls this method when the service is no longer used and is being destroyed.
Your service should implement this to clean up any resources such as threads, registered listeners,
receivers, etc.
• Create a Service
Generally,inandroid tocreateaservicewemustcreateasubclassof Service. Inandroid the
application component such as an activity can start the service by
calling startService() which results in calling the service’s onStartCommand() method.

G. P. CO6I [MAD-22617] 282


MIRAJ ( S.
B.
SHINTRE )
public class SampleService extends Service
{
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//TODO write your own code
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent)
{
//TODOforcommunicationreturn IBinderimplementation return
null;
}
}
• Register a Service in Manifest File
<manifest ... >
...
<application ... >
<service android:name=".SampleService" />
</application>
...
</manifest>
• Start a Service
Intent intent = new Intent(this, MyService.class);
startService(intent);

TheonStartCommand()methodwillreturnavaluefromoneofthefollowing constants.
1. START_STICKY
It will restart the service in case if it terminated and the Intent data which is passed
toonStartCommand() methodisNULL. Thisissuitable fortheservicewhicharenotexecuting commands
but running independently and waiting for the job.

G. P. CO6I [MAD-22617] 283


MIRAJ ( S.
B.
SHINTRE )
2. START_NOT_STICKY
It will not restart the service and it is useful for the services which will run periodically. The service will
restart only when there are a pending startService() calls.It’sabestoptionto avoid running a service in
case if it is not necessary.
3. START_REDELIVER_INTENT
It’ssameasSTAR_STICY andit recreates the service, call onStartCommand() with last intent
that was delivered to the service.

Android Architecture:
Androidoperatingsystemisastack ofsoftwarecomponentswhichisroughlydividedinto five
sectionsandfour mainlayersasshownbelowinthearchitecture diagram.

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,
displayetc.Also, thekernel handlesallthethingsthat Linuxisreallygood

G. P. CO6I [MAD-22617] 284


MIRAJ ( S.
B.
SHINTRE )
at such as networking and a vast array of device drivers, which take the pain out of interfacing to peripheral
hardware.

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,librariestoplay and record audio andvideo, SSLlibraries responsible for Internet securityetc.

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
availabletotheAndroiddeveloperisasfollows−
• 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 −UsedtoaccessdatapublishedbycontentprovidersandincludesSQLite database
management classes.
• android.opengl −AJavainterfacetotheOpenGLES3Dgraphics rendering API.
• android.os − Provides applications with access to standard operating system services including
messages, systemservicesandinter-process communication.
• android.text −Used to renderand manipulate text on a device display.
• android.view −Thefundamentalbuildingblocks of applicationuserinterfaces.
• android.widget −Arichcollectionofpre-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.
HavingcoveredtheJava-basedcorelibrariesintheAndroidruntime,itisnowtimetoturnourattentionto the
C/C++basedlibraries containedinthislayerofthe Android software stack.

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.

G. P. CO6I [MAD-22617] 285


MIRAJ ( S.
B.
SHINTRE )
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.
The Android runtime also provides a set of core libraries which enable Android application developers
towrite AndroidapplicationsusingstandardJavaprogramminglanguage.

Application Framework

The Application Framework layer provides many higher-level services to applications in the form of Java
classes. Application developersareallowedtomakeuseoftheseservicesintheir applications.
The Android framework includes the following key services −
• ActivityManager−Controlsallaspectsoftheapplicationlifecycleandactivitystack.
• Content Providers−Allowsapplicationstopublishandsharedata withother applications.
• Resource Manager − Provides access to non-code embedded resources such as strings, color settings
and user interfacelayouts.
• Notifications Manager − Allows applications to display alerts and notifications to the user.
• ViewSystem−Anextensiblesetofviewsusedtocreateapplicationuserinterfaces.

Applications
You will find all the Android application at the top layer. You will write your application to be installed on
thislayeronly.ExamplesofsuchapplicationsareContactsBooks,Browser,Games etc.
Multimedia Framework:
A multimedia framework is a software framework thathandles media on acomputerandthrough anetwork.A
good multimedia framework offers an intuitive API and a modular architecture to easilyadd supportfornew
audio,videoand container formatsand transmissionprotocols. Itis meanttobeusedbyapplications suchas
mediaplayersandaudioorvideoeditors,butcanalso beusedtobuildvideoconferencingapplications, media
convertersandothermultimediatools.
Data is processed among modules automatically, it is unnecessary for app to pass buffers between
connected modules one by one.
In contrast to function libraries, a multimedia framework provides a run time environment for the media
processing. Ideally such an environment provides execution contexts for the media processing blocks
separated from the application using the framework. The separation supports the independent processing of
multimedia data in a timely manner. These separate contexts can be implemented as threads

G. P. CO6I [MAD-22617] 286


MIRAJ ( S.
B.
SHINTRE )
Bluetooth:
Bluetooth is a way to send or receive data between two different devices. Android platform includes
support for the Bluetooth framework that allows a device to wirelessly exchange data with other Bluetooth
devices.
Android provides Bluetooth API to perform these different operations.
• Scan for other Bluetoothdevices
• Get a list of paired devices
• Connect to other devices through service discovery
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling
bycallingthestaticmethodgetDefaultAdapter(). Itssyntaxisgivenbelow.

In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant
ACTION_REQUEST_ENABLE. Its syntax is.

Apart from this constant, there are other constants provided the API , that supports different tasks. They are
listed below.

G. P. CO6I [MAD-22617] 287


MIRAJ ( S.
B.
SHINTRE )
Sr.No Constant & description

1 ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of bluetooth

ACTION_STATE_CHANGED
2
This constant will notify that Bluetooth state has been changed

ACTION_FOUND
3
This constant is used for receiving information about each device that is discovered

Once you enable the Bluetooth , you can get a list of paired devices by calling
getBondedDevices() method. It returns asetof bluetooth devices. Its syntaxis.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 288


pairedDevices = BA.getBondedDevices();
Apartform theparried Devices ,there areother methodsinthe API thatgives more control over Blueetooth.
They are listedbelow.

Sr.No Method &


description

1 enable()
This method enables the adapter if not enabled

isEnabled()
2
This method returns true if adapter is enabled

disable()
3
This method disables the adapter

getName()
4
This method returns the name of the Bluetooth adapter

setName(String name)
5
This method changes the Bluetooth name

getState()
6
This method returns the current state of the Bluetooth Adapter.

startDiscovery()
7
This method starts the discovery process of the Bluetooth for 120 seconds.

Example

This example provides demonstration of BluetoothAdapter class to manipulate Bluetooth and show list
of paired devices by the Bluetooth.
To experiment with this example , you need to run this on an actual device.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 289


Step Des
s cript
ion
1 You willuse Android studio tocreate an Android application a
package com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add the code
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if
required.
4 Modify AndroidManifest.xml to add necessary permissions.
5 Runtheapplicationandchoose arunningandroiddeviceandinstalltheapplication onitandverify the
results.

Animation:
Animation in android is possible from many ways. In this chapter we will discuss one easy and
widely used way of making animation called tweened animation.

Tween Animation
Tween Animation takes some parameters such as start value , end value, size , time
duration , rotation angle e.t.c and perform the required animation on that object. It can be
applied to any type of object. Soin order tousethis , android has provided usaclasscalled
Animation.
In order toperform animation in android , we are going to call a static function loadAnimation()
of the class AnimationUtils. We are going to receive the result in an instance of Animation
Object. Itssyntaxisasfollows

Notethesecondparameter. Itisthenameoftheouranimation xmlfile.You havetocreateanew folder


called
anim under res directory and make an xml file under anim folder.
This animation class has many useful functions which are listed below −
Sr.No Method &
Description

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 290


1 start()
This method starts the animation.

setDuration(long duration)
2
This method sets the duration of an animation.

getDuration()
3
This method gets the duration which is set by above method

end()
4
This method ends the animation.

cancel()
5
This method cancels the animation.

In order to apply this animation to an object ,we will justcall the startAnimation() methodofthe object. Its
syntax is−

Example
The following example demonstrates the use of Animation in android. You would be able to choose
differenttypeofanimationfromthemenuandtheselectedanimationwillbeappliedon animageView on
thescreen.
To experiment with this example , you need to run this on an emulator or an actual device.

Steps Description

1 You will use Android studio IDE to create an Android application and name it as My Application under a package
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add animation code

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 291


3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
4 Create a new folder under res directory and call it anim. Confim it by visiting res/anim
5 RightclickonanimandclickonnewandselectAndroidXMLfileYouhave tocreatedifferentfilesthatarelisted below.
6 Create files myanimation.xml,clockwise.xml,fade.xml,move.xml,blink.xml,slide.xml and add the XML code.
7 Noneedtochangedefaultstringconstants.Androidstudiotakescareofdefaultconstantsatvalues/string.xml.
8 Runtheapplicationandchoosearunningandroiddeviceandinstalltheapplicationonitandverifytheresults.

Camera:
These are the following two ways, in which you can use camera in your application
• Using existing android camera application in our application
• Directly using Camera API provided by android in our application Using

existing android camera application in our application

You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera


application installed on your phone. Its syntax is given below

Apartfromtheabove,thereareotheravailableIntentsprovidedbyMediaStore.Theyarelisted as follows
Sr.No Intent type anddescription

1 ACTION_IMAGE_CAPTURE_SECURE
It returns the image captured from the camera , when the device is secured

2 ACTION_VIDEO_CAPTURE

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 292


It calls the existing video application in android to capture video

EXTRA_SCREEN_ORIENTATION
3
It is used to set the orientation of the screen to vertical or landscape

EXTRA_FULL_SCREEN
4
It is used to control the user interface of the ViewImage

INTENT_ACTION_VIDEO_CAMERA
5
This intent is used to launch the camera in the video mode

EXTRA_SIZE_LIMIT
6
It is used to specify the size limit of video or image capture size
Now you will use the function startActivityForResult()to launch this activity and wait for its result. Its
syntax is given below

This method has been defined in the activity class. We are calling it from main activity. There are methods
defined in the activity class that does the same job , but used when you are not calling from the activity but
from somewhere else. They are listed below
Sr.No Activity function description

1 startActivityForResult(Intent intent, int requestCode, Bundle options)


It starts an activity , but can take extra bundle of options with it

startActivityFromChild(Activity child, Intent intent, int requestCode)


2
It launch the activity when your activity is child of any other activity

startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options)


3
It work same as above , but it can take extra values in the shape of bundle with it

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 293


startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)
4
It launches activity from the fragment you are currently inside

startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options)


5 It not only launches the activity from the fragment , but can take extra values with it

Nomatterwhichfunctionyouusedtolaunchtheactivity,theyallreturntheresult.Theresult canbe
obtained by overriding the function onActivityResult.

Example

Hereisanexamplethatshowshowtolaunchtheexistingcameraapplicationtocaptureanimage anddisplay
the result in the form of bitmap.
Toexperimentwiththisexample,youneedtorunthisonanactualdeviceonwhichcamerais supported.

Steps Description

1 You will use Android studio IDE to create an Android application and name it as Camera under a
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add intent code to launch the Camera.

3 Modify layout XML file res/layout/activity_main.xml

4 AddtheCamerapermission andruntheapplicationandchoosearunningandroiddeviceandinstall the


application on it and verify the results.

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 294


G. P. CO6I [MAD-22617] 295
MIRAJ ( S.
B.
SHINTRE )
Audio and Video player:
• Android provides many ways to control playback of audio/video files and streams. One of this way
is through a class called MediaPlayer.
• Theandroidmediaframeworkprovidesabuiltinsupportforplayingavarietyof commonmedia
types, such as audio or video. We have a multiple ways to play audio or video but the mostimportant
componentofmedia frameworkisMediaPlayerclass.
• Inandroid,byusingMediaPlayerclasswecanaccessaudioorvideofilesfrom application (raw)
resources, standalone files in file system or from a data stream arriving overanetworkconnection
andplayaudioorvideofileswiththemultipleplayback options such as play, pause, forward,
backward, etc.
• wehavetocallastaticMethodcreate()ofthisclass.Thismethodreturnsaninstanceof
MediaPlayer class. Its syntax is as follows
Syntax:
MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.baitikochi_chuste);
• Onceyou havecreated the Mediaplayerobjectyou can call some methods to start or stop the music.
These methods are listed below.
1. mediaPlayer.start();
2. mediaPlayer.pause();
• Inordertostartmusicfromthebeginning,youhaveto call reset()method.Itssyntaxis given below.
mediaPlayer.reset();
• Incase,ifwewanttoplayanaudiofromaURIthatislocallyavailableinthesystem,we needto
write the code like as shown below
UrimyUri= ..... ; // initialize Uri here
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(getApplicationContext(), myUri); mPlayer.prepare();
mPlayer.start();
• STREAM_MUSIC- Used to identifythe volume of audio streams formusic playback
• IfwewanttoplayanaudiofromaURLviaHTTPstreaming,weneedtowritethecode like as
shown below.

G. P. CO6I [MAD-22617] 296


MIRAJ ( S.
B.
SHINTRE )
Example:
String url= "http:// ............. "; // your URLhere
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setDataSource(url);
mPlayer.prepare(); // might take long! (for buffering, etc)
mPlayer.start();
• Methods of media player class:

Method Description

public void setDataSource(String path) setsthedatasource(filepathorhttp url)


to use.

public void prepare() prepares the player for playback


synchronously.

public void start() it starts or resumes the playback.

public void stop() it stops theplayback.

public void pause() it pauses the playback.

public booleanisPlaying() checks if media player is playing.

public void seekTo(int millis) seekstospecifiedtimeinmiliseconds.

public void setLooping(boolean looping) setstheplayerforlooping or non-


looping.

Method Description

public boolean isLooping() checks if the player is looping or non-looping.

G. P. CO6I [MAD-22617] 297


MIRAJ ( S.
B.
SHINTRE )
public void selectTrack(int index) it selects a track for the specified index.

public int getCurrentPosition() returns the current playback position.

public int getDuration() returns duration of the file.

public void setVolume(float leftVolume,float sets the volume on this player.


rightVolume)

• Video Player:
In android, by using VideoView component and MediaController class we can easily implement
the video player in android applications to play the videos with multiple playback options, such
as play, pause, forward, backward, etc.

Example:
VideoView videoView = (VideoView)findViewById(R.id.vdVw); MediaController
mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
Uri uri = Uri.parse("android.resource://" + getPackageName() +"/"+
R.raw.video1);
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();

• Methods of videoplayer:

Description
Method

G. P. CO6I [MAD-22617] 298


MIRAJ ( S.
B.
SHINTRE )
setMediaController() Itisusedtosetthemediacontrollerto
videoview.

setVideoURI() It is used to set the path of video file.

pause() It is used to pause the video playing.

stopPlayback() it is used to stop the video playing.

seekTo(position) Itisused tomovevideo toparticular


position in milliseconds.

resume() Itisusedtoresumethevideo playing.

start() Itis used tostartplaying the audio /


video.

stopPlayback() Itis used to stop playing the audio /


video.

• Text to Speech:
Text to speech (TTS) makes an android device read the text and convert it to audio out via
the speaker. Android TTS supports multiple languages. TTSisa simple but powerful feature. It can
also be effectively used in mobile APPs dedicated to visually impaired people orin educational app
for kids or can be used in pronunciation learning app, etc. These are some of the ways you can use
TTS.UsingTextToSpeechenhances interaction betweenthe userandthe mobile application.
• Generally, the android TextToSpeech instance can only be used to synthesize text once it has
completedits initialization soimplement TextToSpeech.OnInitListener tonotify the completion of
initialization.
• Duringtheinitialization,wecansettheaudiopitchrate,audiospeed,typeoflanguage to speak, etc.
based on our requirements.
• OnInitListener-Interfacedefinitionofacallbacktobeinvokedindicatingthecompletion ofthe
TextToSpeech engine initialization.
• TextToSpeechneedstobeinitializedfirst.Forthis,youneedtoimplement the
TextToSpeech.OnInitListener interface and override the method:onInit
TextToSpeech tts = new TextToSpeech(this, this);
public TextToSpeech (Context context, TextToSpeech.OnInitListener listener)

G. P. CO6I [MAD-22617] 299


MIRAJ ( S.
B.
SHINTRE )
• How to speak thetext?
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
– The first parameter is the text that would be spoken.
– Thesecondparameterdefinesthatthepreviousinputisflushedsoastobegina clean slate.
Alternatively,wecanuseQUEUE_ADDtoaddthecurrenttexttothe speech.
– The third parameter is the bundle that is passed.
– Fourth is the utterance id string.
• OnUtteranceProgressListener is used to listen for the tts events: start, done,
error

• setLanguage()- CANADA_FRENCH, GERMANY, ITALY, JAPAN, CHINA


– ttobj.setLanguage(Locale.UK);
• Once you have set the language, you can call speak method of the class to speak the text.
ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
• Inthis method, wecheckwhetherthefeatureisavailableonourdevice or not.
@Override public void onInit(int status)
{
if (status == TextToSpeech.SUCCESS)
{
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result ==
TextToSpeech.LANG_NOT_SUPPORTED)
{ Toast.makeText(getApplicationContext(), "Language not supported",
Toast.LENGTH_SHORT).show(); } else { //Disable the button if any.}} else {
Toast.makeText(getApplicationContext(), "Init failed", Toast.LENGTH_SHORT).show(); }
}

Methods Of text To Speech:

Sr.No Method & description

G. P. CO6I [MAD-22617] 300


MIRAJ ( S.
B.
SHINTRE )
1 addSpeech(String text, Stringfilename)
This method adds a mapping between a string of text and a sound file.
2 getLanguage()
This method returns a Locale instance describing the language.
3 isSpeaking()
This method checks whether the TextToSpeech engine is busy speaking.
4 setPitch(float pitch)
This method sets the speech pitch for the TextToSpeech engine.
5 setSpeechRate(float speechRate)
This method sets the speech rate.
6 shutdown()
This method releases the resources used by the TextToSpeech engine.
7 stop()
This method stop the speak.

Contants-
• ERROR-Denotes a generic operation failure.
• ERROR_SERVICE-Denotes a failure of a TTS service.
• LANG_AVAILABLE -Denotes the language is available forthe language by the locale
• LANG_COUNTRY_AVAILABLE -Denotes the language is available for the language and
country specified by the locale
• LANG_MISSING_DATA -Denotes the language data is missing.
• LANG_NOT_SUPPORTED-Denotes the language is not supported.
• SUCCESS-Denotes a successful operation.
• QUEUE_FLUSH-Queue mode where all entries in the playback queue (media to be played
andtexttobesynthesized) aredroppedandreplacedbythenewentry.

• STOPPED-Denotes a stop requested by a client.

G. P. CO6I [MAD-22617] 301


MIRAJ ( S.
B.
SHINTRE )
Sensors
• Generally, most of the android devices have a built-in sensors to measure motion,
orientation and various environmental conditions.
• Mostoftheandroiddeviceshavebuilt-insensorsthatmeasuremotion,orientation,and various
environmental condition. The android platform supports three broad categories of sensors.
– Motion Sensors
– Environmental sensors
– Position sensors
• MotionSensors-Thesesensorsareusefultomeasureaccelerationforcesandrotationalforces along
three axes. This category includes accelerometers, gravity sensors, gyroscopes, and
rotational vector sensors.
• Environmental Sensors- These sensors are useful to measure various environmental parameters,
suchasambientairtemperature andpressure,illumination,andhumidity. Thiscategoryincludes
barometers, photometers, and thermometers.
• Position Sensors- These sensors are useful to measure the physical position of a device. This
category includes orientation sensors and magnetometers.
Androidprovidedaframeworkcalled sensorframework toaccessall thesensors availableon
deviceandtogetall therawsensordata. Thesensorframeworkprovidedawide varietyofsensor related
tasks.Forexample,byusingsensorframeworkwecanperform following things

• It lists all the available sensors on the device


• It determine the capabilities of each sensor, such as its maximum range, manufacturer, power
requirements, and resolution.
• It can acquire raw sensor data and define the minimum rate at which you acquire sensor data.
• Register andunregister sensor event listeners that monitor sensor changes.

G. P. CO6I [MAD-22617] 302


MIRAJ ( S.
B.
SHINTRE )
The Android sensor framework will allow us to access many type ofsensors, some of these sensors
are hardware-based and some are software-based. The Hardware-based sensors are physical components built
onthehandsetortabletdeviceandSoftware-basedsensorsarenot aphysicaldevicesbuttheymimic
Hardware-based sensors.

Classes –

Class Description

SensorManager By usingthisclass we can create an instance of sensor service


and this class provides a various methods for accessing and
listing sensors, registering and unregistering sensor event listeners
and acquiring orientation information.

Sensor Byusingthisclasswecancreateaninstanceofaspecific sensor


and this class provides a various methods thatlet you determine the
sensor's capabilities.

SensorEvent The system uses this class tocreate a sensor event object and it
provides the raw sensor data, type of sensor that generated the
event,accuracyofthedata,andthetimestamp for the event.

SensorEventListener Wecanusethisinterfacetocreatetwocallbackmethods that


receive notifications (sensor events) when sensor values change or
when sensor accuracy changes.

SensorManager lets you access the device's sensors.


• The android.hardware.SensorManager class provides methods :
– to get sensorinstance,
– to access and listsensors,
– to register and unregister sensor listeners etc.
• You can get the instance of SensorManager by calling the method getSystemService() and
passing the SENSOR_SERVICE constant in it.
SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);

G. P. CO6I [MAD-22617] 303


MIRAJ ( S.
B.
SHINTRE )
• class provides methods:
-to get sensor instance,
-to access and list sensors,
-to register and unregister sensor listeners etc.
• public int getSensors()

• getSensorList()
public List<Sensor> getSensorList (int type)
-Use this method to getthe listofavailable sensors ofa certain type. Make multiple calls to get
sensors of different types oruse Sensor.TYPE_ALL toget all the sensors.
• registerListener
public boolean registerListener (SensorEventListener listener, Sensor sensor, int
samplingPeriodUs)

The rate sensor events are delivered at


• unregisterListener
public boolean unregisterListener (SensorEventListener listener, Sensor sensor)

Sensor Class
The android.hardware.Sensor class provides methods to get information of the sensor such as sensor
name, sensor type, sensor resolution, sensor type etc.
The Sensor class defines several constants for accessing the different sensors
Sensor Type Description Common
Uses

G. P. CO6I [MAD-22617] 304


MIRAJ ( S.
B.
SHINTRE )
TYPE_ACCELEROMETER Hardware Measures the acceleration Motion
force inm/s2 that isapplied detection
to a device on all three (shake, tilt,
physical axes(x, y, andz), etc.).
including the force of
gravity.
TYPE_AMBIENT_TEMPERATURE Hardware Measures the ambient Monitoring
room temperature in air
degrees Celsius (°C). See temperatures.
note below.
TYPE_GRAVITY Software Measures the force of Motion
or gravity in m/s2 that is detection
Hardware appliedtoadeviceonall (shake, tilt,
threephysicalaxes(x,y, z). etc.).

G. P. CO6I [MAD-22617] 305


MIRAJ ( S.
B.
SHINTRE )
TYPE_GYROSCOPE Hardware Measuresadevice'srateof rotationinrad/s around Rotation
eachofthethreephysicalaxes(x,y,and z). detection
(spin, turn,
etc.).
TYPE_LIGHT Hardware Measures the ambient light level (illumination) in lx. Controlling
screen
brightness.
TYPE_LINEAR_ACCELERATION Software Measurestheaccelerationforceinm/s 2thatis Monitoring
or applied toa device on allthreephysicalaxes(x, y, and acceleration
Hardware z), excluding the force of gravity. along a
single axis.

TYPE_MAGNETIC_FIELD Hardware Measures the ambient geomagnetic field for all three Creating a
physical axes (x, y, z) in μT. compass.
TYPE_ORIENTATION Software Measuresdegreesof rotationthatadevice makes Determining
around all three physical axes (x, y, z). AsofAPIlevel device
3youcanobtaintheinclination matrixandrotation position.
matrixforadevicebyusing thegravity sensor and the
geomagneticfield sensor in conjunctionwith
the getRotationMatrix() method.

TYPE_PRESSURE Hardware Measures the ambientair pressure in hPa or Monitoring


mbar. air pressure
changes.
TYPE_PROXIMITY Hardware Measuresthe proximityofanobjectincm relative Phone
to theviewscreen of a device.This sensor is position
typicallyusedtodeterminewhethera handsetis during a call.
beinghelduptoaperson'sear.

TYPE_RELATIVE_HUMIDITY Hardware Measures the relative ambient humidity in percent Monitoring


(%). dew point,
absolute, and
relative
humidity.

TYPE_ROTATION_VECTOR Software Measurestheorientation ofadeviceby Motion


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

G. P. CO6I [MAD-22617] 306


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 307
MIRAJ ( S.
B.
SHINTRE )
TYPE_TEMPERATURE Hardware Measures the temperature of the device in Monitoring
degrees Celsius (°C). This sensor temperatures.
implementation varies across devices and this
sensor was replaced with
the TYPE_AMBIENT_TEMPERATURE sensor
in API Level14

Sensor Class:
You can access the sensor via the sensorManager.getDefaultSensor() method, which takes the sensor
type andthedelay defined as constants on SensorManager as parameters.
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
SensorEvent class-
Its instance is created by the system. It provides information about the sensor.
SensorEventListener interface-

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 308


Itprovides two callback methods to getinformation whensensorvalues(x,yandz) change or
sensor accuracy changes
Public and abstract methods Description
void onAccuracyChanged(Sensor sensor, int itis called when sensor accuracy ischanged.
accuracy)
void onSensorChanged(SensorEvent event) it is called when sensor values are changed.

Steps:
1. AndroidprovidesSensorManagerandSensorclassestousethesensorsinour application.In
order tousesensors, firstthingyouneedtodoistoinstantiate theobject of SensorManager class.
It can be achieved as follows.
SensorManager sMgr; sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
2. ThenextthingyouneedtodoistoinstantiatetheobjectofSensorclassbycallingthe
getDefaultSensor() method of the SensorManager class. Its syntax is given below −
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);

3. Oncethatsensorisdeclared ,youneedtoregisteritslistenerandoverridetwomethodswhichare
onAccuracyChangedandonSensorChanged.Itssyntaxisasfollows−
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL); public
void onAccuracyChanged(Sensor sensor, int accuracy)
{}
public void onSensorChanged(SensorEvent event) { }

G. P. CO6I [MAD-22617] 309


MIRAJ ( S.
B.
SHINTRE )
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 accessthis database, you don't need to
establish any kind of connections for it like JDBC,ODBC e.t.c

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

Database - Creation
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
SQLiteDatabasemydatabase=openOrCreateDatabase("yourdatabase
name",MODE_PRIVATE,null);

G. P. CO6I [MAD-22617] 310


MIRAJ ( S.
B.
SHINTRE )
Apartfrom this, thereareotherfunctionsavailablein the database package ,thatdoes thisjob. They are
listedbelow

Sr.No Method & Description

1
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags,
DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode.The common flags mode could be
OPEN_READWRITE OPEN_READONLY

2
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
Itissimilartotheabovemethodasitalsoopenstheexistingdatabasebutitdoesnotdefineanyhandlerto handle the
errors ofdatabases

3
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
It not only opens but create the database if it not exists. This method is equivalent to openDatabase method.

4
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
Thismethodis similar to abovemethod butittakes the Fileobjectas a path rather then astring. It is equivalent to
file.getPath()

Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its
syntax is givenbelow
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the same job
but take some additional parameter is given below

Sr.No Method & Description

1
execSQL(String sql, Object[] bindArgs)
This method not only insert data , but also used to update or modify already existing data in database using bind
arguments

G. P. CO6I [MAD-22617] 311


MIRAJ ( S.
B.
SHINTRE )
Database - Fetching
We can retrieve anything from database using an object ofthe Cursor class. We will calla method of this class
calledrawQuery anditwillreturnaresultsetwiththe cursor pointingtothetable. Wecan 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);
There are other functions available in the Cursor class that allows us to effectively retrieve the data. That
includes

Sr.No Method & Description

1
getColumnCount()
This method return the total number of columns of the table.

2
getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column

3
getColumnName(int columnIndex)
Thismethod returns thename of the column by specifying the index of the column

4
getColumnNames()
This method returns the array of all the column names of the table.

5
getCount()
This method returns the total number of rows in the cursor

6
getPosition()
This method returns the current position of the cursor in the table

7
isClosed()
This method returns true if the cursor is closed and return false otherwise

G. P. CO6I [MAD-22617] 312


MIRAJ ( S.
B.
SHINTRE )
Database - Helperclass
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

Example
Here is an example demonstrating the use of SQLite Database. It creates a basic contacts
applications that allows insertion, deletion and modification of contacts.
To experiment with this example, you need to run this on an actual device on which camera is supported.

Steps Description

1 You willuse Android studioto createan Android application underapackage


com.example.sairamkrishna.myapplication.

2 Modifysrc/MainActivity.javafiletogetreferencesofalltheXMLcomponentsandpopulatethecontacts onlistView.

3 Create new src/DBHelper.java that will manage the database work

4 Create a new Activity as DisplayContact.java that will display the contact on the screen

5 Modify the res/layout/activity_main to add respective XML components

6 Modify the res/layout/activity_display_contact.xml to add respective XML components

G. P. CO6I [MAD-22617] 313


MIRAJ ( S.
B.
SHINTRE )
7 Modify the res/values/string.xml to add necessary string components

8 Modify the res/menu/display_contact.xml to add necessary menu components

9 Create a new menu as res/menu/mainmenu.xml to add the insert contact option

10 Runtheapplicationandchoosea runningandroiddeviceandinstalltheapplication on itandverifythe results.

Constructors of SQLiteOpenHelper class

There are two constructors of SQLiteOpenHelper class.

Constructor Description

SQLiteOpenHelper(Context context, String name, creates an object for creating, opening and
SQLiteDatabase.CursorFactory factory, int version) managing the database.

SQLiteOpenHelper(Context context, String name, creates an object for creating, opening and
SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler managing the database. It specifies the
errorHandler) error handler.

Methods of SQLiteOpenHelper class

There are many methods in SQLiteOpenHelper class. Some of them are as follows:

Method Description

G. P. CO6I [MAD-22617] 314


MIRAJ ( S.
B.
SHINTRE )
public abstract void onCreate(SQLiteDatabase db) called only once when database is created for
the first time.

publicabstractvoidonUpgrade(SQLiteDatabase db,intoldVersion, int called when database needs to be


newVersion) upgraded.

public synchronized void close () closes the database object.

public void onDowngrade(SQLiteDatabase db, int oldVersion, int called when database needs to be
newVersion) downgraded.

SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update, delete, select etc.

Methods of SQLiteDatabase class


There are many methods in SQLiteDatabase class. Some of them are as follows:

Method Description

void execSQL(String sql) executes the sql query not select query.

long insert(String table, String inserts a record on the database. The table specifies the table name,
nullColumnHack, ContentValues values) nullColumnHack doesn't allow completely null values. Ifsecond
argumentisnull,androidwillstorenullvaluesif valuesareempty.
Thethirdargumentspecifiesthevaluesto be stored.

G. P. CO6I [MAD-22617] 315


MIRAJ ( S.
B.
SHINTRE )
int update(String table, ContentValues values, updates a row.
String whereClause, String[] whereArgs)

Cursor query(String table, String[] columns, returns a cursor over the resultset.
Stringselection, String[] selectionArgs, String
groupBy,String having, String orderBy)

Async Task

Intended to enable proper and easy use of the UI thread.

What is AsyncTask?

AsyncTask class is used to do background operations that will update the UI(user interface). Mainly
we used it for short operations that will not effect on our main thread.

Android application runs on a single thread when launched. Due to this single thread model tasks that take
longer time to fetch the response can make the application non-responsive. To avoid this we use android
AsyncTask to perform the heavy tasks in background on a dedicated thread and passing the results back
to the UI thread. Hence use of AsyncTask in android application keeps the UI thread responsive
at all times.

Threading rules

• The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
• The task instance must be created on the UI thread.
• execute(Params...) must be invoked on the UI thread.
• Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...),
onProgressUpdate(Progress...) manually.
• The task can be executed only once (an exception will be thrown if a second execution is attempted.)

G. P. CO6I [MAD-22617] 316


MIRAJ ( S.
B.
SHINTRE )
AsyncTask's generic types:

The three types used by an asynchronous task are the following:

• Params: the type of the parameters sent to the task upon execution.

• Progress: the type of the progress units published during the background computation.

• Result: the type of the result of the background computation.

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the
type Void:

AsyncTask – Life Cycle:

G. P. CO6I [MAD-22617] 317


MIRAJ ( S.
B.
SHINTRE )
AsyncTask Methods
(4 steps):

Example:
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center"
android:background="#FCE9B0">

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Stud_nm"
android:id="@+id/nm"/>

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Stud_mono"
android:id="@+id/no"/>

G. P. CO6I [MAD-22617] 318


MIRAJ ( S.
B.
SHINTRE )
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Stud_mail"
android:id="@+id/mail"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="save"
android:onClick="save"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="display"
android:onClick="Display"/>
</LinearLayout>

MainActivity.java
package com.example.asynctaskex26;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;

public class MainActivity extends AppCompatActivity {

EditText nm,no,mail;
Database db;
asynctask async;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nm=findViewById(R.id.nm);
no=findViewById(R.id.no);
mail=findViewById(R.id.mail);

G. P. CO6I [MAD-22617] 319


MIRAJ ( S.
B.
SHINTRE )
db=new Database(this);
async=new asynctask(this);
}

public void save(View view) {


//db.insert(nm.getText().toString(),no.getText().toString(),mail.getText().toString());

if((nm.getText().toString()).equals("")&&(no.getText().toString()).equals("")&&(mail.getText().toString()).
equals("")){
Toast.makeText(this, "Enter credentials", Toast.LENGTH_SHORT).show();
}
else {
async.execute(nm.getText().toString(), no.getText().toString(), mail.getText().toString());
nm.setText("");
no.setText("");
mail.setText("");
}
}

public void Display(View view) {


Cursor c = db.getdata();
if (c.getCount() == 0) {
Toast.makeText(this, "No record found", Toast.LENGTH_SHORT).show();
} else {
StringBuffer sb=new StringBuffer();
while (c.moveToNext()) {
sb.append("Name:"+ c.getString(0)+"\n");
sb.append("Contact: " + c.getString(1) + "\n");
sb.append("Mail: " +c.getString(2) +"\n\n");
}
AlertDialog.Builder al=new AlertDialog.Builder(this);
al.setTitle("Result");
al.setMessage(sb.toString());
al.show();
}
}
}

User defined class:- asynctask.java


package com.example.asynctaskex26;

import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

G. P. CO6I [MAD-22617] 320


MIRAJ ( S.
B.
SHINTRE )
public class asynctask extends AsyncTask<String,Void,Long> {

Context context;
Database db;
AlertDialog.Builder al;
asynctask(Context c){
context=c;
db=new Database(context);
}
@Override
protectedvoid onPreExecute() {
super.onPreExecute();
al=new AlertDialog.Builder(context);
}

@Override
protected Long doInBackground(String... strings) {
String nm = strings[0];
String no = strings[1];
String mail = strings[2];
long result = db.insert(nm, no, mail);
return result;
}

@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}

@Overrideprotected void onPostExecute(Long aLong) { super.onPostExecute(aLong);


Toast.makeText(context, "Value inserted", Toast.LENGTH_SHORT).show();
}
}

User defined class:- database.java


package com.example.asynctaskex26;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class Database extends SQLiteOpenHelper {

G. P. CO6I [MAD-22617] 321


MIRAJ ( S.
B.
SHINTRE )
public Database(Context c) {
super(c, "std_info.db", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table std_tbl(name text,contact text,mail text);");
}

public long insert(String nm,String no,String mail){


SQLiteDatabase sd=this.getWritableDatabase();
ContentValues ctx=new ContentValues();
ctx.put("name",nm);
ctx.put("contact",no);
ctx.put("mail",mail);
long result=sd.insert("std_tbl",null,ctx);
return result;
}
public Cursor getdata(){
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.rawQuery("select * from std_tbl",null);
return c;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
}

G. P. CO6I [MAD-22617] 322


MIRAJ ( S.
B.
SHINTRE )
Result
Name: Ajith pande
Contact: 1 23456789D
Mail: ajith@gmail com

Value inserted

G. P. CO6I [MAD-22617] 323


MIRAJ ( S.
B.
SHINTRE )
Database notes (PART II)

SQ LiteDatabase

• SQLite is an open-source relational database i.e. used to perform database


operations on android devices such as storing, manipulating or retrieving persistent
data from the database.

• It is embedded in android bydefault. So, there is no need to perform any database setup or
administrationtask.

• The package android.database.sqlite contains all the required APIs to use an SQLite
database in our android applications.

• SQL (Structured Query Language) is a special programming language that is designed


for handling and managing data held in a Relation database management
system (RDBMS).

• As the name suggests, SQLite is the lightest version of SQL. It does not require
any Server, No configuration.

• In the simplest terms, SQLite is a public-domain software package that provides a


relational database management system or RDBMS.

• The "Lite" in SQLite does not refer to its capabilities. Rather, SQLite is
lightweight when it comes to setup complexity, administrative overhead, and resource
usage.

• SQLite is an open-source relational database management system or RDBMS


contained in a C programming library. Relational database systems are used to store data in
largetables.

• In contrast to Other popular RDBMS products like Oracle Database, IBM's DB2, and
Microsoft's SQL Server, SQLite does not require any administrative
overhead or any setup complexity.

G. P. CO6I [MAD-22617] 324


MIRAJ ( S.
B.
SHINTRE )

• As the other databases are working as a standalone process, SQLite is not working as a
standalone process. you have to link it with your application statically or
dynamically.
• SQLite uses dynamically and weakly typed SQL for a column. It means you can store any value
in any column, regardless of the data type. SQLite implements most of the SQL92 standard.
• SQLiteOpenHelperclassprovidesthefunctionalitytousetheSQLitedatabase.

SQLiteOpenHeIper class

• The android.database.sqlite.SQLiteOpenHelper class is used for database creation and


version management. 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 thedatabase.

• For performing any database operation, you have to provide the implementation
ofonCreate()andonupgrade()methodsofSQLiteOpenHelper class.

Its syntax is given below public class class DBHelper


extends SQLiteOpenHelper

public DBHelper()

public void onCreate(SQLiteDatabase db) O public void


onUpgrade(SQLiteDatabase database, intoldVersion, IntnewVersion) O

G. P. CO6I [MAD-22617] 325


MIRAJ ( S.
B.
SHINTRE )
Constructors of SQLiteOpenHelper class
There are two constructors of SQLiteOpenHelper class.
Constr Description
uctor
SQLiteOpenHelper(Context context, creates anobjectforcreating,openingand
Stringname, managing thedatabase.

SQLiteDatabase.CursorFactory factory,
int version)
SQLiteOpenHelper(Context creates
context, Stringname, anobjectforcreating,openingand
managing the database. It specifies the
SQLiteDatabase.CursorFactor error handler.
y factory, int
version,
DatabaseErrorHandIer
errorHandler)

Methods of SQLiteOpenHeIper class


TherearemanymethodsinSQLiteOpenHelperclass.Someofthemareasfollows:
Constr Description
uctor
SQLiteOpenHelper(Context context, creates anobjectforcreating,openingand
Stringname, managing thedatabase.

SQLiteDatabase.CursorFactory factory,
int version)

G. P. CO6I [MAD-22617] 326


MIRAJ ( S.
B.
SHINTRE )
SQLiteOpenHelper(Context creates
context, Stringname, anobjectforcreating,openingand
managing the database. It specifies the
SQLiteDatabase.CursorFactor error handler.
y factory, int
version,
DatabaseErrorHandIer
errorHandler)

SQLiteDatabase class
• Itcontains methods to be performed on sqlite database such as create, update, delete,

Methods ofSQLiteDatabase class


TherearemanymethodsinSQLiteDatabaseclass. Someofthemareasfollows:
Constr Description
uctor
SQLiteOpenHelper(Context context, creates anobjectforcreating,openingand
Stringname, managing thedatabase.

SQLiteDatabase.CursorFactory factory,
int version)
SQLiteOpenHelper(Context creates
context, Stringname, anobjectforcreating,openingand
managing the database. It specifies the
SQLiteDatabase.CursorFactor error handler.
y factory, int
version,
DatabaseErrorHandIer
errorHandler)

G. P. CO6I [MAD-22617] 327


MIRAJ ( S.
B.
SHINTRE )
Method Description
public abstract void onCreate(SQLiteDatabase called only once when database is
db) created for the first time.

public abstract void called when database needs to be


onUpgrade(SQLiteDatabasedb,intoldVersion, upgraded.
int newVersion)
publicsynchronized void close O closes the database object.
public voidonDowngrade(SQLiteDatabase db, called whendatabase needs tobe
int oldVersion,intnewVersion) downgraded.

59.1 Necessity I Features I Advantages of SQLite


The following are the features of SQLite databases:
1) Serverless: SQLite does not require a separate server process or system to operate. The
SQLite library accesses its storage files directly.
2) Zero Configuration: No server means no setup. Creating an SQL ite database instance is as
easy as opening a file.
3) Cross-Platform: A complete SQLite database is stored in a single crossplatform disk file,
requiring noadministration.
4) Self-Contained: A single library contains the entire database system,which
integrates directly into a host application.
5) Transactional: SQLite transactions arefully ACID-compliant means all queries are
Atomic, Consistent, Isolated, and Durable.
6) Light-weight:Asthenamesuggests"Lite",SQLiteisverysmallandlightweight.

G. P. CO6I [MAD-22617] 328


MIRAJ ( S.
B.
SHINTRE )
Method Description
void execSQL(Stringsql) executes the sql query not select query.

long insert(String table, String inserts a record on the database. The table
nullCoIumnHack, ContentVaIues specifies the table name, nullColumnHack
values) doesn't allow completely null values. If
second argument is null, android will store null
values if values are empty. The third argument
specifiesthevaluestobestored.

int update(String table, ContentValues updates a row.


values, String whereClause, String[]
whereArgs)

Cursor query(String table, String[] returns a cursor over the resultset.


columns, String selection, String[]
selectionArgs, String groupBy, String
having, StringorderBy)

7) Familiarlanguage:Familiarquerylanguagefordatabasedevelopersandadmins.
8) HighlyReliable:TheSQLitedevelopmentteamtakescodetestingandverificationvery serious y.

Disadvantages / Drawbacks of SQL ite


The following are the drawbacks of the SQLite database.
• SQLite does not work well in client/server Architecture.
• If you are using SQLite as a backend for High-volume website, then the SQLite will not work fine
whencompared with enterprise client/server database.
• The SQLite database is limited in size to 140 terabytes (TB). SQLite stores the
whole database in Single Disk File. Many file systems do not allow this much size of
the file.
• SQLite has not Implemented RIGHT OUTER JOIN and FULL OUTER JOIN
With SQLite, we can only implement a LEFT OUTER JOIN.
is not possib e to rename a column, remove a column, or add/remove constraints from a table
inSQLite. While you canalwayscreateanewtableandthen drop the older one.

G. P. CO6I [MAD-22617] 329


MIRAJ ( S.
B.
SHINTRE )
• Views in SQLite are read-only. We can't use DIML statements (Insert, Update, and
Delete) with Views.
• We cannot use GRANT and REVOKE statements with SQLite.
5.92 Creation and connection of the database
Database - Creation
• InordertocreateadatabaseyoujustneedtocallthismethodopenOrCreateDatabase withyour
database name and mode as a parameter.
• It returns aninstance ofSQLite database whichyouhave to receive inyour own object. Its
syntax is given below
SQLiteDatabase mydatabase = openOrCreateDatabase("your database name", MODE PRIVATE,
null);

The following functions available in the database package:

Sr.No Method &Description

1 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags,


DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode. The common
flags mode could be OPEN READWRITE OPEN READONLY

2
openDatabase(Stringpath, SQLiteDatabase.CursorFactory factory, int flags)
Itissimilartotheabovemethodasitalsoopenstheexistingdatabasebutitdoesnot define any
handler to handle the errors of databases

openOrCreateDatabase(String path, SQLiteDatabase.CursorF-actory factory)


Itnotonlyopensbutcreatethedatabaseifitnotexists.Thismethodis
equivalent to openDatabase method.
4 openOrCreateDatabase(File file,SQLiteDatabase.CursorFactory factory)

G. P. CO6I [MAD-22617] 330


MIRAJ ( S.
B.
SHINTRE )
This method is similar to above method but it takes the File object as a path rather then a
string. It is equivalent to file.getPath()
Opening and Closing Android SQLite Database Connection

• Before performing any database operations like insert, update, delete records in a table, first
open the database connection by calling getWritableDatabase() method as shown below:
public DBManager open() throws SQLException

dbHelper = new DatabaseHelper(context); database = dbHeIper.getWritabIeDatabase();


return this;

• The dbHelper is an instance of the subclass of SQLiteOpenHelper.


To close a database connection the following method is invoked.
public void closeo dbHelper.close();

Database - Insertion
• wecancreatetable orinsert data intotableusingexecSQL method defined in
SQLiteDatabase class.
Its syntax is given below
TABLEIFNOTEXISTSlogin(Username
VARCHAR, password VARCHAR);"); mydatabase.execSQL("lNSERT INTO
login VALUES('admin•, 'admin');");
• Thiswillinsertsomevaluesintoourtable inour database.Anothermethodtake some
additional parameter is given below

G. P. CO6I [MAD-22617] 331


MIRAJ ( S.
B.
SHINTRE )
• ATnhoitshm
erewthayo,dInnaontdornoliydi,nwseecrtadnaintase,rbtudtaatalsinotuostheedStoQuLpitdeadtaetaobramsoedbiyfypaslrseiangdy existing
Cdoantateintdvaltuaebsastoe iunsienrgt(b)im ndetahrogdu.ments

Following code is use to insert data into the SQL ite database using the insert() method in the android
application.
"Get the Data Repository in write mode
SQLiteDatabase db =this.getWritabIeDatabase();
//Create a new map of values, where column names are the keys

Sr.No Method &Description

1 execSQL(String sql, Object[] bindArgs)

ContentValues cValues = new ContentValues();


CValues.put(KEY_NAME, name);
cValues.put(KEY LOC, location);
designation);
// Insert the new row, returning the primary key value of the new row long newRowld=db.
cValues);

• Ifyouobserveabovecode, wearegettingthedatarepository inwritemode and adding


required values tocolumns andinserting into database.

Update Data in SQLite Database

• Inandroid, wecanupdatethedataintheSQLitedatabaseusinganupdate() method in


androidapplications.
Following code is use to update the data in the SQL ite database using an update() method in the

G. P. CO6I [MAD-22617] 332


MIRAJ ( S.
B.
SHINTRE )
android application.
"Get the Data Repository in write mode SQLiteDatabase
db = this.getWritabIeDatabase(); ContentValues cVals=
new ContentValues();
location);
CVals.put(KEY_DESG, designation); int count -
db.update(TABLE_Users, cVals, KEY ID+" - 7" new

Ifyouobserve above code, weare updatingthe detailsusing update() method based on our
requirements.

Delete Data from SQLite Database

• Inandroid, we can delete datafrom the SQLite database using the delete() method in
android applications.

Following code is use to delete the data from the SQL ite database using the delete() method in
the android application.
"Get the Data Repository in write mode
SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_Users,
KEYID*" new
String[]{String.valueOf(userid)});

• If you observe above code, we are deleting the details using delete() method based on
our requirements.
.9.3 Extracting value from cursors
Cursors
• Cursors arewhatcontaintheresultsetofaquery made against adatabase in Android.

G. P. CO6I [MAD-22617] 333


MIRAJ ( S.
B.
SHINTRE )
• The Cursor class has an API that allows an app to read (in a type-safe manner) the
columnsthatwerereturnedfromthequeryaswellasiterateovertherows
of the resultset.

• 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
tothe table. We can move the cursor forward and retrieve the data.

Cursor resultSet = * from login", null);


resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
Thereareotherfunctionsavailableinthe Cursorclassthatallows usto
effectively retrieve the data. Thatincludes
Sr.No Method
&Description
1 getCoIumnCount()
This method return the total number of columns of the table.

2 getCoIumnIndex(String columnName)
Thismethodreturnstheindexnumberofacolumnbyspecifyingthenameofthe
column

3 getCoIumnName(int col umn Index)


Thismethodreturnsthenameofthecolumnbyspecifyingtheindex
ofthecolumn
4 getColumnNames()
This method returns the array of all the column names of the table.
5 getCount()
This method returns the total number of rows in the cursor
6 getPosition()

This method returns the current position of the cursor in the table

G. P. CO6I [MAD-22617] 334


MIRAJ ( S.
B.
SHINTRE )
Cursor class provides the following methods to manipulate its internal position:
1) boolean Cursor.move(intoffset):Movesthe position bythegivenoffset
2) boolean Cursor.moveToFirst(): Movesthepositiontothefirstrow
3) boolean Cursor.moveToLast(): Movestheposition to thelastrow
4) boolean Cursor.moveToNext():Movesthecursor to thenext rowrelative to the
current position
5) boolean Cursor.moveT0Position(int position): Moves the cursor to the specified position
6) Cursor.moveToPrevious(): Moves the cursortothe previous row relative to the current
position

• Each move() method returns a boolean to indicate whether the operation was
successfulornot.Thisflagisusefulforiteratingovertherowsina cursor.
• ACursorrepresentstheentireresultset ofthequery. Once thequery isfetched a call to
cursor.moveT0First() ismade.

Calling moveToFirst() does twothings:


I) Itallowsustotestwhether the queryreturned anemptyset(by testing thereturn value)
2) It moves the cursor to the first result (when the set is not empty)

The following code is used to fetch all records:


public Cursor fetch()

String[] columns = new String[] { DatabaseHelper._lD,


DatabaseHelper.SUBJECT, DatabaseHelper.DESC
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns,
null, null null, null, null); if (cursor null)

cursor.moveToFirst(); return

cursor;

G. P. CO6I [MAD-22617] 335


MIRAJ ( S.
B.
SHINTRE )
• Another way to use a Cursor is to wrap it in a CursorAdapter. Just as ArrayAdapter
adapts arrays, CursorAdapter adapts Cursor objects, making their data available to an
AdapterView like a ListView.
5.9.4 Transactions
• Generally in SQLite transaction means it's a set of T-SQL statements which will execute together as a
unitlikesingleT-SQLstatement.IfalltheseT-SQLstatementsexecuted
successfully without having any errors then the transaction will be committed and all the changes made
by the transaction will be saved to database permanently. In case if any error occurred while
executing these SQLite statements then the complete transaction will berollbacked.

• If we are performing any operation on table like INSERT, UPDATE or DELETE a record from table
then we will call it as transaction is happening on table and these transactions will follow ACID
properties to ensure data integrity.

• In any DBMS the database transactions must follow ACID (atomicity, consistency, isolation and
durability) properties to produce consistent results and must be isolated from other
databaseoperations.
• The SQL ite database transactions also follow ACID properties of DBMS to make sure data
transactions consistent throught the database.
stands for Atomic, Consistent, Isolated, and Durable and any transaction happening in
DBMS must possess all these qualities

G. P. CO6I [MAD-22617] 336


MIRAJ ( S.
B.
SHINTRE )
Extra Example(Related to CH:5):
Database:
Xml file:

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FCF8F9"
android:orientation="vertical"
tools:context=".MainActivity">

<ImageView
android:layout_width="match_parent"
android:layout_height="184dp"
android:scaleType="centerCrop"
android:src="@drawable/todo"

/>

<EditText
android:id="@+id/dt"
android:layout_width="240dp"
android:layout_height="48dp"
android:layout_marginStart="80sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="200dp"
android:background="#ffffff"
android:hint="Enter Date " />

<EditText
android:id="@+id/task"
android:layout_width="235dp"
android:layout_height="83dp"
android:layout_gravity="start"
android:layout_marginStart="80sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="270dp"
android:background="#ffffff"
android:hint="Enter task"
android:textAlignment="textStart" />

<Button
android:id="@+id/b1"
android:layout_width="95dp"
android:layout_height="50sp"
android:layout_marginStart="50sp"

G. P. CO6I [MAD-22617] 337


MIRAJ ( S.
B.
SHINTRE )
android:layout_marginLeft="50dp"
android:layout_marginTop="400dp"
android:background="#F06292"
android:onClick="insert"

G. P. CO6I [MAD-22617] 338


MIRAJ ( S.
B.
SHINTRE )
android:text="ADD" />

<Button
android:id="@+id/b2"
android:layout_width="95dp"
android:layout_height="50sp"
android:layout_marginStart="250sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="400dp"
android:background="#F06292"
android:onClick="display"
android:text="Show" />

<Button
android:id="@+id/b3"
android:layout_width="95dp"
android:layout_height="50sp"
android:layout_marginStart="50sp"
android:layout_marginLeft="50dp"
android:layout_marginTop="500dp"
android:background="#F06292"
android:onClick="delete"
android:text="Delete" />
<Button
android:id="@+id/b4"
android:layout_width="95dp"
android:layout_height="50sp"
android:layout_marginStart="250sp"
android:layout_marginLeft="50dp"
android:layout_marginTop="500dp"
android:background="#F06292"
android:onClick="update"
android:text="Update" />

</RelativeLayout>

MainActicity.java:
package com.example.studdb;

import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

DBHelper DB;

G. P. CO6I [MAD-22617] 339


MIRAJ ( S.
B.
SHINTRE )
EditText dt,task;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dt=findViewById(R.id.dt);
task=findViewById(R.id.task);
DB=new DBHelper(this);
}

public void insert(View view) {

String s1=dt.getText().toString();
String s2=task.getText().toString();

Boolean check=DB.insertData(s1,s2);
if(check){
Toast.makeText(this, "Task Added :) ", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "Task Not Added :( ", Toast.LENGTH_SHORT).show();
}
}

public void display(View view) {


Cursor c1=DB.getData();
if(c1.getCount()==0){
Toast.makeText(this, "No data found :( ", Toast.LENGTH_SHORT).show();
}
else {
StringBuilder br=new StringBuilder();
while(c1.moveToNext()){
br.append("Date : ").append(c1.getString(0)).append("\n");
br.append("Task : ").append(c1.getString(1)).append("\n\n");

}
AlertDialog.Builder b1=new AlertDialog.Builder(MainActivity.this);
b1.setTitle("To Do:");
b1.setMessage(br.toString());
b1.setIcon(R.drawable.onbulb);
b1.show();
}

}
public void delete(View view) {
String s1=dt.getText().toString();
Boolean check=DB.deleteData(s1);
if(check==true){
Toast.makeText(this, "Task Deleted", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Task not deleted :( ", Toast.LENGTH_SHORT).show();

G. P. CO6I [MAD-22617] 340


MIRAJ ( S.
B.
SHINTRE )
}
}

public void update(View view) {


String s1=dt.getText().toString();
String s2=task.getText().toString();
Boolean check=DB.updateData(s1,s2);
if(check==true){
Toast.makeText(MainActivity.this, "Task updated :) ", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Task not updated :( ", Toast.LENGTH_SHORT).show();
}
}
}

DBHelper.java:
package com.example.studdb;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import
android.database.sqlite.SQLiteOpenHelper;public class
DBHelper extends SQLiteOpenHelper { private
SQLiteDatabase DB;
DBHelper(Context context) {
super(context, "TODO1.db",null,1);
}

@Override
public void onCreate(SQLiteDatabase DB) {
DB.execSQL("create table todotbl2(date TEXT ,task TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("drop table if exists todotbl2");
}
Boolean insertData(String dt, String task){
DB=this.getWritableDatabase();
ContentValues c1=new ContentValues();
c1.put("date",dt);
c1.put("task",task);
long result=DB.insert("todotbl2",null,c1);
return result != -1;
}
Boolean updateData(String dt, String task){
DB=this.getWritableDatabase();

G. P. CO6I [MAD-22617] 341


MIRAJ ( S.
B.
SHINTRE )
ContentValues c1=new ContentValues();
c1.put("date",dt);
c1.put("task",task);
@SuppressLint("Recycle") Cursorcu=DB.rawQuery("select *fromtodotbl2 ",null);
if(cu.getCount()>0)
{
long result = DB.update("todotbl2", c1 ,"date=?",new String[]{dt});
return result != -1;
}
else {
return false;
}
}
Boolean deleteData(String dt){
DB=this.getWritableDatabase();
ContentValues c1=new ContentValues();
c1.put("date",dt);
@SuppressLint("Recycle") Cursor cu=DB.rawQuery("select * from todotbl2",null);
if(cu.getCount()>0)
{
long result = DB.delete("todotbl2", "date=?", new String[]{dt});
return result != -1;
}
else {
return false;
}
}
Cursor getData(){
DB=this.getReadableDatabase();
return DB.rawQuery("select * from todotbl2",null);
}
}

outpit:

G. P. CO6I [MAD-22617] 342


MIRAJ ( S.
B.
SHINTRE )
EXPLICIT INTENT
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center"
android:background="#E0C6FF">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explicit intent"
android:textSize="50sp"/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:hint="Enter no to count factorial"
android:layout_marginTop="50dp"
android:id="@+id/no"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="factorial"

G. P. CO6I [MAD-22617] 343


MIRAJ ( S.
B.
SHINTRE )
android:text="Factorial" />

</LinearLayout>

Mainactivity.java
package com.example.explicitintentfactorialexp18;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

EditText no;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
no=findViewById(R.id.no);
}

public void factorial(View view) {


Intent i=new Intent(this,Factorial.class);
i.putExtra("message",no.getText().toString());
startActivity(i);
}
}
activity_factorial.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Factorial"
android:orientation="vertical"
android:gravity="center"
android:background="#FBBDC8">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Factorial"
android:textSize="70dp"
android:id="@+id/fact_show"/>

</LinearLayout>
Factorial.java
package com.example.explicitintentfactorialexp18;

G. P. CO6I [MAD-22617] 344


MIRAJ ( S.
B.
SHINTRE )
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

public class Factorial extends AppCompatActivity {

TextView result;
int fact=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_factorial);
result=findViewById(R.id.fact_show);
Intent g=getIntent();
String n=g.getStringExtra("message");
int no=Integer.parseInt(n);
while(no>0){
fact=fact*no;
no=no-1;
}
result.setText(String.valueOf(fact));
}
}

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 345


FRAGMENT
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/Theme.FragmentApp.AppBarOverlay"
android:background="#00E676">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minHeight="?actionBarSize"
android:padding="@dimen/appbar_padding"
android:text="@string/app_name"
android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
android:textColor="#01552C"
android:background="#00E676"/>

<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00E676" />
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Mainactivity.java
package com.example.fragmentapp;

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;

import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;

G. P. CO6I [MAD-22617] 346


MIRAJ ( S.
B.
SHINTRE )
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.example.fragmentapp.ui.main.SectionsPagerAdapter;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this,
getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
}

fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.main.PlaceholderFragment">
<TextView
android:id="@+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/activity_vertical_margin"
android:layout_marginEnd="@dimen/activity_horizontal_margin"
android:layout_marginStart="@dimen/activity_horizontal_margin"
android:layout_marginTop="@dimen/activity_vertical_margin"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="@+id/constraintLayout"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1" />
</androidx.constraintlayout.widget.ConstraintLayout>
ui.main → PageViewModel.java
package com.example.fragmentapp.ui.main;

import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;

G. P. CO6I [MAD-22617] 347


MIRAJ ( S.
B.
SHINTRE )
import androidx.lifecycle.ViewModel;
public class PageViewModel extends ViewModel {
private MutableLiveData<Integer> mIndex = new MutableLiveData<>();
private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
@Override
public String apply(Integer input) {
return "Hello world from section: " + input;
}
});

public void setIndex(int index) {


mIndex.setValue(index);
}

public LiveData<String> getText() {


return mText;
}
}
ui.main → PlaceholderFragment.java
package com.example.fragmentapp.ui.main;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import

androidx.lifecycle.ViewModelProvider;import

com.example.fragmentapp.R;

/**
* A placeholder fragment containing a simple view.
*/
public class PlaceholderFragment extends Fragment {

private static final String ARG_SECTION_NUMBER = "section_number";

private PageViewModel pageViewModel;

public static PlaceholderFragment newInstance(int index) {


PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER, index);
fragment.setArguments(bundle);
return fragment;
}

G. P. CO6I [MAD-22617] 348


MIRAJ ( S.
B.
SHINTRE )
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageViewModel = new ViewModelProvider(this).get(PageViewModel.class);
int index = 1;
if (getArguments() != null) {
index = getArguments().getInt(ARG_SECTION_NUMBER);
}
pageViewModel.setIndex(index);
}

@Override
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_main, container, false);
final TextView textView = root.findViewById(R.id.section_label);
pageViewModel.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s){
textView.setText(s);
}
});
return root;
}
}
ui.main → SectionsPagerAdapter.java
package com.example.fragmentapp.ui.main;

import android.content.Context;
import android.widget.Switch;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.fragmentapp.Gallery;
import com.example.fragmentapp.Music;
import com.example.fragmentapp.R;
import com.example.fragmentapp.Video;

/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {

@StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2,R.string.tab_text_3};
private final Context mContext;

public SectionsPagerAdapter(Context context, FragmentManager fm) {

G. P. CO6I [MAD-22617] 349


MIRAJ ( S.
B.
SHINTRE )
super(fm);
mContext = context;
}

@Override
public Fragment getItem(int position) {
Fragment f=null;
switch(position){
case 0:
f=new Music();
break;
case 1:
f=new Video();
break;
case 2:
f=new Gallery();
break;
}
return f;
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}

@Override
public int getCount() {
// Show 2 total pages.
return 3;
}
}

fragment_music.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Music"
android:background="@color/design_default_color_error">

<!-- TODO: Update blank fragment layout -->


<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bc">

<ImageButton
android:layout_width="100dp"
android:layout_height="100dp"

G. P. CO6I [MAD-22617] 350


MIRAJ ( S.
B.
SHINTRE )
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:id="@+id/play"

android:layout_margin="40dp"
android:src="@drawable/play"
android:background="@android:color/transparent"
android:scaleType="fitCenter"/>

<ImageButton
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="40dp"
android:layout_toRightOf="@+id/play"
android:src="@drawable/pause"
android:background="@android:color/transparent"
android:id="@+id/pause"
android:scaleType="fitCenter"/>

<ImageButton
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="40dp"
android:layout_toLeftOf="@+id/play"
android:src="@drawable/stop"
android:background="@android:color/transparent"
android:scaleType="fitCenter"
android:id="@+id/stop"/>

</RelativeLayout>

</FrameLayout>

Music.java
package com.example.fragmentapp;

import android.media.MediaPlayer;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;

/**

G. P. CO6I [MAD-22617] 351


MIRAJ ( S.
B.
SHINTRE )
* A simple {@link Fragment} subclass.
* Use the {@link Music#newInstance} factory method to
* create an instance of this fragment.
*/
public class Music extends Fragment {

// TODO: Renameparameterarguments, choosenamesthatmatch


// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER

private static final String ARG_PARAM1 = "param1";


private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters


private String mParam1;
private String mParam2;
MediaPlayer mp=null;
ImageButton play,pause,stop;

public Music() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Music.
*/
// TODO: Rename and change types and number of parameters
public static Music newInstance(String param1, String param2) {
Music fragment = new Music();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,

G. P. CO6I [MAD-22617] 352


MIRAJ ( S.
B.
SHINTRE )
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root=inflater.inflate(R.layout.fragment_music, container, false);
play=root.findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mp==null){
mp= MediaPlayer.create(getActivity(),R.raw.channa);
}
mp.start();
}
})

pause=root.findViewById(R.id.pause);
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mp!=null){
mp.pause();
}
}
});

stop=root.findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopsong();
}
});

return root;
}

private void stopsong() {


mp.release();
mp=null;
}
public void onComplete(MediaPlayer mp){
stopsong();
}
}

fragment_video.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Video"

G. P. CO6I [MAD-22617] 353


MIRAJ ( S.
B.
SHINTRE )
android:background="@color/black">

<VideoView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/video"
android:layout_gravity="center"/>

</FrameLayout>

Video.java
package com.example.fragmentapp;

import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.VideoView;

/**
* A simple {@link Fragment} subclass.
* Use the {@link Video#newInstance} factory method to
* create an instance of this fragment.
*/
public class Video extends Fragment {

// TODO: Renameparameterarguments, choosenamesthatmatch


// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters


private String mParam1;
private String mParam2;
VideoView video;

public Video() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Video.

G. P. CO6I [MAD-22617] 354


MIRAJ ( S.
B.
SHINTRE )
*/
// TODO: Rename and change types and number of parameters
public static Video newInstance(String param1, String param2) {
Video fragment = new Video();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

G. P. CO6I [MAD-22617] 355


MIRAJ ( S.
B.
SHINTRE )
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_video, container, false);
video=root.findViewById(R.id.video);
String vpath="android.resource://com.example.fragmentapp/"+R.raw.video;
Uri url=Uri.parse(vpath);
video.setVideoURI(url);
MediaController mc=new MediaController(getActivity());
video.setMediaController(mc);
mc.setAnchorView(video);
return root;
}
}

fragment_gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Gallery"
android:background="@drawable/frnd">

<!-- TODO: Update blank fragment layout -->

</FrameLayout>

Gallery.java
package com.example.fragmentapp;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
* A simple {@link Fragment} subclass.
* Use the {@link Gallery#newInstance} factory method to
* create an instance of this fragment.
*/
public class Gallery extends Fragment {

// TODO: Renameparameterarguments, choosenamesthatmatch


// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

G. P. CO6I [MAD-22617] 356


MIRAJ ( S.
B.
SHINTRE )
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

public Gallery() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Gallery.
*/
// TODO: Rename and change types and number of parameters
public static Gallery newInstance(Stringparam1, String param2){
Gallery fragment = new Gallery();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_gallery, container, false);
}
}

output:

G. P. CO6I [MAD-22617] 357


MIRAJ ( S.
B.
SHINTRE )
TEXTTOSPEECH
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical"
android:background="#CDB7FF">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text to \nspeech"
android:textSize="80sp"
android:gravity="center"/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:hint="Text"
android:layout_margin="50dp"
android:textSize="30sp"
android:id="@+id/text"/>

</LinearLayout>
MainActivity.java
package com.example.texttospeech;

G. P. CO6I [MAD-22617] 358


MIRAJ ( S.
B.
SHINTRE )
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextToSpeech ts;
EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=findViewById(R.id.text);
text.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//ts.speak("Write something",TextToSpeech.QUEUE_FLUSH,null);
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//ts.speak(s.toString(),TextToSpeech.QUEUE_FLUSH,null);
}
@Override
public voidafterTextChanged(Editable s){
String s1=text.getText().toString();
String s2;
s2 = new String(String.valueOf(s1.charAt(s1.length()-1)));
ts.speak(s2,TextToSpeech.QUEUE_FLUSH,null);
}
});
ts=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status!=TextToSpeech.ERROR){
ts.setLanguage(Locale.UK);
}
}
});
}
public void onPause(){
if (ts != null) {
ts.stop();
ts.shutdown();
}
super.onPause();
}
}

G. P. CO6I [MAD-22617] 359


MIRAJ ( S.
B.
SHINTRE )
abcd and abd

a s d f

z x c v b n m
?123

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 360


Camera:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fff996"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take a Photo"
android:onClick="take"/>
<ImageView
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:layout_gravity="center_horizontal"
android:id="@+id/pic"/>

</LinearLayout>
Java code:
package com.example.cameraa;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {


ImageView pic;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic=findViewById(R.id.pic);
}

public void take(View view) {


Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);

}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

G. P. CO6I [MAD-22617] 361


MIRAJ ( S.
B.
SHINTRE )
super.onActivityResult(requestCode, resultCode, data);
Bitmap ph=(Bitmap)data.getExtras().get("data");
pic.setImageBitmap(ph);
}
}

manifest file:
<uses-permission android:name="android.permission.CAMERA"/>

G. P. CO6I [MAD-22617] 362


MIRAJ ( S.
B.
SHINTRE )
Vedio Recording:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fff789"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record Video"
android:backgroundTint="#3C3A2A"
android:layout_marginStart="150sp"
android:layout_marginLeft="150sp"
android:textColor="#FFF121"
android:onClick="record"/>

</LinearLayout>

G. P. CO6I [MAD-22617] 363


MIRAJ ( S.
B.
SHINTRE )
Java code:
package com.example.vediorecord;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

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

public void record(View view) {


Intent intent=new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT,10);
startActivityForResult(intent,1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
AlertDialog.Builder builder=new AlertDialog.Builder(this);
VideoView videoView=new VideoView(this);
videoView.setVideoURI(data.getData());
videoView.start();
builder.setTitle("Video Recording...");
builder.setView(videoView).show();
}
}
Manifest file:
<uses-feature android:name="android.hardware.camera2"/>

G. P. CO6I [MAD-22617] 364


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 365
MIRAJ ( S.
B.
SHINTRE )
Services:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F179A1"
tools:context=".MainActivity">

<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints">

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="170dp"
android:fontFamily="sans-serif-condensed-light"
android:text="@string/heading"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="#26A69A"
android:textSize="36sp"
android:textStyle="bold" />
<Button
android:id="@+id/startButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#26A69A"
android:fontFamily="sans-serif-condensed-light"
android:text="@string/startButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:onClick="s1"
android:textStyle="bold" />
<Button
android:id="@+id/stopButton"

G. P. CO6I [MAD-22617] 366


MIRAJ ( S.
B.
SHINTRE )
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#26A69A"
android:fontFamily="sans-serif-condensed-light"
android:text="@string/stopButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:onClick="s2"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
Java code:
package com.example.servicelifecycle;

import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void s1(View view) {
startService(new Intent( this, NewService.class ) );
}

public void s2(View view) {


stopService(new Intent( this, NewService.class ) );
}

manifest file:
<service android:name=".NewService"/>
NewService class:
package com.example.servicelifecycle;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;

G. P. CO6I [MAD-22617] 367


MIRAJ ( S.
B.
SHINTRE )
import android.widget.Toast;

import androidx.annotation.Nullable;

public class NewService extends Service {

private MediaPlayer player; // declaring object of MediaPlayer

@Override
public int onStartCommand(Intent intent, int flags, int startId) { // execution of service will start on calling
this method

player = MediaPlayer.create( this, Settings.System.DEFAULT_RINGTONE_URI ); // creating a media player


which will play the audio of Default ringtone

player.setLooping( true ); // providing the boolean value as true to play the audio on loop

player.start(); // starting the process


Toast.makeText(getApplicationContext(),"service started",Toast.LENGTH_LONG).show();
return START_STICKY; // returns the status of the program
}
@Override
public void onDestroy() { // execution of the service will stop on calling this method
super.onDestroy();
player.stop(); // stopping the process
Toast.makeText(getApplicationContext(),"service stopped",Toast.LENGTH_SHORT).show();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

G. P. CO6I [MAD-22617] 368


MIRAJ ( S.
B.
SHINTRE )
Bluetooth:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
android:layout_gravity="center"
tools:context=".MainActivity">
<TextView
android:layout_width="310dp"
android:layout_height="65dp"
android:layout_marginStart="50sp"
android:layout_marginLeft="50sp"
android:layout_marginTop="20dp"
android:fontFamily="sans-serif"
android:text="Bluetooth "
android:textColor="#000000"
android:textSize="30sp" />
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"

G. P. CO6I [MAD-22617] 369


MIRAJ ( S.
B.
SHINTRE )
android:layout_height="wrap_content"
android:layout_marginStart="50sp"
android:layout_marginLeft="50sp"
android:layout_marginTop="10dp"
android:text="Turn ON"
android:onClick="on"
/>
<Button
android:id="@+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="50sp"
android:layout_marginLeft="50sp"
android:layout_marginTop="10dp"
android:onClick="visible"
android:text="Get Visible" />

<Button
android:id="@+id/b4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="50sp"
android:layout_marginLeft="50sp"
android:layout_marginTop="10dp"
android:onClick="list"
android:text="List Devices" />

<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="50sp"
android:layout_marginLeft="50sp"
android:layout_marginTop="10dp"
android:onClick="off"
android:text="Turn OFF"
/>

<ListView
android:id="@+id/l1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:textColor="#ffffff"

/>
</LinearLayout>
Colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

G. P. CO6I [MAD-22617] 370


MIRAJ ( S.
B.
SHINTRE )
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
<color name="actionbar_background">#000000</color>

<color name="actionbar_text">#ffffff</color>
</resources>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetooth">

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


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

<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/CustomActionBarTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>
Styles.xml:
<resources>

<!-- Base application theme. -->


<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>

</style>
<style name="CustomActionBarTheme"
parent="@style/Theme.AppCompat.Light.DarkActionBar">
<item name="android:actionBarStyle">@style/MyActionBar</item>
<item name="android:actionBarTabTextStyle">@style/MyActionBarTabText</item>
<item name="android:actionMenuTextColor">@color/actionbar_text</item>

<!-- Support library compatibility -->


<item name="actionBarStyle">@style/MyActionBar</item>
<item name="actionBarTabTextStyle">@style/MyActionBarTabText</item>

G. P. CO6I [MAD-22617] 371


MIRAJ ( S.
B.
SHINTRE )
<item name="actionMenuTextColor">@color/actionbar_text</item>
</style>

<!-- ActionBar styles -->


<style name="MyActionBar"
parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse" >
<item name="android:background">@color/actionbar_background</item>
<item name="android:titleTextStyle">@style/MyActionBarTitleText</item>

<!-- Support library compatibility -->


<item name="background">@color/actionbar_background</item>
<item name="titleTextStyle">@style/MyActionBarTitleText</item>
</style>

<!-- ActionBar title text -->


<style name="MyActionBarTitleText"
parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textColor">@color/actionbar_text</item>
</style>

<!-- ActionBar tabs text -->


<style name="MyActionBarTabText"
parent="@style/Widget.AppCompat.ActionBar.TabText">
<item name="android:textColor">@color/actionbar_text</item>
</style>

</resources>
Java:
package com.example.bluetooth;

import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {


Button b1,b2,b3,b4;
private BluetoothAdapter ba;
ListView l1;

G. P. CO6I [MAD-22617] 372


MIRAJ ( S.
B.
SHINTRE )
private Set<BluetoothDevice> pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=findViewById(R.id.b1);
b2=findViewById(R.id.b2);
b3=findViewById(R.id.b3);
b4=findViewById(R.id.b4);
l1=findViewById(R.id.l1);
ba=BluetoothAdapter.getDefaultAdapter();
getSupportActionBar().setHomeAsUpIndicator(R.drawable.pictureone);// set drawable icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Toast.makeText(this, "Action bar icon clicked", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void on(View view) {
if(!ba.isEnabled()){
Intent i1=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i1,0);
Toast.makeText(this, "Bluetooth TURNED ON", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Bluetooth Already ON", Toast.LENGTH_SHORT).show();
}
}
publicvoidoff(Viewview) {
ba.disable();
Toast.makeText(this, "Bluetooth OFF", Toast.LENGTH_SHORT).show();
}
public void visible(View view) {
Intent i2=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(i2,0);
}
public void list(View view) {
pd=ba.getBondedDevices();
ArrayList list=new ArrayList();
for(BluetoothDevice bt :pd) list.add(bt.getName());
Toast.makeText(this, "Showing paired devices ", Toast.LENGTH_SHORT).show();

final ArrayAdapter ad=new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);


l1.setAdapter(ad);
}

G. P. CO6I [MAD-22617] 373


MIRAJ ( S.
B.
SHINTRE )
output:

G. P. CO6I [MAD-22617] 374


MIRAJ ( S.
B.
SHINTRE )
Activity lifecycle:
• Xml code-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#F8A4C0">
</LinearLayout>

• Javacode-

package com.example.activity_life_cycle;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

G. P. CO6I [MAD-22617] 375


MIRAJ ( S.
B.
SHINTRE )
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(),"onCreate()
called",Toast.LENGTH_SHORT).show();
}

@Override
protected void onStart() {
super.onStart();
Toast.makeText(getApplicationContext(),"onStart() called",Toast.LENGTH_SHORT).show();
}

@Override
protected void onResume() {
super.onResume();
Toast.makeText(getApplicationContext(),"onResume()
called",Toast.LENGTH_SHORT).show();
}

@Override
protected void onPause() {
super.onPause();
Toast.makeText(getApplicationContext(),"onPause() called",Toast.LENGTH_SHORT).show();
}

@Override
protected void onStop() {
super.onStop();
Toast.makeText(getApplicationContext(),"onStop() called",Toast.LENGTH_SHORT).show();
}

@Override
protected void onRestart() {
super.onRestart();
Toast.makeText(getApplicationContext(),"onRestart()
called",Toast.LENGTH_SHORT).show();
}

@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(),"onDestroy()
called",Toast.LENGTH_SHORT).show();
}
}

• Output-

G. P. CO6I [MAD-22617] 376


MIRAJ ( S.
B.
SHINTRE )
Broadcast receiver:
• Xml code-

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Battery Status"
android:textSize="20dp"
android:id="@+id/tv"
/>
</LinearLayout>

• MainActivity.java-

package com.example.broadcastreceiver1;

import androidx.appcompat.app.AppCompatActivity;

G. P. CO6I [MAD-22617] 377


MIRAJ ( S.
B.
SHINTRE )
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


BroadcastRec bc;
TextView tv;
WifiManager wm;
ConnectivityManager cm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=findViewById(R.id.tv);
bc=new BroadcastRec(tv);
// wm=(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//cm=(ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
}

@Override
protected void onStart() {
super.onStart();
registerReceiver(bc,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
registerReceiver(bc,new IntentFilter(Intent.ACTION_BATTERY_LOW));
registerReceiver(bc,new IntentFilter(Intent.ACTION_POWER_CONNECTED));
registerReceiver(bc,new IntentFilter(Intent.ACTION_POWER_DISCONNECTED));
registerReceiver(bc,new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
registerReceiver(bc,new IntentFilter(Intent.ACTION_BUG_REPORT));
registerReceiver(bc,new IntentFilter(Intent.ACTION_REBOOT));
registerReceiver(bc,new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
registerReceiver(bc,new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));

@Override
protected void onStop() {
super.onStop();
unregisterReceiver(bc);
}

}BroadcastRec.java-

package com.example.broadcastreceiver1;

G. P. CO6I [MAD-22617] 378


MIRAJ ( S.
B.
SHINTRE )
import android.app.usage.NetworkStats;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class BroadcastRec extends BroadcastReceiver {


TextView tv;
public BroadcastRec(TextView tv){
this.tv=tv;
}
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW)){
tv.setText("Battery is low !");
}
if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
int perc=intent.getIntExtra("level",0);
tv.setText("Battery "+perc+"%");
}
if(Intent.ACTION_POWER_CONNECTED.equals(intent.getAction()))
Toast.makeText(context,"Charging Connected !",Toast.LENGTH_SHORT).show();
if(Intent.ACTION_POWER_DISCONNECTED.equals(intent.getAction()))
Toast.makeText(context,"Charging Disconnected !",Toast.LENGTH_SHORT).show();
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
Toast.makeText(context,"BOOT COMPLETED !",Toast.LENGTH_SHORT).show();
if(Intent.ACTION_REBOOT.equals(intent.getAction()))
Toast.makeText(context,"System Rebooted!",Toast.LENGTH_SHORT).show();
if(WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())){
int
wifistate=intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,WifiManager.WIFI_STATE_UNKN
OWN);
switch (wifistate){
case WifiManager.WIFI_STATE_ENABLED:
Toast.makeText(context,"Wifi is ON!",Toast.LENGTH_LONG).show();
break;
case WifiManager.WIFI_STATE_DISABLED:
Toast.makeText(context,"Wifi is OFF!",Toast.LENGTH_LONG).show();
break;
}

}
if(Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(intent.getAction())){
boolean mode=intent.getBooleanExtra("state",false);
if(mode)

G. P. CO6I [MAD-22617] 379


MIRAJ ( S.
B.
SHINTRE )
Toast.makeText(context,"Aeroplane mode is ON!",Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"Aeroplane mode is OFF!",Toast.LENGTH_LONG).show();
}

Output-

Animation:
• Xml code-

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

G. P. CO6I [MAD-22617] 380


MIRAJ ( S.
B.
SHINTRE )
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center"
>

<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/android"
android:id="@+id/img"
/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/lv"
android:layout_margin="50dp"
/>

</LinearLayout>

• Java code-

package com.example.animation;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


ListView lv;
Animation a;
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=findViewById(R.id.lv);
img=findViewById(R.id.img);
String style[]=getResources().getStringArray(R.array.animationStyle);
final ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,style);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

G. P. CO6I [MAD-22617] 381


MIRAJ ( S.
B.
SHINTRE )
if(adapter.getItem(i).equals("Clockwie/Anti Clockwise")){
rotate();
}
if(adapter.getItem(i).equals("Zomm In/Out")){
zoom();
}
if(adapter.getItem(i).equals("Fade In/Out")){
fadeIn();
}

}
});
}

private void fadeIn() {


a= AnimationUtils.loadAnimation(this,R.anim.fadein);
img.startAnimation(a);
}

private void zoom() {


zoomIn();
zoomOut();

private void zoomIn() {


a= AnimationUtils.loadAnimation(this,R.anim.zoomin);
img.startAnimation(a);
}

private void zoomOut() {


a= AnimationUtils.loadAnimation(this,R.anim.zoomout);
img.startAnimation(a);
}

public void rotate(){


a= AnimationUtils.loadAnimation(this,R.anim.rotate);
img.startAnimation(a);
}
}
Rotate.xml-

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotY="50%"
android:pivotX="50%"
android:duration="5000"
/>
</set>

G. P. CO6I [MAD-22617] 382


MIRAJ ( S.
B.
SHINTRE )
• zoomIn.xml

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromYScale="1"
android:fromXScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toYScale="3"
android:toXScale="3"
android:duration="5000"
/>
</set>

• fadeIn.xml

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="5000"
/>
</set>

• string.xml-

<resources>
<string name="app_name">Animation</string>
<string-array name="animationStyle">
<item>Clockwie/Anti Clockwise</item>
<item>Zomm In/Out</item>
<item>Fade In/Out</item>
</string-array>
</resources>

• Output-

G. P. CO6I [MAD-22617] 383


MIRAJ ( S.
B.
SHINTRE )
Async task:
• Activity_main.xml-

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center">
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/roll"
android:hint="Roll No"
android:layout_height="wrap_content"
android:id="@+id/nm"
android:hint="Name"
/>
<EditText
android:layout_width="200dp"

G. P. CO6I [MAD-22617] 384


MIRAJ ( S.
B.
SHINTRE )
/>
<EditText
android:layout_width="200dp"

android:layout_height="wrap_content"
android:id="@+id/cls"
android:hint="Class"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert Record"
android:layout_marginTop="50dp"
android:onClick="clk"/>

</LinearLayout>

MainActivity.java-
• package com.example.exp_26;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


Async async;
EditText roll,nm,cls;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
roll=findViewById(R.id.roll);
nm=findViewById(R.id.nm);
cls=findViewById(R.id.cls);

async=new Async(this);
}

public void clk(View view) {


async.execute(roll.getText().toString(),nm.getText().toString(),cls.getText().toString());
}
}

• Async.java-

package com.example.exp_26;

import android.app.ProgressDialog;
import android.content.Context;

G. P. CO6I [MAD-22617] 385


MIRAJ ( S.
B.
SHINTRE )
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import android.widget.VideoView;

public class Async extends AsyncTask<String,Void,Long> {


Context context;
long res;
DbClass db;
ProgressDialog pd;
public Async(Context c)
{
context=c;
db=new DbClass(context);
}
@Override
protectedvoid onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(context);
pd.setMax(100);
pd.setMessage("Inserting .....");
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
pd.dismiss();
Toast.makeText(context,"Inserting Failed. ",Toast.LENGTH_SHORT).show();
}
});
pd.show();
}
@Override
protected Long doInBackground(String... strings) {
res=db.insert(strings[0],strings[1],strings[2]);
try
{
for(int i=0;i<100;i=i+5)
{
Thread.sleep(200);
pd.setProgress(i);
}
}catch(InterruptedException e){
e.printStackTrace();
}
return res;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}

G. P. CO6I [MAD-22617] 386


MIRAJ ( S.
B.
SHINTRE )
@Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
pd.dismiss();
Toast.makeText(context,"Inserted at row-"+aLong,Toast.LENGTH_SHORT).show();
}
}

• DbClass.java-

package com.example.exp_26;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class DbClass extends SQLiteOpenHelper {


Context obj;
public DbClass(@Nullable Context context) {
super(context, "std2.db", null, 1);
obj=context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table tbl_stud(roll TEXT,name TEXT,class TEXT)");

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {

}
public long insert(String r,String n,String c){
SQLiteDatabase db=getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("roll",r);
contentValues.put("name",n);
contentValues.put("class",c);
long l=db.insert("tbl_stud",null,contentValues);
return l;
}
}

• Output-

G. P. CO6I [MAD-22617] 387


MIRAJ ( S.
B.
SHINTRE )
830d

3ebir 8edge

Tabe: sbud

name class
Filter Filter Filter

2 18304 Sabir Bedge TY

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 388


Content Provider:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#DAA5BC"
tools:context=".MainActivity">

<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="50dp"
android:hint="Name"
android:textSize="20dp"
android:id="@+id/nm"
/>

<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="50dp"
android:hint="Mobile"
android:textSize="20dp"
android:id="@+id/mob"
/>

<Button
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="50dp"
android:text="Add To Contacts"
android:textSize="20dp"
android:id="@+id/add"
android:onClick="addContact"
/>

<Button
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="50dp"
android:text="Contacts List"
android:textSize="20dp"
android:id="@+id/list"
android:onClick="showContact"
/>

G. P. CO6I [MAD-22617] 389


MIRAJ ( S.
B.
SHINTRE )
</LinearLayout>
Main.Activity.java:
package com.example.contentprovider;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText nm,mob;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nm=findViewById(R.id.nm);
mob=findViewById(R.id.mob);

public void addContact(View view) {


String name=nm.getText().toString() ;
String phone = mob.getText().toString() ;
Intent contactIntent = new Intent(ContactsContract.Intents.Insert. ACTION ) ;
contactIntent.setType(ContactsContract.RawContacts. CONTENT_TYPE ) ;
contactIntent
.putExtra(ContactsContract.Intents.Insert. NAME , name)
.putExtra(ContactsContract.Intents.Insert. PHONE , phone);
startActivityForResult(contactIntent , 1 ) ;
}
@Override
protectedvoidonActivityResult(intrequestCode,intresultCode,Intentintent){
super .onActivityResult(requestCode , resultCode , intent) ;
if (requestCode == 1 ) {
if (resultCode == Activity. RESULT_OK ) {
Toast. makeText ( this, "Contact Added" , Toast. LENGTH_SHORT ).show() ;
}
if (resultCode == Activity. RESULT_CANCELED ) {
Toast. makeText ( this, "Cancelled Adding Contact" ,
Toast. LENGTH_SHORT).show() ;
}
}
}

G. P. CO6I [MAD-22617] 390


MIRAJ ( S.
B.
SHINTRE )
public void showContact(View view) {
Intent Contacts=new Intent(Intent.ACTION_VIEW, ContactsContract.Contacts.CONTENT_URI);
startActivity(Contacts);
}
}
Maifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.contentprovider">

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


<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>

<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" />


</intent-filter>
</activity>
</application>

</manifest>

Output:

G. P. CO6I [MAD-22617] 391


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 392
MIRAJ ( S.
B.
SHINTRE )
Chapter 6
Security and Application Deployment
In android, we can send SMS from our android application in two ways By
using SmsManagerclass
By using an implicit Intent
1. SmsManager class-
If we use SMSManager API, it will directly send SMS from our application. SMSManager
class is used to send sms

Sr.No. Method & Description

1 ArrayList<String> divideMessage(Stringtext)
This method divides a message text into several fragments, none bigger than the maximum
SMS messagesize.

2 static SmsManager getDefault()


This method is used to get the default instance of the SmsManager

3 void sendDataMessage(String destinationAddress, String scAddress, short destinationPort,


byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent)
ThismethodisusedtosendadatabasedSMStoaspecificapplicationport.

4 void sendMultipartTextMessage(String destinationAddress, String scAddress,


ArrayList<String> parts, ArrayList<PendingIntent> sentIntents,
ArrayList<PendingIntent> deliveryIntents)
Send a multi-part text based SMS.

G. P. CO6I [MAD-22617] 393


MIRAJ ( S.
B.
SHINTRE )
5 void sendTextMessage(String destinationAddress, String scAddress, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent)
Send a text basedSMS.

SmsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null,"sms message", null, null);
SMSManager API required SEND_SMS permission in our android manifest to send
SMS.FollowingisthecodesnippettosetSEND_SMSpermissionsin manifest file.
<uses-permission android:name="android.permission.SEND_SMS"/>

In android, we can easily send an email from our android application using existing email
clientssuchasGMAIL,Outlook,etc.insteadofbuildinganemailclientfromscratch.
Generally, the Intent object in android with proper action (ACTION_SEND) and data
willhelpustolaunchtheavailableemailclientstosendanemailinour application.
In android, Intent is a messaging object which is used to request an action from
another app component such as activities, services, broadcast receivers, and content
providers.
TosendanemailusingtheIntentobjectinandroidapplication,weneedtowritethe code as
shown below.

Intent it = new Intent(Intent.ACTION_SEND); it.putExtra(Intent.EXTRA_EMAIL, new


String[]{"[email protected]"}); it.putExtra(Intent.EXTRA_SUBJEC T, "Welcome
to Tutlane"); it.putExtra(Intent.EXTRA_TEXT, "Hi Guest, Welcome to Tutlane Tutorial
Site");
it.setType("message/rfc822");

G. P. CO6I [MAD-22617] 394


MIRAJ ( S.
B.
SHINTRE )
To send an email from your application, you don‟t have to implement an email client from the
beginning, but you can use an existing one like the default Email app provided from Android,
Gmail, Outlook, K-9 Mail etc. For this purpose, we need to write an Activity that launches an
email client, using an implicit Intent with the right action and data. In this example, we are
going to send an email from our app by using an Intent object that launches existing email
clients.
Following section explains different parts of our Intent object required to send an email.

Intent Object - Action to send Email


You will use ACTION_SEND action to launch an email client installed on your Android
device. Following is simple syntax to create an intent with ACTION_SEND action.
Intent emailIntent = new Intent(Intent.ACTION_SEND);

Intent Object - Data/Type to send Email


Sr.No. Extra Data & Description

1
EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.

2
EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.

3
EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.

4
EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with ACTION_SEND to supply an alternative to
EXTRA_TEXT as HTML formatted text.

5
EXTRA_SUBJECT
A constant string holding the desired subject line of a message.

G. P. CO6I [MAD-22617] 395


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 396
MIRAJ ( S.
B.
SHINTRE )
6
EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with ACTION_SEND to supply the literal
data to be sent.
7
EXTRA_TITLE
A CharSequence dialog title to provide to the user when used with a ACTION_CHOOSER

To send an email you need to specify mailto: as URI using setData() method and data type will be
to text/plain using setType() method as follows −
emailIntent.setData(Uri.parse("mailto:")); emailIntent.setType("text/plain");

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 397


Intent Object - Extra to send Email
Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be
attached to the intent before sending the intent to a target email client. You can use
following extra fields in your email

For below example code is present in folder email refer all files

G. P. CO6I [MAD-22617] 398


MIRAJ ( S.
B.
SHINTRE )
By Intent
You can use Android Intent to send SMS by calling built -in SMS functionality of the
Android. Following section explains different parts of our Intent object required to
send an SMS.
Intent Object - Action to send SMS
You will use ACTION_VIEW action to launch an SMS client installed on your
Android device. Following is simple syntax to create an intent with
ACTION_VIEW action.
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
Intent Object - Data/Type to send SMS
To send an SMS you need to specify smsto: as URI using setData() method and data
type will be tovnd.android-dir/mms-smsusing setType() method as follows −

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");

Intent Object - Extra to send SMS


Android has built-in support to add phone number and text message to send an SMS as follows

smsIntent.putExtra("address" , new
String("0123456789;3393993300")); smsIntent.putExtra("sms_body" , "Test
SMS to Angilla");

G. P. CO6I [MAD-22617] 399


MIRAJ ( S.
B.
SHINTRE )
To send or receive mail

What is Email?
• Email is messages distributed by electronic means from one system user to one or more recipients via a
network.
• Intent is carrying data from one component to another component with-in the application or outside
• the application.

• Send an email from your application, you don’t have to implement an email client from the starting
,butyoucanuseanexistingone likethedefaultEmailappproviding from Android, Gmail, Outlooketc.
• For this purpose, we need to write an Activity that launches an email client, using an implicit Intent
with the right action and data.
• To send an email from our app by using an Intent object that launches existing email clients.

G. P. CO6I [MAD-22617] 400


MIRAJ ( S.
B.
SHINTRE )
• EXTRA_EMAIL :
▪ A string array of all "To" recipient email addresses

• EXTRA_SUBJECT
▪ A constant string holding the desired subject line of a message.

• EXTRA_TEXT
▪ A constant CharSequence that is associated with the Intent, used with ACTION_SEND to
supply the literal data to be sent.

• ACTION_SEND :
o TheuserchoosefromseveralActivities,evenifyousetType(“text/plain"), becausethatApp/Activities
can manage all file types and so even email message files. The solution is in the setSelector method
• setType :
▪ setType(String mimeType) input param is represent the MIME type datathat uwant to get in
return from firing intent.

▪ By using one of following MIME type you can force user to pick option which you desire.
Please take a Note here, All MIME types in android are in lowercase.

 setType :

➢ .xml -> text / xml


➢ .txt -> text / html
➢ .html -> text / html
➢ .pdf -> application/pdf

G. P. CO6I [MAD-22617] 401


MIRAJ ( S.
B.
SHINTRE )
Android Google Maps
Android provides facility to integrate Google map in our application. Google map
displays your current location, navigate location direction, search location etc. We can also
customize Google map according to our requirement.
• Types of GoogleMaps
1. Normal:Thistypeofmapdisplaystypicalroadmap,naturalfeatures like river and
some features build by humans.
2. Hybrid:This type of map displays satellite photograph data with typical road
maps. It also displays road and feature labels.
3. Satellite: Satellite type displays satellite photograph data, but doesn't display
road and feature labels.
4. Terrain: This type displays photographic data. This includes colors, contour
lines and labels and perspective shading.
5. None: This type displays an empty grid with no tiles loaded.

G. P. CO6I [MAD-22617] 402


MIRAJ ( S.
B.
SHINTRE )
Google API
The Google Maps Android API consists of a core set of classes that combine to provide
mappingcapabilitiesinAndroidapplications. Thekeyelementsofamap are as follows:
• GoogleMap – The main class of the Google Maps Android API. This class is
responsible for downloading and displaying map tiles and for displaying and
responding to map controls. The GoogleMap object is not created directly by the
application but is instead created when MapView or MapFragment instances are
created. A reference to the GoogleMap object can be obtained within application
code via a call to the getMap() method of a MapView, MapFragment or
SupportMapFragment instance.
• MapView - A subclass of the View class, this class provides the view canvas onto
whichthemapisdrawnbytheGoogleMapobject,allowingamaptobe placed in the
user interface layout of an activity.
• SupportMapFragment – A subclass of the Fragment class, this class allows a mapto
beplaced withina Fragment in an Android layout.
• Marker – The purpose of the Marker class is to allow locations to be marked on a map.
Markers are added toa map by obtaining areference to the GoogleMap object
associated with a map and then making a call to the addMarker () method of that
object instance. The position of a marker is defined via Longitude and Latitude.
Markerscanbeconfiguredinanumber of ways,including specifyingatitle,text and
an icon. Markers may also be made to be “draggable”, allowing the user to move the marker
to different positions on a map.
• Shapes –The drawing of lines and shapes on a map is achieved through the use of
the Polyline, Polygon and Circle classes.
• UiSettings –The UiSettings class provides a level of control from within an application
of which user interface controls appear on a map. Using this class, for example, the
application can control whether or not the zoom, current location and compass
controls appear on a map.
Displaying the Map

G. P. CO6I [MAD-22617] 403


MIRAJ ( S.
B.
SHINTRE )
To get hold of the GoogleMap object in our MainActivity class we need to
implement the OnMapReadyCallback interface and override the
onMapReadycallback method.
• Syntax of different types of map
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Methods Description

addCircle(CircleOptions options) This method add circle to map.

addPolygon(PolygonOptionsoptions) This method add polygon to map.

addTileOverlay(TileOverlayOptions options) Thismethod addtile overlaytothemap.

animateCamera(CameraUpdate update) This method moves the map according to the


update with an animation.

clear() Thismethodremoveseverythingfromthe map.

getMyLocation() Thismethodreturnsthecurrently displayed user


location.

moveCamera(CameraUpdate update) This method reposition the camera


according to the instructions defined in the
update.

G. P. CO6I [MAD-22617] 404


MIRAJ ( S.
B.
SHINTRE )
setTrafficEnabled(boolean enabled) Thismethodsetthetrafficlayeronoroff.

snapshot(GoogleMap.SnapshotReadyCallback Thismethodtakesasnapshotofthemap.
callback)

stopAnimation() This method stops the camera animation if there


is anyprogress.

Step: Now open google_maps_api.xml (debug) in values folder

G. P. CO6I [MAD-22617] 405


MIRAJ ( S.
B.
SHINTRE )
Step : Now open activity_maps.xml and add a fragment code in it

• Here add a fragment element to the activity‟s layout file to define a Fragment
object. In this element, set the android:name attribute to
“com.google.android.gms.maps.MapFragment”. This automatically attaches a
MapFragmenttotheactivity.Thefollowinglayoutfilecontains a fragmentelement:
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.abhiandroid.GoogleMaps.googlemaps.MapsActivity"/>

G. P. CO6I [MAD-22617] 406


MIRAJ ( S.
B.
SHINTRE )
• INTERNET – To determine if we are connected to Internet or not.
ACCESS_FINE_LOCATION – To determine user‟s location using GPS. It will give us
precise location.

<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
Step :Now we will code MapsActivity.java file for inserting callbacks in Google Maps
• -OnMapReadyCallback:
• Thiscallback iscalled whenthemapis readytobe used
@Override
public void onMapReady(GoogleMap googleMap) { }
This callback is called whenever device is connected and disconnected and
implement onConnected() and onConnectionSuspended() functions.
//When the connect request has successfully completed @Override public
voidonConnected(Bundle bundle){ }

//Called when the client is temporarily in a disconnected state.@Override publicvoid


onConnectionSuspended(int i) { }

G. P. CO6I [MAD-22617] 407


MIRAJ ( S.
B.
SHINTRE )
Displaying zoom control
You can also enable or disable the zoom gestures in the map by calling the
setZoomControlsEnabled(boolean) method.
UiSettings class- Settings for the user interface of a GoogleMap. To obtain this interface,
call getUiSettings().

UiSettings uiSettings = map.getUiSettings();


uiSettings.setZoomGesturesEnabled(true);

Or

G. P. CO6I [MAD-22617] 408


MIRAJ ( S.
B.
SHINTRE )
map.getUiSettings().setZoomGesturesEnabled(true);

G. P. CO6I [MAD-22617] 409


MIRAJ ( S.
B.
SHINTRE )
You can place a maker with some text over it displaying your location on the map. Itcanbe
donebyviaaddMarker() method.Itssyntax isgivenbelow−
final LatLng TutorialsPoint = new LatLng(21 , 57);
Marker TP = googleMap.addMarker(new MarkerOptions()
.position(TutorialsPoint).title("TutorialsPoint"));

Geocoder and ReverseGeoCoder

A class for handling geocoding and reverse geocoding. Geocoding is the process of
transforming a street address or other description of a location into a (latitude, longitude)
coordinate. Reverse geocoding is the process of transforming a (latitude, longitude)
coordinate into a (partial) address. The amount of detail in a reverse geocoded location
description may vary, for example one might contain the full street address of the closest
building,whileanothermightcontainonlyacityname and postal code
Geocoder
Android Geocoder class is used for Geocoding as well as Reverse Geocoding.
Geocoding refers to transforming street address or any address into latitude and longitude.
Reverse Geocoding refers to transforming latitude and longitude into its corresponding
street address.
Address class helps in fetching the street address, locality, sub-locality, city, country, landmark
etc. features of the location.

G. P. CO6I [MAD-22617] 410


MIRAJ ( S.
B.
SHINTRE )
Geocoding is the process of converting addresses (like a street address) into
geographic coordinates (like latitude and longitude), which you can use to place markers
on a map, or position the map.
Reverse geocoding is the process of converting geographic coordinates into a human-
readable address.
Geocoding
Geocoding is the process of converting the addresses (postal address) into geo
coordinates as latitude and longitude. Reverse geocoding is converting a geo coordinate
latitude and longitude to an address. In this tutorial we will be doing reverse geo coding
and get the addresses ofthepassed coordinates.

Methods of Geocoder class


1. List<Address> getFromLocation(double latitude, double longitude, int maxResults):-
This method returns an array of Address which specifies the surrounding latitude and
longitude.
2. List<Address> getFromLocationName(String location, int results, double leftLatitude,
double leftLongitude, double rightLatitude, double rightLongitude):- This method
returns an array of Address which describes the given location such as place, an

G. P. CO6I [MAD-22617] 411


MIRAJ ( S.
B.
SHINTRE )
address, etc.

G. P. CO6I [MAD-22617] 412


MIRAJ ( S.
B.
SHINTRE )
3. List<Address> getFromLocationName(String location, int results): This method returns
an array of Address which describes te given location such as place, an address, etc.
4. static boolean isPresent(): This method returns true if the methods
getFromLocation()andgetFromLocationName() areimplemented.
Location class Methods
Aclass representingan Address, i.e, asetof Strings describingalocation. Methods
of Android.Location.addressclass-
• public String getCountryCode ()- Returns thecountry code ofthe address, for example
"US", or null if it is unknown.

• public StringgetCountryName ()-Returnsthelocalizedcountry nameofthe address,


for example "Iceland", or null if it is unknown.

• publicdoublegetLatitude()-Returnsthelatitudeofthe addressifknown

• public String getLocality ()-Returns the locality of the address, for example
"Mountain View", or null if it is unknown.

• publicdoublegetLongitude()-Returnsthelongitudeoftheaddressifknown.
• public String getPhone ()- Returns the phone number of the address if known, or null if
it is unknown.
• public String getPostalCode ()Returns the postal code of the address, for
example "94110", or null if it is unknown.
• publicStringgetPremises()Returnsthepremisesoftheaddress,ornullifitis unknown.
• publicbooleanhasLatitude()-Returnstrueifalatitudehasbeenassignedto this
Address, falseotherwise.

G. P. CO6I [MAD-22617] 413


MIRAJ ( S.
B.
SHINTRE )
• public boolean hasLongitude ()-Returns true if a longitude has been assigned to this
Address, false otherwise.
• 11.public void setAddressLine (int index, String line)- Sets the line ofthe address
numberedbyindex(startingat0)tothegivenString,whichmaybe null.
• public void setCountryCode (String countryCode)- Sets the country code of the
address to the given String, which may be null.
• public void setCountryName (String countryName)- Sets the country name of the
address to the given String, which may be null.
• public void setLatitude (double latitude)- Sets the latitude associated with this address.
• public void setLocality (String locality)- Sets the locality of the address to the given
String, which may be null.
• public void setLongitude (double longitude)-Sets the longitude associated with this
address.
• public void setPhone (String phone)-Sets the phone number associated with this
address.
• public void setPostalCode (String postalCode)-Sets the postal code of the address
to the given String, which may be null.
• public void setPremises (String premises)-Sets the premises of the address to the
given String, which may be null.

G. P. CO6I [MAD-22617] 414


MIRAJ ( S.
B.
SHINTRE )
Android Reverse Geocoding Step1:
Define Permissions
We need location access permission to find the latitude and longitude of the Android device.
Followingtwolines are the keytogive permission to access the location.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<uses-permission android:name="android.permission.INTERNET" />

XML Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.javapapers.com.androidgeocodelocation" >

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<uses-permission android:name="android.permission.INTERNET"/>

<application android:allowBackup="true"
android:icon="@drawable/ic_launcher" android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name=".MyActivity"
android:label="@string/app_name" >
<intent-filter>

G. P. CO6I [MAD-22617] 415


MIRAJ ( S.
B.
SHINTRE )
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>

</manifest>
Step 2: Accessing the Geo Location for Lat and Long
Following class is the key element in accessing the latitude and longitude of the Android
device.It implementsthe LocationListener andgets thelocationcoordinate updates.Wehave
designed our requirement not to be a continous update for location. On demand we will get the
location coordinates.

Step 3: Reverse Geocoding to get Location Address


Following class isthe key element for reverse geocoding to get the address for the passed
latitude and longitude coordinates. We access the Geocoder Google API for reverse
geocodingandgeteverylineofaddresslikestreet,city,pin/zipcodeand etc.
LocationAddress.java
package android.javapapers.com.androidgeocodelocation;

import android.content.Context; import


android.location.Address; import
android.location.Geocoder; import
android.os.Bundle;
import android.os.Handler;

G. P. CO6I [MAD-22617] 416


MIRAJ ( S.
B.
SHINTRE )
import android.os.Message; import
android.util.Log;

import java.io.IOException; import


java.util.List;
import java.util.Locale;

public class LocationAddress {


private static final String TAG ="LocationAddress";

public static void getAddressFromLocation(final double latitude, final double longitude,


final Contextcontext,finalHandlerhandler) {
Thread thread = new Thread() {
@Override
public void run(){
Geocoder geocoder = new Geocoder(context, Locale.getDefault()); String result
= null;
try {
List<Address> addressList = geocoder.getFromLocation( latitude,
longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb=newStringBuilder();
for (int i=0; i< address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");

G. P. CO6I [MAD-22617] 417


MIRAJ ( S.
B.
SHINTRE )
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
result = sb.toString();
}
} catch (IOException e){
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message = Message.obtain();
message.setTarget(handler); if
(result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result="Latitude:"+latitude+"Longitude:" +longitude+
"\n\nAddress:\n" + result;
bundle.putString("address", result); message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result="Latitude:"+latitude+"Longitude: "+longitude+ "\n Unable
to get address for this lat-long.";
bundle.putString("address", result); message.setData(bundle);

G. P. CO6I [MAD-22617] 418


MIRAJ ( S.
B.
SHINTRE )
}
message.sendToTarget();
}
}
};
thread.start();
}
}
Step 4: AndroidUI
How these pieces fit together is with the following Android activity.
MyActivity.java
package android.javapapers.com.androidgeocodelocation;

import android.app.Activity;import
android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler; import
android.os.Message; import
android.provider.Settings; import
android.view.View; import
android.widget.Button;

G. P. CO6I [MAD-22617] 419


MIRAJ ( S.
B.
SHINTRE )
import android.widget.TextView;

public class MyActivity extends Activity {

Button btnGPSShowLocation; Button


btnShowAddress; TextView
tvAddress;

AppLocationService appLocationService;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
tvAddress =(TextView)findViewById(R.id.tvAddress);
appLocationService = new AppLocationService(
MyActivity.this);

btnGPSShowLocation= (Button) findViewById(R.id.btnGPSShowLocation);


btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Location gpsLocation =appLocationService
.getLocation(LocationManager.GPS_PROVIDER); if
(gpsLocation != null) {

G. P. CO6I [MAD-22617] 420


MIRAJ ( S.
B.
SHINTRE )
double latitude = gpsLocation.getLatitude(); double
longitude =gpsLocation.getLongitude();
Stringresult="Latitude:"+gpsLocation.getLatitude()+ "
Longitude: " + gpsLocation.getLongitude();
tvAddress.setText(result);
} else {
showSettingsAlert();
}
}
});

btnShowAddress = (Button) findViewById(R.id.btnShowAddress);


btnShowAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {

Location location = appLocationService


.getLocation(LocationManager.GPS_PROVIDER);

//you can hard-code the lat & long if you have issues with getting it
//remove the below if-condition and use the following couple of lines
//double latitude = 37.422005;
//double longitude = -122.084095

if (location != null) {

G. P. CO6I [MAD-22617] 421


MIRAJ ( S.
B.
SHINTRE )
double latitude = location.getLatitude(); double
longitude =location.getLongitude();
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeocoderHandler());
} else {
showSettingsAlert();
}

}
});

public void showSettingsAlert() {


AlertDialog.Builder alertDialog =new AlertDialog.Builder(
MyActivity.this);
alertDialog.setTitle("SETTINGS");
alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { Intent
intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MyActivity.this.startActivity(intent);

G. P. CO6I [MAD-22617] 422


MIRAJ ( S.
B.
SHINTRE )
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { dialog.cancel();
}
});
alertDialog.show();
}

privateclassGeocoderHandler extendsHandler{ @Override


public void handleMessage(Message message){ String
locationAddress;
switch(message.what){case
1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address"); break;
default:
locationAddress = null;
}
tvAddress.setText(locationAddress);
}

G. P. CO6I [MAD-22617] 423


MIRAJ ( S.
B.
SHINTRE )
}
}
Android UI layout file to show the address and location
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MyActivity">

<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Location"
android:id="@+id/btnGPSShowLocation"

G. P. CO6I [MAD-22617] 424


MIRAJ ( S.
B.
SHINTRE )
android:layout_toEndOf="@+id/textView" android:layout_marginTop="53dp"
android:layout_below="@+id/textView" android:layout_alignParentStart="true" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Address"
android:id="@+id/btnShowAddress"
android:layout_toEndOf="@+id/tvAddress"
android:layout_below="@+id/btnGPSShowLocation"
android:layout_alignParentStart="true" />

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tvAddress"
android:layout_alignParentBottom="true"
android:layout_marginBottom="134dp"
android:layout_alignParentEnd="true" />

</RelativeLayout>

G. P. CO6I [MAD-22617] 425


MIRAJ ( S.
B.
SHINTRE )
Key Points forGeocoding
• Need Google API access and so remember to run in an emulator that is
configured for Google API.
• Remember to have the right permissions defined in the Mainfest.xml
• To test via an Android Emulator, we can use theDDMS andpass the latitude and
longitude using the „Emulator Control‟.

Reverse Geo Coding


Android Geocoder class is used for Geocoding as well as Reverse Geocoding.
Geocoding refers to transforming street address or any address into latitude and longitude.
Reverse Geocoding refers to transforming latitude and longitude into its corresponding
street address.

Getting the location


LocationListener &Location-
The LocationListener interface, which is part of the Android Locations API is used for
receiving notifications from the LocationManager when the location has changed. The
LocationManagerclass provides access to the systems location services.
The LocationListener class needs to implement the following methods.
• onLocationChanged(Location location) : Called when the location has changed.
• onProviderDisabled(String provider) : Called when the provider isdisabled by the
user.
• onProviderEnabled(String provider) : Called when the provider is enabled by the
user.
• onStatusChanged(String provider, int status, Bundle extras) : Called when the
provider statuschanges.

G. P. CO6I [MAD-22617] 426


MIRAJ ( S.
B.
SHINTRE )
Location -
The Locationobject represents a geographic location which can consist of a latitude,
longitude, time stamp, and other information such as bearing, altitude and velocity.
• double getLatitude()-Get the latitude, in degrees.
• double getLongitude()-Get the longitude, in degrees.
• booleanhasAltitude()-True if this location has an altitude.
• booleanhasBearing()-True if this location has a bearing.
• void reset()-Clears the contents of the location.
• void setAccuracy(float accuracy)-Set the estimated accuracy of this location,
meters.
• voidsetAltitude(doublealtitude)-Setthealtitude,inmetersabovesealevel. Retriving the
location
• voidsetBearing(float bearing)-Set the bearing, in degrees.
• voidsetLatitude(double latitude)-Set the latitude, in degrees.
• void setLongitude(double longitude)-Set the longitude, in degrees. Access the
location
• Provide permissions for receiving location update
Toaccess current location informationthroughlocationproviders, weneed to set
permissions with android manifest file.
<manifest ... >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.
ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
• </manifest>

G. P. CO6I [MAD-22617] 427


MIRAJ ( S.
B.
SHINTRE )
ACCESS_COARSE_LOCATION is used when we use network location provider for
our Android app. But, ACCESS_FINE_LOCATION is providing permission for both
providers.INTERNETpermissionismustfortheuseofnetworkprovider.
Create LocationManager instance as reference to the location service
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
requestLocationUpdates(String provider, long minTimeMs, float minDistanceM,
LocationListenerlistener)
Register for location updates from the given provider with the given arguments.

• Request current location from LocationManager


After creating the location service reference, location updates are requested using
requestLocationUpdates() method of LocationManager. For this function, we need to send the
type of location provider, number of seconds, distance and the LocationListener object
over which the location to be updated.
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);

G. P. CO6I [MAD-22617] 428


MIRAJ ( S.
B.
SHINTRE )
La titudc: 37.422dd5, Longitude.- 1 22.084 055

G. P. MIRAJ ( S. B. SHINTRE ) CO6I [MAD-22617] 429


Monitoring the Location
Geofencing combines awareness of the user's current location with awareness of the user's
proximity to locations that may be of interest. To mark a location of interest, you specify its
latitude and longitude. To adjust the proximity for the location, you add a radius. The latitude,
longitude, and radius define a geofence, creating a circular area, or fence, around the
location ofinterest.

Set up for Geofence monitoring

The first step in requesting geofence monitoring is to request the necessary


permission. To use geofencing, your app must request
ACCESS_FINE_LOCATION.IfyourapptargetsAndroid 10(APIlevel29) or higher, your
app mustalso request ACCESS_BACKGROUND_LOCATION.
To request the necessary permissions, add them as child elements of the
<manifest> element in your app manifest:

G. P. CO6I [MAD-22617] 430


MIRAJ ( S.
B.
SHINTRE )
<!-- Required ifyour apptargets Android10 (API level 29) orhigher -->

Ifyouwanttousea BroadcastReceivertolistenforgeofencetransitions,add an element


specifyingtheservice name.Thiselementmustbeachildof
the <application> element:

Toaccessthe location APIs,you needtocreatean instanceoftheGeofencing client.


To learn how to connect your client:

G. P. CO6I [MAD-22617] 431


MIRAJ ( S.
B.
SHINTRE )
Android security model

a) Threat Model
b) Android platform securitymodel

1. Threat Model

Beyonditsauthorizations, datacanbeaccessedandoperatedthrough a Privilege


applicationbasedonthis attack Escalation -This attack istotally different within
various mobile platforms.

Mobile platforms is a targetable area to malware attacks because various mobile platforms
have powerful ability to store a large amount of data (sensitive) Malicious-Basedon
theresearchesandarticlesApplicationstherearesomeof themalwarethreatshavebeen
addressed such as by static and dynamic analysis of application binaries, enhanced
application installers, novel run-time privacy

G. P. CO6I [MAD-22617] 432


MIRAJ ( S.
B.
SHINTRE )
frameworks and app store analysis tools. - Evaluate potential privacy and security
risksRiskyIn-App-AnadvertisementlibraryisapartofAdLibraries theapps,thatthe
app developers integrate it.

2. Android Platform SecurityModel:

The Android security model is primarily based on a sandbox and permission


mechanism. Each application is running in a specific Dalvik virtual machine with a unique
user ID assigned to it, which means the application code runs in isolation from the code of all
others applications. As a consequence, one application has not granted access to other
applications‟ files.

Android application has been signed with a certificate with a private key Know the ownerof the
application is unique. This allows the author of The application will be identified ifneeded.
When an application is installed in The phone is assigned a user ID, thus avoiding it from
affectingitOtherapplicationsbycreatingasandboxforit.

G. P. CO6I [MAD-22617] 433


MIRAJ ( S.
B.
SHINTRE )
This user ID is permanent on which devices and applications with the same user ID are
allowedto run inasingle process. This is away to ensure that a malicious application
hasCannotaccess/compromisethedataofthegenuineapplication.

It is mandatory for an application to list all the resources it will Access during installation.
Terms are required of an application, in The installation process should be user-based or
interactive Checkwith thesignature oftheapplication.

The purpose of a permission is to protect the privacy of an Android user. Android apps must
request permission to access sensitive user data (such as contacts and SMS), as well as
certain system features (such as camera and internet). Depending on the feature, the system
might grant the permission automatically or might prompt the user to approve the request.

Security program overview

The key components of the Android Security Program include:

• Design review: The Android security process begins early in the development lifecycle
withthecreationofarichandconfigurablesecuritymodelanddesign.Each majorfeatureofthe
platform is reviewed by engineering and security resources, with appropriatesecurity controls
integrated into the architecture of the system.

• Penetration testing and code review: During the development of the platform, Android-
created and open source components are subject to vigorous security reviews. These
reviews are performed by the Android Security Team, Google‟s Information Security
Engineering team, and independent security consultants. The goal of these reviews is to
identify weaknesses and possible vulnerabilities well

G. P. CO6I [MAD-22617] 434


MIRAJ ( S.
B.
SHINTRE )
beforemajorreleases, andtosimulatethetypesofanalysisthatareperformedby external
security experts upon release.

• Open source and community review: AOSP enables broad security review by any interested
party. Android also uses open source technologies that have undergone significant external
security review, such as the Linux kernel. Google Play provides a forum for users and
companies to provide information about specific apps directly to users.

• Incident response: Even with these precautions, security issues may occur after shipping,
which is why the Android project has created a comprehensive security response process.
Full-time Android security team members monitor the Android- specific and the general
security community for discussion of potential vulnerabilities and review security bugs
filed on the Android bug database. Upon the discovery of legitimate issues, the Android
team has a response process that enables the rapid mitigation of vulnerabilities to ensure
that potential risk to all Android users is minimized

• Monthly security updates: The Android security team provides monthly updates to Google
Android devices and allourdevice manufacturing partners.

G. P. CO6I [MAD-22617] 435


MIRAJ ( S.
B.
SHINTRE )
API Keys

New Users: Before you can start using the Google Maps Platform APIs and SDKs, youmust
signupandcreateabillingaccount.TousethePlacesAPIyoumust haveanAPIkey.The
APIkey isaunique identifier that is used toauthenticate requestsassociatedwithyour
projectforusageandbillingpurposes.

Get the API key

You musthave atleastone API keyassociated with your project. To get

an APIkey:

1. Go to the Google Cloud Platform Console.


2. Clicktheprojectdrop-down and selectorcreatetheprojectfor whichyou wanttoaddanAPI key.

3. Clickthemenubutton and select APIs & Services > Credentials.


4. OntheCredentialspage,clickCreatecredentials>APIkey. TheAPIkey
createddialogdisplaysyournewlycreated APIkey.
5. Click Close.
Thenew APIkeyislisted onthe Credentialspageunder APIkeys.
(RemembertorestricttheAPIkeybeforeusingitinproduction.)

G. P. CO6I [MAD-22617] 436


MIRAJ ( S.
B.
SHINTRE )
Publish Your App
Publishing is thegeneral process that makes your Android applications available to users.
WhenyoupublishanAndroidapplicationyouperformtwomaintasks:
• You prepare the application for release.
During the preparation step you build a release version of your application, which users can
download and install ontheir Android-powered devices.
• You release the application to users.
During the release step you publicize, sell, and distribute the release version of your
application to users.

Documenting the process of publishing an app on the Google Play Store as I go through it
forthe first time.

Step 1: Sign up
Sign up for an account onthe Android Developer Console. Creating an account costs
$25.

Step 2: Create a newapplication


• Onthe Developer Consoleselect the Publish anAndroidApplication option.

• Fill out the details: Title, Short Description, Full Description.

G. P. CO6I [MAD-22617] 437


MIRAJ ( S.
B.
SHINTRE )
Step 3: Prepare multimedia
• Screenshots: I usedtheandroid emulatortotakescreenshots of myapp.

• Hi-res icon: I used the launcher icon. It was an SVG file, so I converted it to PNG using
GIMP.

• Featuregraphic:This isanimagethat shows uponthetopoftheappdownload page in


Google Play on mobile phones.

Step 4: Prepare code for release


• Remove log statements.
• Remove the android:debuggable attribute from your manifest file. I didn‟t have to do this
because Android Studioautomaticallysetsthis attributebasedonthe kind of APK its
building. Neat!
• Set the android:versionCode attribute in the manifest tag in manifest.xml. Two important
notes: (1) This must be an integer that increases with each release. (2) This number is not
displayed to users.
I chose “1”.

• Set the android:versionName attribute in the manifest tag in manifest.xml. This string is
shown to users and has no other purpose.
I chose “1.0”.

Step 5: Build a release-ready APK


The release-ready APK is different from the debug APK in that it is signed with certificate
that is owned by the developer. This is done to ensure that updates to the app come from a
verifiedsource,i.e.adeveloperwithaccesstotheprivatekey.

I recommend you follow the instructions here to create a signed APK.

TL;DR? Here are some important take-away points:

• Android Studio -> Build -> Generate Signed APK

• A Java Keystore (JKS) is a repository of public -private key pairs.

G. P. CO6I [MAD-22617] 438


MIRAJ ( S.
B.
SHINTRE )
• You must sign all APKs with the same key pair.

• Losing a key-pair consequences that you will not be able to push updates to your app.

Step 6: Upload APK


Go back to theDeveloper Consoleandclick onManage Releases. Then create a
Production Release and upload your signed APK.

Google will perform acheck onthe APK. My appwas using an SVG forthe launcher icon,
whichisno-bueno.IhadtochangeittoPNGandrecreatethesignedAPK.

Step 7:
Complete the checklist on the left until all the items have a green checkmark. The consolere-
evaluatesthechecklisteverytimeyouclickSaveDraftinthetopright.

You are now ready to publish :)

G. P. CO6I [MAD-22617] 439


MIRAJ ( S.
B.
SHINTRE )
Extra Examples (Related to CH:6):

Email:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#1DE9B6"
tools:context=".MainActivity">

<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:id="@+id/to"
android:hint="To"
/>
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:id="@+id/sub"
android:hint="Subject"
android:layout_marginTop="40dp"
/>
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:id="@+id/msg"
android:hint="Message"
android:layout_marginTop="40dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:layout_marginTop="50dp"
android:onClick="send"
/></LinearLayout> Java code:
package com.example.emailsend;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;

G. P. CO6I [MAD-22617] 440


MIRAJ ( S.
B.
SHINTRE )
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText e1,e2,e3;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1=findViewById(R.id.to);
e2=findViewById(R.id.sub);
e3=findViewById(R.id.msg);
}

public void send(View view) {


Intent intent=new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL,new String[]{e1.getText().toString()});
intent.putExtra(Intent.EXTRA_SUBJECT,e2.getText().toString());
intent.putExtra(Intent.EXTRA_TEXT,e3.getText().toString());
intent.setType("text/plain");
startActivity(Intent.createChooser(intent,"Select App"));
}
}

G.P.MIRAJ CO6I [MAD-22617] 441


To draw a route between two locations.
<resources>

<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">AIzaSyAn47NqVmFN-


gDDvymQLN2brbJP1AYlERk</string>
</resources>

Java code:
package com.example.exp31;

import androidx.fragment.app.FragmentActivity;

import android.graphics.Color;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import java.util.ArrayList;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

LatLng gpm = new LatLng(16.847371365859033, 74.64267602818104);


LatLng Bethesda = new LatLng(16.842463402136154, 74.64043379814368);
ArrayList<LatLng> list;
private GoogleMap mMap;
String tit[]={"GPM","Bethesda school"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
list=new ArrayList<LatLng>();
list.add(gpm);
list.add(Bethesda);
}

G. P. CO6I [MAD-22617] 442


MIRAJ ( S.
B.
SHINTRE )
@Override
public voidonMapReady(GoogleMap googleMap){
mMap = googleMap;

for (int i=0;i<list.size();i++){


mMap.addMarker(new MarkerOptions().position(list.get(i)).title(tit[i]));
mMap.moveCamera(CameraUpdateFactory.newLatLng(list.get(i)));
}
// Add a marker in Sydney and move the camera
mMap.addPolyline((new PolylineOptions().add(Bethesda,gpm).width(5).color(Color.RED).geodesic(true)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Bethesda,13));

G. P. CO6I [MAD-22617] 443


MIRAJ ( S.
B.
SHINTRE )
Send Message:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center"
android:background="#E1A6BA">
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Enter mobile
number"android:id="@+id/t1"
/>
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Enter message"
android:layout_marginTop="20dp"
android:id="@+id/t2"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send SMS"
android:onClick="send"
android:layout_marginTop="30dp"
android:background="@color/colorAccent"
android:textColor="#FFF"
/>
</LinearLayout>
• Java code-
package com.example.sms1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;

G. P. CO6I [MAD-22617] 444


MIRAJ ( S.
B.
SHINTRE )
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText t1,t2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=findViewById(R.id.t1);
t2=findViewById(R.id.t2);
}
public void send(View view) {
try {
SmsManager manager=SmsManager.getDefault();
manager.sendTextMessage(t1.getText().toString(),null,t2.getText().toString(),null,null);
Toast.makeText(this,"Message Sent",Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(this,"Cant send message",Toast.LENGTH_SHORT).show();
}
}

}
• Manifest.xml-

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sms1">
<uses-permission android:name="android.permission.SEND_SMS"/>
<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" />
</intent-filter>
</activity>
</application>

</manifest>

• Output-

G. P. CO6I [MAD-22617] 445


MIRAJ ( S.
B.
SHINTRE )
Map:
• Xml code-
<resources>
<string name="google_maps_key" templateMergeStrategy="preserve"
translatable="false">AIzaSyDkpRvpyHSycWv1jtcPobA20md9LOcl18I</string>
</resources>

• Java code:
package com.example.map4;

import androidx.fragment.app.FragmentActivity;

import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

G. P. CO6I [MAD-22617] 446


MIRAJ ( S.
B.
SHINTRE )
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public voidonMapReady(GoogleMap googleMap){
mMap = googleMap;

// Add a marker in Sydney and move the camera


LatLng gpm = new LatLng(16.847238, 74.642633);
mMap.addMarker(new MarkerOptions().position(gpm).title("GPMiraj"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(gpm));

}
}
• Output-

G. P. CO6I [MAD-22617] 447


MIRAJ ( S.
B.
SHINTRE )
To draw a route between two locations.

• Xml code-

<resources>

<string name="google_maps_key" templateMergeStrategy="preserve"


translatable="false">AIzaSyDkpRvpyHSycWv1jtcPobA20md9LOcl18I</string>
</resources>

• Java code-

package com.example.map2;
import androidx.fragment.app.FragmentActivity;
import android.graphics.Color;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import java.util.ArrayList;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {


LatLng gpm = new LatLng(16.847238, 74.642633);
LatLng talav = new LatLng(16.829939, 74.649439);
ArrayList<LatLng> list;
private GoogleMap mMap;
String tit[]={"GPM","Ganesh Talav"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
list=new ArrayList<LatLng>();
list.add(gpm);
list.add(talav);
}

G. P. CO6I [MAD-22617] 448


MIRAJ ( S.
B.
SHINTRE )
@Override
public voidonMapReady(GoogleMap googleMap){
mMap = googleMap;

for (int i=0;i<list.size();i++){


mMap.addMarker(new MarkerOptions().position(list.get(i)).title(tit[i]));
mMap.moveCamera(CameraUpdateFactory.newLatLng(list.get(i)));
}
// Add a marker in Sydney and move the camera
mMap.addPolyline((new PolylineOptions().add(talav,gpm).width(5).color(Color.RED).geodesic(true)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(talav,13));

• Output-

***

G. P. CO6I [MAD-22617] 449


MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 450
MIRAJ ( S.
B.
SHINTRE )

You might also like