0% found this document useful (0 votes)
43 views174 pages

ch1 9

Uploaded by

caught0you
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views174 pages

ch1 9

Uploaded by

caught0you
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 174

Unit 1 Introduction of Android

1. Android Operating System

2. History of Mobile Software Development

3. Open Handset Alliance (OHA)

4. The Android Platform

5. Installation

6. Android SDK

7. Command Line Tools and the Android Emulator

8. Application Context

9. Application Tasks

1. Android Operating System

Android is an operating system developed by Google for mobile systems. It is based on the
Linux kernel and mainly designed for touchscreen devices such as tablets and smartphones. The
Android architecture is divided into four main layers and five sections. This is explained using
the given diagram –

The Android - Operating System

o Android is an Operating System. o It is not a


hardware platform. o Android includes a Linux
kernel-based OS. o Android OS are written in
C or C++. o We can develop User applications
using JAVA.
o It is called as APK (Android Application
Package).

Unit-1 Introduction of Android Page 1


• Android is released under two different open source licenses.
• The Linux kernel is released under the GPL (GNU General Public License), as is
required for anyone licensing the open source OS kernel.
• The Android platform, excluding the kernel, is licensed under the Apache Software
License (ASL).
• While both licensing models are open source–oriented. Let's See Android versions...

Android Architecture:-

Unit-1 Introduction of Android Page 2


The architecture of an Android system consist of a software stack of different layers. Each
layer contains a group of various program components.

Linux Kernel:-

It is the chief component in the android architecture. The interaction of the hardware with the
software is provided by means of Linux. All the hardware drivers are handled by this kernel.
Drivers are the small programs written specifically to communicate with the hardware. The
lowest layer is the linux kernel,which is the closets to the hardware. It has all the major
hardware drivers such as display driver,camera driver,power management driver, and so forth.

Example, the linux kernel has the camera driver. On installing the android os in a compatible
devices, the linux kernel will search the camera and then make it available to the system by
using camera driver.

Libraries:-

The layer next to the linux kernel layer is the android’s native libraries. This layer provides the
device,which has the capability to handle different types of data and information. This libraries
are coded in C and C++ languages for fast procedural transactions of data. A brief description
of some of the native android libraries is as follows:

1.WebKit:- Refers to the browser engine used to render and display HyperTextMarkup
Language(HTML) content.

2. Media Framework:- Refers to a library that handles the entire multi media feature by
deploying media codecs.
Unit-1 Introduction of Android Page 3
3.Surface Manager:-Refers to the Manipulations Performed on the screen of the device. To do
so , Window Manager is combine with of screen buffering.

4.SQLite :- Refers to the Database engine Used in Android for Data Storage purposes.

5. OpenGL:-Refers to as a Rendering engine, which is used to render Graphics to the screen.


Android Runtime:-

Dalvik virtual machine and the Core Java Libraries are the part of Android Runtime
Environment. For Those who are familier with Java may realise that there is no Java Virtual
Machine(JVM). In android runtime, Dlavik virtual Machine is present instead of JVM. Dalvik
is a specialized virtual machine designed specifically for Android and optimized for
batterypowered mobile devices with limited memory and CPU.

Dalvik Virtual Machine:-

It is used in Android system similar to the usage of JVMin Java. However, Dlavik Virtual
Machine is optimized for Low-Power Centeral Processing Unit(CPUs). And Low memory
modules. Unlike the JVM, the Dalvik Virtual Machine does not Recognise files with the .class
extension ;instead, it executes the files with the .dex extension. Infact, .dex files are generated
implicitly from the .class file and are highly optimized where memory and processing power
are constraints.

Advantages:

• It is optimised for small platform where memory and processing power are
constraints.
• It recognizes its exclusively designed APIs along with some useful APIs of Java.
• At Times, many instances can be created simultaneously,giving benefit in the security,
isolation, memory management and multi threading.

Core Java Libraries:-

These are the exclusively designed Java libraries for Android rather than Java SE and Java ME
libraries.However, most of the functionality of these libraries is similar to the java SE libraries.

Application Framework:-

Application framework is of utmost importance for developer as the blocks inside this layer
directly communication with Android applications. The basic and much needed functionalities
such as resource management and voice call management are provided by this layer.

Blocks

Activity Manager:- Manages the activity life cycle of applications.

Content Providers:-provide data sharing between applications.

Telephony Manager:- Manages all Voice calls. This management can be considered as optional.
If your application is meant to use the voice calls,then telephony manager is used.

Location Manager:-Manages the activities related with location in your application.


Unit-1 Introduction of Android Page 4
Resource Manager:- Manages the different kinds of resources in an application.
Application

It is the Top layer in the android artictecture.This is the place where your application is finally
deployed over a device. Some applications are installed by default in a device, such as SMS
client app,dialer,Web browser, and contact manager.

Application Component

Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that
describes each component of the application and how they interact.

There are following four main components that can be used within an Android application −
Sr.No Components & Description

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

Services
They handle background processing associated with an application.

Broadcast Receivers
They handle communication between Android OS and applications.

Content Providers
They handle data and database management issues.

1.Activities
An activity represents a single screen with a user interface,in-short Activity performs actions
on the screen. For example, an email application might have one activity that shows a list of
new emails, another activity to compose an email, and another activity for reading emails. If an
application has more than one activity, then one of them should be marked as the activity that
is presented when the application is launched.

Unit-1 Introduction of Android Page 5


An activity is implemented as a subclass of Activity class as follows −

public class MainActivity extends Activity { }

2.Services
A service is a component that runs in the background to perform long-running operations. For
example, a service might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking user interaction with an
activity.
A service is implemented as a subclass of Service class as follows −

public class MyService extends Service { }

3.Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from the
system. For example, applications can also initiate broadcasts to let other applications know
that some data has been downloaded to the device and is available for them to use, so this is
broadcast receiver who will intercept this communication and will initiate appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcaster as an Intent object.

public class MyReceiver extends BroadcastReceiver {


public void onReceive(context,intent){} }

4.Content Providers
A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. The data may be stored in
the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must implement
a standard set of APIs that enable other applications to perform transactions.

public class MyContentProvider extends ContentProvider {


public void onCreate(){} }
We will go through these tags in detail while covering application components in individual
chapters.

Additional Components
There are additional components which will be used in the construction of above mentioned
entities, their logic, and wiring between them. These components are −
S.No Components & Description

Unit-1 Introduction of Android Page 6


1

Fragments
Represents a portion of user interface in an Activity.

Views
UI elements that are drawn on-screen including buttons, lists forms etc.

Layouts

View hierarchies that control screen format and appearance of the views.

Intents
Messages wiring components together.

Resources
External elements, such as strings, constants and drawable pictures.

Manifest
Configuration file for the application.

Features of Android Operating System


The unique features/characteristics of the android operating system include the following.
• Near Field Communication (NFC)
• Alternate Keyboards
• IR Transmission

Unit-1 Introduction of Android Page 7


• No-Touch Control
• Automation
• Wireless App Downloads
• Storage & Battery Swap
• Custom Home Screen
• Widgets
• Custom ROMs
• Headset layout
• Storage
• Connectivity: GSM/EDGE, IDEN, CDMA, Bluetooth, WI-FI, EDGE,3G,NFC, LTE,GPS.
• Messaging: SMS, MMS, C2DM (could to device messaging), GCM (Google could
messaging)
• Multilanguage support
• Multi-touch
• Video calling
• Screen capture
• External storage
• Streaming media support
• Optimized graphics

What is a Mobile Application?


A mobile application (or mobile app) is a software application designed to run on smartphones,
tablet computers and other mobile devices.
The history of the mobile app begins, obviously, with the history of the mobile device and
the first mobile phones whose microchips required the most basic of software to send and
receive voice calls. But since then, things have got a lot more complicated.
Where did it all begin?
The first public cellular phone call was made by Martin Cooper of Motorola on 3rd April
1973 in a publicity stunt in New York. There would be another ten years of R&D however
before the first cell phone would hit the market. The DynaTAC 8000X weighed in at around
2 pounds, cost $4,000 and didn’t run any apps.

Psion
EPOC

The first recognisable apps came with Psion’s range of


handheld computers – mostly PDAs – that used the EPOC operating system. First released in
the early 90s the sixteen-bit machines (SIBO) which ran EPOC allowed users programmes such
as a word processor, database, spreadsheet and diary. Later models in the range, running a 32-
bit OS, would come with up to 2MB RAM and allow users to add additional apps via software
packs (or via download if you were lucky enough to own a modem).

Unit-1 Introduction of Android Page 8


EPOC, which was programmed in OPL (Open Programming Language) and allowed users to create
their own apps, would later form the backbone of the Symbian operating system.

Palm OS

Palm emerged as a major rival to Psion in the PDA market with its cheaper, lower functionality
range of PDAs – the Palm Pilot. Commercial success allowed Palm to release a new generation
of machines in 1996 which utilised the Palm OS. This had a touchscreen GUI and came with a
raft of basic apps as well as tons of third-party apps programmed in C/C++.
From Palm OS 3.0 onwards these included a WAP browser.
Following the acquisition of PalmSource by ACCESS, Palm OS became the ACCESS Linux
Platform before being abandoned in favour of webOS (which is now used in LG’s smart TVs).
Symbian

As mentioned earlier, Symbian grew out of the Psion EPOC operating system. Originally
developed by Symbian Ltd – a joint venture of Psion, Ericsson, Motorola and Nokia – the
operating system was almost ubiquitous. In 2009 250 million devices were running Symbian.

It was Nokia that really drove the development of Symbian OS. The S60 platform was
used on nearly all Nokia handsets as well as some Samsung and LG ones. The use of
different, fragmented platforms (Sony Ericsson and Motorola used UIQ and there was
MOAP(S) for NTT DoCoMo), each with its own API, meant that there were a variety of
deployment techniques and no standard market place for apps.
The incompatibility of apps across platforms and the failure to fully move to open source
(several key components were licensed from third parties) are probably what sounded the death-

Unit-1 Introduction of Android Page 9


knell for Symbian. There were also problems with malware, a browser which didn’t support
multiple windows or compress pages and a nightmare process for typing in nonLatin text.
A market share of 37.6% in 2010 had dropped to 4.4% in 2012 after Nokia jumped ship for the
Windows Phone platform and other OEMs gathered beneath the banner of Android with its
single, unified market place for apps.
The last Symbian smartphone, the Nokia 808 PureView ran the Nokia Belle update which used
C++. It was an award-winning phone (chiefly because of its 41-megapixel camera) but wasn’t
enough to prolong Nokia’s heyday.

Open Handset Alliance (OHA)


What does Open Handset Alliance (OHA) mean?
The Open Handset Alliance (OHA) is a business alliance that was created for the purpose of
developing open mobile device standards. The OHA has approximately 80 member companies,
including HTC, Dell, Intel, Motorola, Qualcomm and Google. The OHA's main product is the
Android platform - the world's most popular smartphone platform.
OHA members are primarily mobile operators, handset manufacturers, software development
firms, semiconductor companies and commercialization companies. Members share a commitment
to expanding the commercial viability of open platform development.

OHA member companies back the open platform concept for a number of reasons, as follows:

Unit-1 Introduction of Android Page 10


Lower overall handset costs: Opens up resources, which facilitates the focus
on creating innovative applications, solutions and services.

Unit-1 Introduction of Android 11


Page
Developer-friendly environment: In the open-source community, developers share
notes to expedite application development.

Post-development: Provides an ideal channel for application marketing and distribution.

The Android Platform


The Android platform is a platform for mobile devices that uses a modified Linux kernel. The Android
Platform was introduced by the Open Handset Alliance in November of 2007. Most applications that
run on the Android platform are written in the Java programming language.

The Android Platform was launched in 2007 by the Open Handset Alliance, an alliance of
prominent companies that includes Google, HTC, Motorola, Texas Instruments and others.
Although most of the applications that run on the Android Platform are written in Java, there
is no Java Virtual Machine. Instead, the Java classes are first compiled into what are known as
Dalvik Executables and run on the Dalvik Virtual Machine (DVM).

Android is an open development platform. However, it is not open in the sense that everyone
can contribute while a version is under development. This is all done behind closed-doors at
Google. Rather, the openness of Android starts when its source code is released to the public
after it is finalized. This means once it is released anyone interested can take the code and
alter it as they see fit.

To create an application for the platform, a developer requires the Android SDK, which
includes tools and APIs. To shorten development time, Android developers typically integrate
the SDK into graphical user IDEs (Integrated Development Environments). Beginners can
also make use of the App Inventor, an application for creating Android apps that can be
accessed online.

Android SDK
The Android SDK (Software Development Kit) is a set of development tools used to develop
applications for the Android platform that has become Apple’s biggest rival in the smartphone
space. The Android SDK includes the following:
Required libraries.
Debugger.
An emulator.
Relevant documentation for the Android Application Program Interfaces (APIs).
Sample source code.
Every time Google releases a new version of Android, a corresponding SDK is also released. To
be able to write programs with the latest features, developers must download and install each
version’s SDK for the particular phone. The SDK essentially represents Android’s delivered
toolkit for a specific version and technology of its operating systems.
The development platforms that are compatible with SDK include operating systems like
Windows (XP or later), Linux (any recent Linux distribution) and Mac OS X (10.4.9 or later).
The components of Android SDK can be downloaded separately. Third-party addons are also
available for download.
Although the SDK can be used to write Android programs in the command prompt, the most
common method is by using an integrated development environment (IDE).
The recommended IDE is Eclipse with the Android Development Tools (ADT) plug-in. However,
other IDEs, such as NetBeans or IntelliJ, will also work.
Most of these IDEs provide a graphical interface enabling developers to perform development
tasks faster. Since Android applications are written in Java code, a user should have the Java
Development Kit (JDK) installed.

Command Line Tools and the Android Emulator


The Android SDK is composed of multiple packages that are required for app development.
This page lists the most important command line tools that are available, organized by the
packages in which they're delivered.
You can install and update each package using Android Studio's SDK Manager
sdkmanager or the command line tool. All of the packages are downloaded into your
directory Android SDK , which you can locate as follows:
1. In Android Studio, click File > Project Structure.
2. Select SDK Location in the left pane. The path is shown under Android SDK
location. Located in: android_sdk/cmdline-tools/version/bin/ apkanalyzer
Provides insight into the composition of your APK after the build process completes.
avdmanager

Allows you to create and manage Android Virtual Devices (AVDs) from the command
line.
lint
A code scanning tool that can help you to identify and correct problems with the structural quality
of your code.
retrace
For applications compiled by R8, retrace decodes an obfuscated stack trace that maps back
to your original source code.

sdkmanager
Allows you to view, install, update, and uninstall packages for the Android SDK.

How to Install Android SDK Tools on Windows https://android.tutorials24x7.com/blog/how-to-


install-android-sdk-tools-on-window

Android Emulator
The Android emulator is an Android Virtual Device (AVD), which represents a specific Android
device. We can use the Android emulator as a target device to execute and test our
Android application on our PC. The Android emulator provides almost all the functionality of a real
device. We can get the incoming phone calls and text messages. It also gives the location of the
device and simulates different network speeds. Android emulator simulates rotation and other
hardware sensors. It accesses the Google Play store, and much more

Testing Android applications on emulator are sometimes faster and easier than doing on a real
device. For example, we can transfer data faster to the emulator than to a real device connected
through USB.
The Android emulator comes with predefined configurations for several Android phones, Wear
OS, tablet, Android TV devices.

Requirement and recommendations


The Android emulator takes additional requirements beyond the basic system requirement for
AndroidStudio. These requirements are given below: o SDK Tools 26.1.1 or higher

o 64-bit processor o Windows: CPU with UG (unrestricted guest)


support o HAXM
6.2.1 or later (recommended HAXM 7.2.0 or later)
https://developer.android.com/studio/run/emulator
Application Context
Android apps are popular for a long time and it is evolving to a greater level as user’s
expectations are that they need to view the data that they want in an easier smoother view.
Hence, the android developers must know the important terminologies before developing the
app. In Android Programming we generally come across a word context. So what exactly is
this context and why is it so important? To answer this question lets first see what the literal
meaning of context is:

―The circumstances that form the setting for an event, statement, or idea, and in terms of which
it can be fully understood‖
In android, context is the main important concept and the wrong usage of it leads to memory
leakage. Activity refers to an individual screen and Application refers to the whole app
and both extend the context class.

Types of Context in Android


There are mainly two types of context are available in Android.
o Application Context and

o Activity Context
The Overall view of the App hierarchy looks like the following

o It can be seen in the above image that in “Sample Application”, nearest Context is
Application Context. In “Activity1” and “Activity2”, both Activity Context (Here it is
Activity1 Context for Activity1 and Activity2 Context for Activity2) and
Application Context. The nearest Context to both is their Activity Context only.
Application Context o This context is tied to the life cycle of an application. Mainly it
is an instance (object) that is a singleton and can be accessed via getApplicationContext().
Some use cases of Application Context are:
If it is necessary to create a singleton object
During the necessity of a library in an
activity o getApplicationContext():
o It is used to return the context which is linked to the Application which holds all
activities running inside it. When we call a method or a constructor, we often have to pass a
context and often we use “this” to pass the activity context or “getApplicationContext” to
pass the application context. This method is generally used for the application level and can
be used to refer to all the activities. For example, if we want to access a variable throughout
the android app, one has to use it via getApplicationContext().
Application Tasks
A task is a collection of activities that users interact with when performing a certain job. The
activities are arranged in a stack—the back stack)—in the order in which each activity is
opened. For example, an email app might have one activity to show a list of new messages.
When the user selects a message, a new activity opens to view that message. This new activity is
added to the back stack. If the user presses the Back button, that new activity is finished and
popped off the stack. The following video provides a good overview of how the back stack works.
When apps are running simultaneously in a multi-windowed environment, supported in
Android 7.0 (API level 24) and higher, the system manages tasks separately for each window;
each window may have multiple tasks. The same holds true for Android apps running on
Chromebooks: the system manages tasks, or groups of tasks, on a per-window basis.
The device Home screen is the starting place for most tasks. When the user touches an icon in
the app launcher (or a shortcut on the Home screen), that app's task comes to the foreground.
If no task exists for the app (the app has not been used recently), then a new task is created
and the "main" activity for that app opens as the root activity in the stack.
When the current activity starts another, the new activity is pushed on the top of the stackand
takes focus. The previous activity remains in the stack, but is stopped. When an activity
stops, the system retains the current state of its user interface. When the user presses
the Back button, the current activity is popped from the top of the stack (the activity
isdestroyed) and the previous activity resumes (the previous state of its UI is
restored).Activities in the stack are never rearranged, only pushed and popped from the stack—
pushedonto the stack when started by the current activity and popped off when the user leaves
it using the Back button. As such, the back stack operates as a "last in, first out" object structure.
Figure 1 visualizes this behaviour with a timeline showing the progress between
activitiesalong with the current back stack at each point in time.

Figure 1. A representation of how each new activity in a task adds an item to the back stack.
When the user presses the Back button, the current activity is destroyed and the previous
activity resumes.
If the user continues to press Back, then each activity in the stack is popped off to reveal the
previous one, until the user returns to the Home screen (or to whichever activity was running
when the task began). When all activities are removed from the stack, the task no longer
exists.
Android Activity Lifecycle

Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android


Activity is the subclass of ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of Java.By the help of
activity, you can place all your UI components or widgets in a single screen.The 7 lifecycle
method of Activity describes how activity will behave at different states. Android Activity
Lifecycle methods

Let's see the 7 lifecycle methods of android activity.


1. onCreate()
It is called when the activity is first created. This is where all the static work is done like creating
views, binding data to lists, etc. This method also provides a Bundle containing its previous
frozen state, if there was one.
2. onStart()
It is invoked when the activity is visible to the user. It is followed by onResume() if the
activity is invoked from the background. It is also invoked after onCreate() when the activity
is first started.
3. onRestart()
It is invoked after the activity has been stopped and prior to its starting stage and thus is
always followed by onStart() when any activity is revived from background to on-screen.
4. onResume()
It is invoked when the activity starts interacting with the user. At this point, the activity is at
the top of the activity stack, with a user interacting with it. Always followed by onPause()
when the activity goes into the background or is closed by the user.
5. onPause()
It is invoked when an activity is going into the background but has not yet been killed. It is a
counterpart to onResume(). When an activity is launched in front of another activity, this
callback will be invoked on the top activity (currently on screen). The activity, under the
active activity, will not be created until the active activity’s onPause() returns, so it is
recommended that heavy processing should not be done in this part.
6. onStop()
It is invoked when the activity is not visible to the user. It is followed by onRestart() when the
activity is revoked from the background, followed by onDestroy() when the activity is closed
or finished, and nothing when the activity remains on the background only. Note that this
method may never be called, in low memory situations where the system does not have
enough memory to keep the activity’s process running after its onPause() method is called.

7. onDestroy()
The final call received before the activity is destroyed. This can happen either because the
activity is finishing (when finish() is invoked) or because the system is temporarily destroying
this instance of the activity to save space. To distinguish between these scenarios, check it
with isFinishing() method.
Unit 2 Android Application Design and Resource

2.1 Anatomy of an Android Application(Android Application Components), Android Manifest


File

2.2 Managing Application’s Identity, Enforcing Application System Requirements,


Registering Application’s Activities and other Application Components, Working with
Permissions.

2.1 Anatomy of an Android Application


Android applications are created by bringing together one or more components known as Activities.
An activity is a single, standalone module of application functionality that usually correlates directly
to a single user interface screen and its corresponding functionality.
Starting from a user clicking on the App icon to launch the app, to the user exiting from the App,
there are certain defined states that the App is in, let's see what they are.

1. When a user clicks on the App icon, the Main Activity gets started and it creates the App's
User Interface using the layout XMLs. And the App or Activity starts running and it is said to
be in ACTIVE state.
2. When any dialog box appears on the screen, like when you press exit on some apps, it
shows a box confirming whether you want to exit or not. At that point of time, we are not
able to interact with the App's UI until we deal with that dialog box/popup. In such a
situation, the Activity is said to be in PAUSED state.
3. When we press the Home button while using the app, our app doesn't closes. It just get
minimized. This state of the App is said to be STOPPED state.
4. When we finally destroy the App i.e., when we completely close it, then it is said to be in
DESTROYED state.
Hence, all in all there are four states of an Activity (App) in Android namely,
Active, Paused, Stopped and Destroyed.

There are four building blocks to an Android application:

1. Activity
2. Intent Receiver
3. Service
4. Content Provider
Not every application needs to have all four, but your application will be written with some
combination of these.
Once you have decided what components you need for your application, you should list them in a file
called AndroidManifest.xml. This is an XML file where you declare the components of your application
and what their capabilities and requirements are. We will discuss soon, what the
AndroidManifest.xml is responsible for.

Unit -2 Android Application Design And Resource Page 21


Activity:
Activities are the most common of the four Android building blocks. An activity is usually a single
screen in your application. Each activity is implemented as a single class that extends the Activity
base class. Your class will display a user interface composed of Views and respond to events. Most
applications consist of multiple screens. For example, a text messaging application might have one
screen that shows a list of contacts to send messages to, a second screen to write the message to
the chosen contact, and other screens to review old messages or change settings. Each of these
screens would be implemented as an activity.
When a new screen opens, the previous screen is paused and put onto a history stack. The user can
navigate backward through previously opened screens in the history. Screens can also choose to be
removed from the history stack when it would be inappropriate for them to remain. Android retains
history stacks for each application launched from the home screen. Intent and Intent Filters:
Android uses a special class called Intent to move from screen to screen. Intent describe what an
application wants done. The two most important parts of the intent data structure are the action
and the data to act upon. Typical values for action are MAIN (the front door of the application),
VIEW, PICK, EDIT, etc. The data is expressed as a Uniform Resource Indicator (URI). For example, to
view a website in the browser, you would create an Intent with the VIEW action and the data set to
a Website-URI.
new Intent(android.content.Intent.VIEW_ACTION, ContentURI.create("http://anddev.org"));

There is a related class called an IntentFilter. While an intent is effectively a request to do something,
an intent filter is a description of what intents an activity (or intent receiver) is capable of handling.
Activities publish their IntentFilters in the AndroidManifest.xml file.

Intent Receiver:
You can use an IntentReceiver when you want code in your application to execute in reaction to an
external event, for example, when the phone rings, or when the data network is available, or when
it's midnight. Intent receivers do not display a UI, although they may display Notifications to alert the
user if something interesting has happened. Intent receivers are also registered in
AndroidManifest.xml, but you can also register them from code using Context.registerReceiver().

Service:
A Service is code that is long-lived and runs without a UI. A good example of this is a media player
playing songs from a play list. In a media player application, there would probably be one or more
activities that allow the user to choose songs and start playing them. However, the music playback
itself should not be handled by an activity because the user will expect the music to keep playing even
after navigating to a new screen. In this case, the media player activity could start a service using
Context.startService() to run in the background to keep the music going. The system will then keep
the music playback service running until it has finished. (You can learn more about the priority given
to services in the system by reading Life Cycle of an Android Application.) Note that you can connect

Unit -2 Android Application Design And Resource Page 22


to a service (and start it if it's not already running) with the Context.bindService() method. When
connected to a service, you can communicate with it through an interface exposed by the service.
For the music service, this might allow you to pause, rewind, etc.

Content Provider:
Applications can store their data in files, a SQLite database, preferences or any other mechanism that
makes sense. A content provider, however, is useful if you want your application's data to be shared
with other applications. A content provider is a class that implements a standard set of methods to
let other applications store and retrieve the type of data that is handled by that content provider.

Android Manifest File

The AndroidManifest.xml file contains information of your package, including components of the
application such as activities, services, broadcast receivers, content providers etc.

It performs some other tasks also:

It is responsible to protect the application to access any protected parts by providing the
permissions.

It also declares the android API that the application is going to use.
It lists the instrumentation classes. The instrumentation classes provides profiling and other
information. These information are removed just before the application is published etc.

This is the required xml file for all the android application and located inside the root directory.

A simple AndroidManifest.xml file looks like this:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sampleapplication.hello" android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15"


/>

<application android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" android:label="@string/title_activity_main"
>

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intentfilter>
</activity> </application>

Unit -2 Android Application Design And Resource Page 23


</manifest>

Elements of the AndroidManifest.xml file

The elements used in the above xml file are described below.

<manifest>

Manifest is the root element of the AndroidManifest.xml file. It has package attribute that describes
the package name of the activity class. <application>

Application is the sub element of the manifest. It includes the namespace declaration. This element
contains several sub elements that declares the application component such as activity etc.

The commonly used attributes are of this element are icon, label, theme etc.

● android:icon represents the icon for all the android application components.
● android:label works as the default label for all the application components.
● android:theme represents a common theme for all the android activities.

<activity>

activity is the sub element of application and represents an activity that must be defined in the
AndroidManifest.xml file. It has many attributes such as label, name, theme, launchMode etc.

● android:label represents a label i.e. displayed on the screen.


● android:name represents a name for the activity class. It is required attribute.

<intent-filter> intent-filter is the sub-element of activity that describes the type of intent to

which activity, service

or broadcast receiver can respond to.

<action>

It adds an action for the intent-filter. The intent-filter must have at least one action element.

<category>
It adds a category name to an intent-filter.
2.2 Managing Application’s Identity

Your application’s Android manifest file defines the application properties. The package name must
be defined within the Android manifest file within the <manifest> tag using the package attribute:
<manifest xmlns:android="http://schemas.android.com/apk/res/android

Unit -2 Android Application Design And Resource Page 24


" package="com.androidbook.multimedia" android:versionCode="1"

android:versionName="1.0"> Versioning Your Application

Versioning your application appropriately is vital to maintaining your application in the field.
Intelligent versioning can help reduce confusion and make product support and upgrades simpler.
There are two different version attributes defined within the <manifest> tag: the version name and
the version code.
The version name (android:versionName) is a user-friendly, developer-defined version attribute. This
information is displayed to users when they manage applications on their devices and when they
download the application from marketplaces. Developers use this version information to keep track
of their application versions in the field.
The Android operating system uses the version code (android:versionCode) that is a numeric
attribute to manage application upgrades

Setting the Application Name and Icon


Overall application settings are configured with the <application> tag of the Android manifest file.
Here you set information such as the application icon (android:icon) and friendly name
(android:label).These settings are attributes of the <application> tag.
For example, here we set the application icon to a drawable resource provided with the application
package and the application label to a string resource:

<application android:icon="@drawable/icon" android:label="@string/app_name">

Enforcing Application System Requirements


In addition to configuring your application’s identity, the Android manifest file is also used
to specify any system requirements necessary for the application to run properly. For
example, an augmented reality application might require that the handset have GPS, a
compass, and a camera. Similarly, an application that relies upon the Bluetooth APIs
available within the Android SDK requires a handset with an SDK version of API Level 5 or
higher (Android
2.0).These types of system requirements can be defined and enforced in the Android
manifest file.Then, when an application is listed on the Android Market, applications can be
filtered by these types of information; the Android platform also checks these requirements
when installing the application package on the system and errors out if necessary.
Some of the application system requirements that developers can configure through the

Android manifest file include

● The Android SDK versions supported by the application


● The Android platform features used by the application

Unit -2 Android Application Design And Resource Page 25


● The Android hardware configurations required by the application
● The screen sizes and pixel densities supported by the application
● Any external libraries that the application links to

Targeting Specific SDK Versions


Android devices run different versions of the Android platform. Often, you see old, less powerful,
or even less expensive devices running older versions of the Android platform, whereas newer,
more powerful devices that show up on the market often run the latest Android software.

There are now dozens of different Android devices in users’ hands. Developers must decide
who their target audience is for a given application. Are they trying to support the largest
population of users and therefore want to support as many different versions of the
platform as possible? Or are they developing a bleeding-edge game that requires the latest
device hardware?
Developers can specify which versions of the Android platform an application supports
within its Android manifest file using the <uses-sdk> tag. This tag has three important
attributes:

● The minSdkVersion attribute:This attribute specifies the lowest API level that the
application supports.
● The targetSdkVersion attribute:This attribute specifies the optimum API level that
the application supports.
● The maxSdkVersion attribute:This attribute specifies the highest API level that the
application supports.
Each attribute of the <uses-sdk> tag is an integer that represents the API level associated with
a given Android SDK. This value does not directly correspond to the SDK version.
Instead, it is the revision of the API level associated with that SDK. The API level is set by the
developers of the Android SDK. You need to check the SDK documentation to determine the
API level value for each version.

This shows the Android SDK versions available for shipping applications.

Unit -2 Android Application Design And Resource Page 26


Specifying the Minimum SDK Version

You should always specify the minSdkVersion attribute for your application. This value
represents the lowest Android SDK version your application supports.

For example, if your application requires APIs introduced in Android SDK 1.6, you would
check that SDK’s documentation and find that this release is defined as API Level 4.
Therefore, add the following to your Android Manifest file within the tag block:

<manifest>
<uses-sdk android:minSdkVersion="4" />

It’s that simple. You should use the lowest API level possible if you want your application to
be compatible with the largest number of Android handsets. However, you must ensure that
your application is tested sufficiently on any non-target platforms (any API level supported
below your target SDK, as described in the next section).
Specifying the Target SDK Version

You should always specify the targetSdkVersion attribute for your application. This value
represents the Android SDK version your application was built for and tested against.
For example, if your application was built using the APIs that are backward-compatible to
Android 1.6 (API Level 4), but targeted and tested using Android 2.2 SDK (API Level 8), then
you would want to specify the targetSdkVersion attribute as 8.Therefore, add the following
to your Android manifest file within the manifest tag block:
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="8" />

Why should you specify the target SDK version you used? Well, the Android platform has
built-in functionality for backward-compatibility (to a point).Think of it like this: A specific
method of a given API might have been around since API Level 1. However, the internals of
that method—its behavior—might have changed slightly from SDK to SDK. By specifying the
target SDK version for your application, the Android operating system attempts to match
your application with the exact version of the SDK (and the behavior as you tested it within
the application), even when running a different (newer) version of the platform. This means
that the application should continue to behave in “the old way” despite any new changes or
“improvements” to the SDK that might cause unintended consequences in your application.

Specifying the Maximum SDK Version


You will rarely want to specify the maxSdkVersion attribute for your application. This value
represents the highest Android SDK version your application supports, in terms of API level.
It restricts forward-compatibility of your application.

Unit -2 Android Application Design And Resource Page 27


One reason you might want to set this attribute is if you want to limit who can install the
application to exclude devices with the newest SDKs. For example, you might develop a free
beta version of your application with plans for a paid version for the newest SDK. By setting
the maxSdkVersion attribute of the manifest file for your free application, you disallow
anyone with the newest SDK to install the free version of the application. The downside of
this idea? If your users have phones that receive over-the-air SDK updates, your application
would cease to work (and appear) on phones where it had functioned perfectly, which
might “upset” your users and result in bad ratings on your market of choice.
The short answer: Use maxSdkVersion only when absolutely necessary and when you
understand the risks associated with its use.
Enforcing Application Platform Requirements
Android devices have different hardware and software configurations. Some devices have
built-in keyboards and others rely upon the software keyboard. Similarly, certain Android
devices support the latest 3-D graphics libraries and others provide little or no graphics
support. The Android manifest file has several informational tags for flagging the system
features and hardware configurations supported or required by an Android application.
Specifying Supported Input Methods
The <uses-configuration> tag can be used to specify which input methods the application
supports. There are different configuration attributes for five-way navigation, the hardware
keyboard and keyboard types; navigation devices such as the directional pad, trackball, and
wheel; and touch screen settings.
There is no “OR” support within a given attribute. If an application supports multiple input
configurations, there must be multiple <uses-configuration> tags—one for each complete
configuration supported.
For example, if your application requires a physical keyboard and touch screen input using a
finger or a stylus, you need to define two separate <uses- configuration> tags in your manifest
file, as follows:

Example:
<uses-configuration android:reqHardKeyboard="true" android:reqTouchScreen="finger" />

<uses-configuration android:reqHardKeyboard="true"
Specifying Required Device Features
Not all Android devices support every Android feature. Put another way: There are a number
of APIs (and related hardware) that Android devices may optionally include. For example, not
all Android devices have multi-touch ability or a camera flash.
The <uses-feature> tag can be used to specify which Android features the application
requires to run properly. These settings are for informational purposes only—the Android

Unit -2 Android Application Design And Resource Page 28


operating system does not enforce these settings, but publication channels such as the
Android Market use this information to filter the applications available to a given user.
If your application requires multiple features, you must create a <uses-feature> tag for each.
For example, an application that requires both a light and proximity sensor requires two tags:
Example:
<uses-feature android:name="android.hardware.sensor.light" /> <usesfeature

android:name="android.hardware.sensor.proximity" />

android:reqTouchScreen="stylus" />

Specifying Supported Screen Sizes

Android devices come in many shapes and sizes. Screen sizes and pixel densities vary widely
across the range of Android devices available on the market today. The Android platform
categorizes screen types in terms of sizes (small, normal, and large) and pixel density (low,
medium, and high).These characteristics effectively cover the variety of screen types
available within the Android platform.
An application can provide custom resources for specific screen sizes and pixel densities
.The <supportsscreen> tag can be used to specify which Android types of screens the
application supports.
For example, if the application supports QVGA screens (small) and HVGA screens (normal)
regardless of pixel density, the <supports-screen> tag is configured as follows:
<supports-screens android:smallScreens="true"

android:normalScreens="true"

android:largeScreens="false" android:anyDensity="true"/>

For more information about the <supports-screen> tag of the Android manifest file, see the
Android SDK reference as well as the Android Dev Guide documentation on Screen Support.

Unit -2 Android Application Design And Resource Page 29


Working with External Libraries
You can register any shared libraries your application links to within the Android manifest
file. By default, every application is linked to the standard Android packages (such as
android.app) and is aware of its own package.However, if your application links to additional
packages, they must be registered within the <application> tag of the Android manifest file
using the <uses-library> tag. For example

<uses-library android:name="com.sharedlibrary.sharedStuff"/>
This feature is often used for linking to optional Google APIs. For more information about the
<uses-library> tag of the Android manifest file, see the Android SDK reference.

Registering Application’s Activities and other Application Components


Each Activity within the application must be defined within the Android manifest file with an
<activity> tag. For example, the following XML excerpt defines an Activity class called
AudioActivity:

<activity android:name="AudioActivity" />


This Activity must be defined as a class within the com.androidbook.multimedia package.
That is, the package specified in the <manifest> element of the Android manifest file. You
can also enforce scope of the activity class by using the dot as a prefix in the Activity name:

<activity android:name=".AudioActivity" />

Or you can specify the complete class name:

<activity android:name="com.androidbook.multimedia.AudioActivity" />


Designating a Primary Entry Point Activity for Your Application Using an Intent
Filter
An Activity class can be designated as the primary entry point by configuring an intent filter

using the Android manifest tag <intent-filter> in the application’s AndroidManifest.xml file

with the MAIN action type and the LAUNCHER category.

The following tag of XML configures the Activity class called MultimediaMenuActivity as the

primary launching point of the application:

<activity android:name=".MultimediaMenuActivity"

android:label="@string/app_name">

<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>
Configuring Other Intent Filters
The Android operating system uses Intent filters to resolve implicit intents. That is, Intents

that do not specify the Activity or Component they want launched. Intent filters can be

applied to Activities, Services, and BroadcastReceivers. The filter declares that this

component is open to receiving any Intent sent to the Android operating system that

matches its criteria.

Intent filters are defined using the <intent-filter> tag and must contain at least one <action>

tag but can also contain other information, such as <category> and <data> blocks. Here we

have a sample intent filter block, which might be found within an <activity> block:

<intent-filter>

<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.BROWSABLE" />

<category android:name="android.intent.category.DEFAULT" />

<data android:scheme="geoname"/>

</intent-filter>
This intent filter definition uses a predefined action called VIEW, the action for viewing

particular content. It is also BROWSABLE and uses a scheme of geoname so that when a Uri

starts with geoname://, the activity with this intent filter launches.
Registering Services and Broadcast Receivers
All application components are defined within the Android manifest file. In addition

to activities, all services and broadcast receivers must be registered within the

Android Manifest file.

● Services are registered using the <service> tag. ● Broadcast


Receivers are registered using the <receiver> tag.

Both Services and Broadcast Receivers use intent filters.

Registering Content Providers


If your application acts as a content provider, effectively exposing a shared data service for

use by other applications, it must declare this capability within the Android manifest file

using the <provider> tag. Configuring a content provider involves determining what subsets

of data are shared and what permissions are required to access them, if any.

Working with Permissions

App permissions help support user privacy by protecting access to the following:

● Restricted data, such as system state and a user's contact information. ●


Restricted actions, such as connecting to a paired device and recording audio.

Workflow for using permissions

If your app offers functionality that might require access to restricted data or restricted
actions, determine whether you can get the information or perform the actions without
needing to declare permissions. You can fulfill many use cases in your app, such as taking
photos, pausing media playback, and displaying relevant ads, without needing to declare
any permissions.

If you decide that your app must access restricted data or perform restricted actions to
fulfill a use case, declare the appropriate permissions. Some permissions, known as
installtime permissions, are automatically granted when your app is installed. Other
permissions, known as runtime permissions, require your app to go a step further and
request the permission at runtime.
Types of permissions

Android categorizes permissions into different types, including install-time permissions,


runtime permissions, and special permissions. Each permission's type indicates the scope
of restricted data that your app can access, and the scope of restricted actions that your
app can perform, when the system grants your app that permission.

Install-time permissions

Install-time permissions give your app limited access to restricted data, and they allow your
app to perform restricted actions that minimally affect the system or other apps. When you
declare install-time permissions in your app, the system automatically grants your app the
permissions when the user installs your app. An app store presents an install-time
permission notice to the user when they view an app's details page.

Android includes several sub-types of install-time permissions, including normal


permissions and signature permissions.

Normal permissions

These permissions allow access to data and actions that extend beyond your app's sandbox.
However, the data and actions present very little risk to the user's privacy, and the operation
of other apps.

The system assigns the "normal" protection level to normal permissions, as shown on the
permissions API reference page.

Signature permissions

If the app declares a signature permission that another app has defined, and if the two apps
are signed by the same certificate, then the system grants the permission to the first app at
install time. Otherwise, that first app cannot be granted the permission.

Runtime permissions

Runtime permissions, also known as dangerous permissions, give your app additional
access to restricted data, and they allow your app to perform restricted actions that more
substantially affect the system and other apps. Therefore, you need to request runtime
permissions in your app before you can access the restricted data or perform restricted
actions. When your app requests a runtime permission, the system presents a runtime
permission prompt.
Many runtime permissions access private user data, a special type of restricted data that
includes potentially sensitive information. Examples of private user data include location and
contact information.

The system assigns the "dangerous" protection level to runtime permissions, as shown on
the permissions API reference page.

Special permissions

Special permissions correspond to particular app operations. Only the platform and OEMs
can define special permissions. Additionally, the platform and OEMs usually define special
permissions when they want to protect access to particularly powerful actions, such as
drawing over other apps.

The Special app access page in system settings contains a set of user-toggleable operations.
Many of these operations are implemented as special permissions.

Each special permission has its own implementation details. The instructions for using each
special permission appear on the permissions API reference page. The system assigns the
"appop" protection level to special permissions.

Unit: 3 Exploring User Interface Screen Elements


3.1 Introducing Android Views, Layouts, TextView, Buttons, Check Boxes, Radio Groups, Indicators,
SeekBar, Context Menus, User Events, Styles and Themes, Dates and Times, Retrieving Data.
What is Android Views?
A View is a simple building block of a user interface. It is a small rectangular box that can be
TextView, EditText, or even a button. It occupies the area on the screen in a rectangular area and is
responsible for drawing and event handling. View is a superclass of all the graphical user interface
components.
The Android SDK has a Java package name android.view. This package contains a number of
interfaces and classes related to drawing on the screen. However, when we refer to the View object,
we actually refer to onl y one of the classes within this package: the android.view.View class. View is
the basic building block of UI (User Interface) in android. View refers to the android.view.View class,
which is the super class for all the GUI components like TextView, ImageView, Button etc. View class
extends Object class and Implements Drawable.Callback, KeyEvent.Callback and
AccessibilityEventSource.
The question that might be bothering you would be, what can be the size of this rectangle? The
answer is either we can set it manually, by specifying the exact size (with proper units) or by
using some predefined values. These predefined values are match_parent and wrap_content.
match_parent means it will occupy the complete space available on the display of the device.
Whereas, wrap_content means it will occupy only that much space as required for its content to
display.

ViewGroup
View Group is a subclass of the ViewClass and can be considered as a superclass of Layouts. It
provides an invisible co0ntainer to hold the views or layouts. ViewGroup instances and views work
together as a container for Layouts. To understand in simpler words it can be understood as a
special view that can hold other views that are often known as a child view.

The Android framework will allow us to use UI elements or widgets in two ways:
• Use UI elements in the XML file
• Create elements in the Kotlin file dynamically
Introducing Android Layouts
A layout defines the structure for a user interface in your app, such as in an activity. All elements in
the layout are built using a hierarchy of View and ViewGroup objects. A View usually draws
something the user can see and interact with. Whereas a ViewGroup is an invisible container that
defines the layout structure for View and other ViewGroup objects.
One special type of control found within the android.widget package is called a layout. A layout
control is still a View object, but it doesn’t actually draw anything specific on the screen. Instead, it is
a parent container for organizing other controls (children). Layout controls determine how and
where on the screen child controls are drawn. Each type of layout control draws its children using
particular rules. For instance, the LinearLayout control draws its child controls in a single horizontal
row or a single vertical column. Similarly, a TableLayout control displays each child control in tabular
format(in cells within specific rows and columns).
In “Designing User Interfaces with Layouts,” we organize various controls within layouts and other
containers. These special View controls, which are derived from the android.view.ViewGroup class,
are useful only after you understand the various display controls these containers can hold. By
necessity, we use some of the layout View objects within this chapter to illustrate how to use the
controls previously mentioned.
Types of Layouts
• Linear Layout
• Relative Layout
• Constraint Layout
• Table Layout
• Frame Layout
• List View
• Grid View
• Absolute Layout
• WebView
• ScrollView
• Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View
elements one by one either in a particular direction either horizontally or vertically based on
the orientation property.
• Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the
position of child View elements relative to each other like (A to the right of B) or relative to
the parent (fix to the top of the parent).
• Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to specify the
position of layout constraints for every child View relative to other views present. A
ConstraintLayout is similar to a RelativeLayout, but having more power.
• Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the position of
View elements it contains on the top of each other to display only a single View inside the
FrameLayout.
• Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child View
elements in rows and columns.
• Android Web View: WebView is a browser that is used to display the web pages in our
activity layout.
• Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in a single
column.
• Android Grid View: GridView is a ViewGroup that is used to display a scrollable list of items
in a grid view of rows and columns.

Layout params
This tutorial is more about creating your GUI based on layouts defined in XML file. A layout may
contain any type of widgets such as buttons, labels, textboxes, and so on. Following is a simple
example of XML file having LinearLayout −

Once your layout has created, you can load the layout resource from your application code, in your
Activity.onCreate() callback implementation as shown below −

Attributes of Layout in Android


The following are the attributes for customizing a Layout while defining it:
• android:id: It uniquely identifies the Android Layout.
• android:hint: It shows the hint of what to fill inside the EditText.
• android:layout_height: It sets the height of the layout.
• android:layout_width: It sets the width of the layout.
• android:layout_gravity: It sets the position of the child view.
• android:layout_marginTop: It sets the margin of the from the top of the layout.
• android:layout_marginBottom: It sets the margin of the from the bottom of the layout.
• android:layout_marginLeft: It sets the margin of the from the left of the layout.
• android:layout_marginRight: It sets the margin of the from the right of the layout.
• android:layout_x: It specifies the x coordinates of the layout. • android:layout_y: It
specifies the y coordinates of the layout.
Types of Android Views(Control,palette)
Another thing that might now come to your mind must be, “what are the available types of view in
Android that we can use?”
For that, we’ll see all these types one by one as follows:
• TextView
• EditText
• Button
• Image Button
• Date Picker
• RadioButton
• CheckBox buttons
• Image View

1).TextView :-
A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete
text editor, however the basic class is configured to not allow editing.
TextView Attributes
Attribute & Description android:id This is the ID
which uniquely identifies the control.
android:capitalize If set, specifies that this TextView has a textual input method and should
automatically capitalize what the user types. • Don't automatically capitalize anything - 0
• Capitalize the first word of each sentence - 1
• Capitalize the first letter of every word - 2 • Capitalize every character - 3
android:cursorVisible Makes the cursor visible (the default) or invisible. Default is
false. android:editable If set to true, specifies that this TextView has an input
method.
android:fontFamily Font family (named by string) for the text.
android:gravity Specifies how to align the text by the view's x- and/or y-axis when the text is smaller
than the view.
android:hint Hint text to display when the text is empty.
android:inputType The type of data being placed in a text field. Phone, Date, Time, Number,
Password etc.
android:password Whether the characters of the field are displayed as password dots instead
of themselves. Possible value either "true" or "false".
android:phoneNumber If set, specifies that this TextView has a phone number input method.
Possible value either "true" or "false". android:text Text to display. android:textAllCaps
Present the text in ALL CAPS. Possible value either "true" or "false". android:textSize
Size of the text. Recommended dimension type for text is "sp" for scaledpixels
(example: 15sp).
Example
MainActivity.java
package com.example.demo;

import android.os.Bundle; import android.app.Activity; import android.view.Menu; import


android.view.View; import android.widget.TextView; import android.widget.Toast;

public class MainActivity extends Activity {


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

//--- text view---


TextView txtView = (TextView) findViewById(R.id.text_id);
}
}

activity_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView android:id="@+id/text_id" android:layout_width="300dp"


android:layout_height="200dp" android:capitalize="characters" android:text="hello_world"
android:textColor="@android:color/holo_blue_dark"
android:textColorHighlight="@android:color/primary_text_dark"
android:layout_centerVertical="true" android:layout_alignParentEnd="true"
android:textSize="50dp"/>

</RelativeLayout>

2).EditText
A EditText is an overlay over TextView that configures itself to be editable. It is the predefined
subclass of TextView that includes rich editing capabilities.

Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method. android:text
This is the Text to display.
Inherited from android.view.View Class –

Attribute Description android:background This is a drawable to use as the


background. android:contentDescription This defines text that briefly describes
content of the view. android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke when the
view is clicked. android:visibility This controls the initial visibility of the view.

Example activity_main.xml file –

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" android:layout_marginLeft="14dp"
android:layout_marginTop="18dp" android:text="@string/example_edittext" />

<Button
android:id="@+id/button" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1" android:layout_marginTop="130dp"
android:text="@string/show_the_text" />
<EditText android:id="@+id/edittext" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1" android:layout_marginTop="61dp"
android:ems="10"
android:text="@string/enter_text" android:inputType="text" />
</RelativeLayout>

MainActivity.java file-

package com.example.demo; import android.os.Bundle; import android.app.Activity; import


android.view.View; import android.view.View.OnClickListener; import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


EditText eText;
Button btn; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);0 eText = (EditText) findViewById(R.id.edittext); btn =
(Button) findViewById(R.id.button); btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) { String str = eText.getText().toString();
Toast msg = Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG); msg.show();
}
});
}
}

3).Button:-
A Button is a Push-button which can be pressed, or clicked, by the user to perform an action.

Button Attributes
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom
This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text. android:editable
If set, specifies that this TextView has an input method.
android:text
This is the Text to display

Inherited from android.view.View Class –


android:background
This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke when the
view is clicked. android:visibility
This controls the initial visibility of the view.

Button Example

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:id="@+id/btn_next" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" android:layout_centerInParent="true"
android:layout_marginStart="172dp" android:layout_marginEnd="151dp"
android:text="NEXT" tools:layout_editor_absoluteX="149dp"
tools:layout_editor_absoluteY="80dp" android:onClick="btn_next"/>
<Button android:id="@+id/btn_previous" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@id/btn_next"
android:layout_alignParentEnd="true" android:layout_alignParentBottom="true"
android:layout_marginTop="67dp" android:layout_marginEnd="140dp"
android:layout_marginBottom="225dp" android:text="PREVIOUS"
android:onClick="btn_previous"/>
</RelativeLayout>

MainActivity.java

package com.example.exampleofbutton; 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 btn_next(View view) {
Toast.makeText(this,"Next Button Clicked", Toast.LENGTH_SHORT).show();
}

public void btn_previous(View view) {


Toast.makeText(this,"Previous Button Clicked", Toast.LENGTH_SHORT).show();
}
}

Example of TextView,EditText and Button

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:id="@+id/parentRelative"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center" tools:context=".MainActivity">

<EditText android:id="@+id/editTextName" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_below="@id/textviewname"
android:layout_marginTop="-249dp" android:ems="10" android:hint="Enter Your Name"
android:inputType="textPersonName" android:padding="20dp"
android:textColor="#F44336" />

<Button android:id="@+id/btnclickhere" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_below="@id/editTextName"
android:layout_marginTop="29dp" android:padding="20dp" android:text="ClickMe" />
<TextView
android:id="@+id/textviewname" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:padding="20dp" android:text="TextView"
/>
</RelativeLayout>

MainActivity.java

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


import android.os.Bundle; import android.view.View; import android.widget.Button; import
android.widget.EditText; import android.widget.TextView; import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText editTextName;
Button btnclickhere;
TextView textviewname;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName=(EditText)findViewById(R.id.editTextName);
btnclickhere=(Button)findViewById(R.id.btnclickhere);
textviewname=(TextView)findViewById(R.id.textviewname);
btnclickhere.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name=editTextName.getText().toString();
textviewname.setText("Hi"+name);

}
});
}
}

4). CheckBox:- Android CheckBox is a type of two state button either checked or unchecked.There
can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the user,
activate/deactivate the specific action etc.Android CheckBox class is the subclass of
CompoundButton class.
The android.widget.CheckBox class provides the facility of creating the CheckBoxes.
Method:-There are many inherited methods of View, TextView, and Button classes in the CheckBox
class. Some of them are as follows:
1).public boolean isChecked():-Returns true if it is checked otherwise false.
2).public void setChecked(boolean status):- Changes the state of the CheckBox.
CheckBox Attributes
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom
This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text. android:editable
If set, specifies that this TextView has an input method.
android:text
This is the Text to display Inherited
from android.view.View Class –
android:background
This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke when the
view is clicked. android:visibility
This controls the initial visibility of the view.
Example
MainActivity.java
package com.example.checkboxexample; import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import
android.widget.Toast; public class MainActivity extends AppCompatActivity {
CheckBox ch,ch1,ch2,ch3;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); ch=(CheckBox)findViewById(R.id.checkBox);
ch1=(CheckBox)findViewById(R.id.checkBox3); ch2=(CheckBox)findViewById(R.id.checkBox4);
ch3=(CheckBox)findViewById(R.id.checkBox5);
}
// This function is invoked when the button is pressed.
public void Check(View view) { /* Finding CheckBox by its unique ID */
String msg="";
// Concatenation of the checked options in if // isChecked() is used to check whether //
the CheckBox is in true state or not.
if(ch.isChecked()) msg = msg + " Painting "; if(ch1.isChecked()) msg = msg + "
Dancing "; if(ch2.isChecked()) msg = msg + " Reading "; if(ch3.isChecked()) msg
= msg + " Surfing ";
// Toast is created to display the // message using show() method.
Toast.makeText(this, msg+"Are Selected", Toast.LENGTH_LONG).show();
}
}

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">
<TextView android:layout_width="398dp" android:layout_height="wrap_content"
android:layout_marginStart="8dp" android:layout_marginTop="48dp"
android:layout_marginEnd="8dp" android:text="Choose your hobbies:"
android:textSize="24sp" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
<CheckBox android:id="@+id/checkBox" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="16dp"
android:text="Painting" android:textSize="18sp" />
<CheckBox android:id="@+id/checkBox3" android:layout_width="match_parent"
android:layout_height="37dp" android:text="Dancing" android:textSize="18sp" />
<CheckBox
android:id="@+id/checkBox4" android:layout_width="match_parent"
android:layout_height="37dp" android:text="Reading" android:textSize="18sp" />
<CheckBox android:id="@+id/checkBox5" android:layout_width="match_parent"
android:layout_height="37dp" android:text="Surfing" android:textSize="18sp" />
<Button android:id="@+id/button" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="16dp"
android:onClick="Check" android:text="@string/submit"/>
</LinearLayout>

5).Radio Group and Radio Button


RadioButton is a two states button which is either checked or unchecked. If a single radio button is
unchecked, we can click it to make checked radio button. Once a radio button is checked, it cannot
be marked as unchecked by user.
RadioButton is generally used with RadioGroup. RadioGroup contains several radio buttons, marking
one radio button as checked makes all other radio buttons as unchecked.
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" >

<TextView android:id="@+id/textView" android:layout_width="fill_parent"


android:layout_height="wrap_content" android:layout_marginTop="30dp"
android:gravity="center_horizontal" android:textSize="22dp"
android:text="Single Radio Buttons"/>
<!-- Default RadioButtons -->
<RadioButton android:id="@+id/radioButton1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_gravity="center_horizontal"
android:text="B.Com" android:layout_marginTop="20dp" android:textSize="20dp" />
<RadioButton android:id="@+id/radioButton2" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="B.C.A"
android:layout_marginTop="10dp" android:textSize="20dp" /> <RadioButton
android:id="@+id/radioButton3" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="B.B.A"
android:layout_marginTop="10dp" android:textSize="20dp" />

<View android:layout_width="fill_parent" android:layout_height="1dp"


android:layout_marginTop="20dp" android:background="#B8B894" />
<TextView android:id="@+id/textView2"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_marginTop="30dp" android:gravity="center_horizontal"
android:textSize="22dp" android:text="Radio button inside RadioGroup" />
<!-- Customized RadioButtons -->
<RadioGroup android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/radioGroup">
<RadioButton android:id="@+id/radioMale" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Male"
android:layout_marginTop="10dp" android:checked="false" android:textSize="20dp"
/> <RadioButton android:id="@+id/radioFemale"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text=" Female" android:layout_marginTop="20dp" android:checked="false"
android:textSize="20dp" />
</RadioGroup> <Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Show Selected"
android:id="@+id/button" android:onClick="onclickbuttonMethod"
android:layout_gravity="center_horizontal" /> </LinearLayout> MainActivity.java package
com.example.radiobuttondemo; 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 btn;
RadioButton genderradioButton;
RadioGroup rGroup; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rGroup=(RadioGroup)findViewById(R.id.radioGroup);
}
public void onclickbuttonMethod(View view) { int selectedId =
rGroup.getCheckedRadioButtonId(); genderradioButton = (RadioButton)
findViewById(selectedId);
// Toast.makeText(this, "genderradioButton", Toast.LENGTH_SHORT).show();
if(selectedId==-1) {
Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this,genderradioButton.getText(),
Toast.LENGTH_SHORT).show();
}
}
}

Indicators
The Android SDK provides a number of controls that can be used to visually show some form of
information to the user. These indicator controls include progress bars, clocks, and other similar
controls.
ProgressBars
Android ProgressBar is a graphical view indicator that shows some progress. Android progress bar
displays a bar representing the completing of the task. Progress bar in android is useful since it gives
the user an idea of time to finish its task.
Progress bars are used to show progress of a task. For example, when you are uploading or
downloading something from the internet, it is better to show the progress of download/upload to
the user.
Android ProgressBar attributes
Some important attributes used to describe a ProgressBar are given below.
• android:max : We can set the maximum value of the ProgressBar using this attribute. By
default the progress bar maximum value is 100
• android:indeterminate : A boolean value is set depending on whether the time is
determinate or not. Setting this attribute to false would show the actual progress. Else if it’s
set to true a cyclic animation is displayed to show that progress is happening •
android:minHeight :
It’s used to set the height of the ProgressBar
• android:minWidth : It’s used to set the width of the ProgressBar
• android:progress : It’s used to set the number by which the progress bar value will be
incremented
• style : By default the progress bar will be displayed as a spinning wheel. If we want it to be
displayed as a horizontal bar, we need to set the attribute as :
style=”?android:attr/progressBarStyleHorizontal”
Method
1).getMax():-This method returns the maximum value of the progress.
2). incrementProgressBy(int diff):-This method increments the progress bar by the difference of
value passed as a parameter.
3). setIndeterminate(boolean indeterminate):-This method sets the progress indicator as
determinate or indeterminate.
4). setMax(int max):-This method sets the maximum value of the progress dialog.
5). setProgress(int value):-This method is used to update the progress dialog with some specific
value.
6). show(Context context, CharSequence title, CharSequence message):-This is a static method, used
to display progress dialog.
Example
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">
<ProgressBar
android:id="@+id/simpleProgressBar" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:layout_centerHorizontal="true"/> <Button
android:id="@+id/startButton" android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Start" android:textSize="20sp" android:textStyle="bold"
android:layout_centerHorizontal="true" android:layout_marginTop="100dp"
android:padding="10dp" android:background="#0f0" android:textColor="#fff"/>
</RelativeLayout> Mainactivity.java
package com.example.textviewdemo; import androidx.appcompat.app.AppCompatActivity; import
android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import
android.view.View; import android.widget.Button; import android.widget.ProgressBar; public
class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // initiate progress bar and start button
final ProgressBar simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar);
Button startButton = (Button) findViewById(R.id.startButton);
// perform click event on button
startButton.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { // visible the progress bar
simpleProgressBar.setVisibility(View.VISIBLE);
}
});
}
}

SeekBar:-
Android SeekBar is a type of ProgressBar. On touching the thumb on seekbar and dragging it to the
right or left, the current value of the progress changes. SeekBar is used for forwarding or
backwarding the songs, Video etc. In the setOnSeekBarChangeListener interface is used which
provides three methods.
• onProgressChanged: In this method progress is changed and then according to this change
the progress value can used in our logic.
• onStartTrackingTouch: In this method when the user has started dragging, then this method
will be called automatically.
• onStopTrackingTouch: In this method, when the user stops dragging, then this method will
called automatically. Example
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">

<TextView
android:id="@+id/textView" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true" android:layout_marginEnd="180dp"
android:layout_marginBottom="460dp" android:text="Example of Seekbar" />

<SeekBar
android:id="@+id/seekBar" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginEnd="8dp"
android:layout_marginStart="8dp" android:layout_marginTop="372dp"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="#0F0"/><!-- set green color in the background of seek bar-->
</RelativeLayout> MainActivity.java
package com.example.seekbarexample; import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color; import android.os.Bundle; import android.widget.SeekBar;
import android.widget.TextView; import android.widget.Toast; public class MainActivity extends
AppCompatActivity {
// Define the global variable
SeekBar seekbar;
TextView Text_message;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// use findViewById() to get the Button
Text_message= (TextView)findViewById(R.id.textView); seekbar=
(SeekBar)findViewById(R.id.seekBar); //SeekBar.setBackgroundColor(Color.GREEN);
seekbar.setBackgroundColor(Color.GREEN);// green background color for the seek bar
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
Toast.makeText(getApplicationContext(),"seekbar progress: "+progress,
Toast.LENGTH_SHORT).show();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch started!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch stopped!",
Toast.LENGTH_SHORT).show();
}
});
}
}

Context menus:-
In Android, the context menu is like a floating menu and arises when the user has long
pressed or clicks on an item and is beneficial for implementing functions that define the specific
content or reference frame effect. The Android context menu is similar to the right-click menu in
Windows or Linux. In the Android system, the context menu provides actions that change a specific
element or context frame in the user interface and one can provide a context menu for any view.
The context menu will not support any object shortcuts and object icons. Note that we are going to
implement this project using the Java language.
Example
Step 1: Create a New Project
Step 2: Working with the activity_main.xml file Open res -> Layout -> activity_main.xml and write the
following code. In this file add only a TextView to display a simple text.

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">
<TextView
android:id="@+id/textView" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" android:text="Long press me!" android:textColor="#000"
android:textSize="20sp" android:textStyle="bold" />
</RelativeLayout>

Step 3: Working with the Mainactivity.java file Open the app -> Java -> Package -> Mainactivity.java
file. In this step, add the code to show the ContextMenu. Whenever the app will start make a long
click on a text and display the number of options to select them for specific purposes.

MainActivity.java

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


import android.graphics.Color; import android.os.Bundle; import android.view.ContextMenu;
import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Link those objects with their respective id's
// that we have given in .XML file
textView = (TextView) findViewById(R.id.textView);
relativeLayout = (RelativeLayout) findViewById(R.id.relLayout);
// here you have to register a view for context menu
// you can register any view like listview, image view,
// textview, button etc
registerForContextMenu(textView);
}
@Override public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// you can set menu header with title icon etc menu.setHeaderTitle("Choose a color");
// add menu items
menu.add(0, v.getId(), 0, "Yellow"); menu.add(0, v.getId(), 0, "Gray");
menu.add(0, v.getId(), 0, "Cyan");
}
// menu item select listener
@Override
public boolean onContextItemSelected(MenuItem item) { if (item.getTitle() == "Yellow") {
relativeLayout.setBackgroundColor(Color.YELLOW);
} else if (item.getTitle() == "Gray") {
relativeLayout.setBackgroundColor(Color.GRAY);
} else if (item.getTitle() == "Cyan") {
relativeLayout.setBackgroundColor(Color.CYAN);
}
return true;
}
}

User Event

Events are a useful way to collect data about a user's interaction with interactive components of
Applications. Like button presses or screen touch etc. The Android framework maintains an event
queue as a first-in, first-out (FIFO) basis. You can capture these events in your program and take
appropriate action as per requirements.

There are following three concepts related to Android Event Management –


● Event Listeners − An event listener is an interface in the View class that contains a single
callback method. These methods will be called by the Android framework when the View to which
the listener has been registered is triggered by user interaction with the item in the UI.
● Event Listeners Registration − Event Registration is the process by which an Event Handler
gets registered with an Event Listener so that the handler is called when the Event Listener fires the
event.
● Event Handlers − When an event happens and we have registered an event listener for the
event, the event listener calls the Event Handlers, which is the method that actually handles the
event.
Event Listeners & Event Handlers
Event Handler Event Listener & Description onClick()
OnClickListener()
This is called when the user either clicks or touches or focuses upon any widget like button, text,
image etc. You will use onClick() event handler to handle such event.
onLongClick() OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget like button, text,
image etc. for one or more seconds. You will use onLongClick() event handler to handle such event.
onFocusChange() OnFocusChangeListener()
This is called when the widget loses its focus ie. user goes away from the view item. You will use the
onFocusChange() event handler to handle such an event.
onKey() OnFocusChangeListener()
This is called when the user is focused on the item and presses or releases a hardware key on the
device. You will use onKey() event handler to handle such an event.
onTouch() OnTouchListener()
This is called when the user presses the key, releases the key, or any movement gesture on the
screen. You will use onTouch() event handler to handle such event.
onMenuItemClick() OnMenuItemClickListener()
This is called when the user selects a menu item. You will use onMenuItemClick() event handler to
handle such event.
onCreateContextMenu() onCreateContextMenuItemListener()
This is called when the context menu is being built(as the result of a sustained "long click)

Event Listeners Registration


Event Registration is the process by which an Event Handler gets registered with an Event
Listener so that the handler is called when the Event Listener fires the event. Though there are
several tricky ways to register your event listener for any event, I'm going to list down only top 3
ways, out of which you can use any of them based on the situation.
● Using an Anonymous Inner Class
● Activity class implements the Listener interface.
● Using Layout file activity_main.xml to specify event handler directly.

Touch Mode
Users can interact with their devices by using hardware keys or buttons or touching the
screen.Touching the screen puts the device into touch mode. The user can then interact with it by
touching the on-screen virtual buttons, images, etc.You can check if the device is in touch mode by
calling the View class's InTouchMode() method.

Focus
A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This
indicates that it’s ready to accept input from the user.
● isFocusable() − it returns true or false
● isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A view
may be focusable when using a hardware key but not when the device is in touch mode)

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


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

android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >

android:layout_height="wrap_content" android:text="Click Event"


android:layout_marginTop="200dp" android:layout_marginLeft="130dp"/>

android:id="@+id/txtResult" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp"
android:textColor="#86AD33" android:textSize="20dp"
android:textStyle="bold" android:layout_marginTop="12dp"/> </LinearLayout>
MainActivity.java
package com.tutlane.inputeventsexample; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.view.View; import android.widget.Button; import
android.widget.TextView;

public class MainActivity extends AppCompatActivity { Button btn;


TextView tView; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); btn = (Button)findViewById(R.id.btnClick); tView =
(TextView)findViewById(R.id.txtResult); btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

tView.setText("You Clicked On Button");


}
});
}
}
Styles and Themes
A style resource defines the format and looks for a UI. A style can be applied to an individual
View (from within a layout file) or to an entire Activity or application (from within the manifest file).
Defining Styles
A style is defined in an XML resource that is separate from the XML that specifies the layout. This
XML file resides under the res/values/ directory of your project and will have as the root node which
is mandatory for the style file. The name of the XML file is arbitrary, but it must use the .xml
extension.
You can define multiple styles per file using tag as shown below – <?xml
version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomFontStyle">

<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>

<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>

<item name="android:textColor">#00FF00</item>/>
</style>
</resources>
Using Styles Once your style is defined, you can use it in your XML Layout file using style attribute as
follows –

Theme is a style that is applied to an entire activity or app, instead of an individual View like as
mentioned above. When we applied a style as a theme, the views in activity or app apply to the all
style attributes that supports. For example. If we apply TextviewStyle as a theme for an activity, then
the text of all the views in activity appears in the same style.
Following is the example of defining a theme in the android application.
<color name="custom_theme_color">#b0b0ff</color>
<style name="CustomTheme" parent="Theme.AppCompat.Light">
<item name="android:windowBackground">@color/custom_theme_color</item>
<item name="android:colorBackground">@color/custom_theme_color</item> </style> The
above code overrides windowBackground and colorBackground properties of
Theme.AppCompat.Light theme.
To set a theme for a particular activity, open AndroidManifest.xml file and write the code like as
shown below
<activity android:theme="@android:style/CustomTheme">
In case, if we want to set the theme for all the activities in android application, open
AndroidManifest.xml file and write the code like as shown below.
<application android:theme="@android:style/CustomTheme">
Android Styling Color Palette
In android, we can customize the application basic theme colors based on our requirements.
Following is the example of basic material design in the android application.

Generally, the above layout defined in styles.xml file like as shown below and it resides in res/values
folder.
<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>
We can customize the application basic theme colors based on our requirements. Now we will see
how to use these styles and themes in android applications with examples.
Android Styles and Themes Example
Following is the example of defining a custom style for controls in LinearLayout to apply different
styles for controls in the android application.
Create a new android application using android studio and give names as StylesThemesExample. In
case if you are not aware of creating an app in android studio check this article Android Hello World
App.
Now we need to define our styles in styles.xml file, for that open styles.xml file from \res\values
folder and write the code like as shown below.
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="TextviewStyle" parent="@android:style/Widget.TextView">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">100dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textColor">#86AD33</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">20dp</item>
</style>
<style name="ButtonStyle" parent="@android:style/Widget.Button">
<item name="android:layout_width">200dp</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">100dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android:background">#F1511B</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">15dp</item>
</style>
<string name="wlcmsg">welcome </string> </resources>
If you observe above code, we defined a two styles (TextViewStyle, ButtonStyle) and we can apply
these styles for required controls in android application.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="@+id/TextView1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp"
android:layout_marginTop="200dp" android:textColor="#00ADEF" android:textSize="15dp"
android:text="@string/wlcmsg"/>
<TextView
android:id="@+id/TextView2" style="@style/TextviewStyle" android:text="Welcome to
Tutlane"/>
<Button android:id="@+id/btnShow" android:text="Click on Button"
style="@style/ButtonStyle" /> </LinearLayout>
If you observe above code we are referring our styles to required controls using style attribute.
Dates and Times
Date and Time in Android are formatted using the SimpleDateFormat library from Java, using
Calendar instance which helps to get the current system date and time. The current date and time
are of the type Long which can be converted to a human-readable date and time. In this article, it’s
been discussed how the Date and Time values can be formatted in various formats and displayed.
Have a look at the following image to get an idea of the entire discussion.

Steps to Format the Date and Time in Android


Step 1: Create an empty activity project
• Using Android Studio create an empty activity project. Refer to Android | How to
Create/Start a New Project in Android Studio?
Step 2: Working with the activity_main.xml file
• The main layout of the activity file containing 8 TextViews. One to show the current system
date and time value in Long type, and others to display the same date and time value in a
formatted human-readable way.
• To implement the UI invoke the following code inside the activity_main.xml file.
Activity_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:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity"
tools:ignore="HardcodedText">

<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="32dp"
android:text="Date and Time value in Long type :" android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" /> <!--text view to show the current date and
time in Long type-->
<TextView android:id="@+id/dateTimeLongValue"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="64dp"
android:textSize="18sp" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView android:id="@+id/textView" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="64dp" android:text="Date and Time formatted :"
android:textSize="18sp" android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/dateTimeLongValue" />

<!--text views to show the current date and time in formatted and human readable way-->
<TextView android:id="@+id/format1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<TextView android:id="@+id/format2" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format1" />
<TextView android:id="@+id/format3" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format2" />

<TextView android:id="@+id/format4" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format3" />

<TextView
android:id="@+id/format5" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format4" />

<TextView
android:id="@+id/format6" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format5" /> <TextView
android:id="@+id/format7" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format6" />

</androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Working with the MainActivity file
Understanding the way of formatting the date and time in Android using SimpleDateFormat •
Firstly, the instance of the Calendar is created and the desired format of the date and time
to be shown is passed to the SimpleDateFormat method. The String should include the following
characters and one may include the separators like -, / etc.
• The below table includes the characters to be used to generate the most used common
pattern of date and time.
Character to be used Output
dd Date in numeric value
E Day in String (short form. Ex: Mon)
EEEE Day in String (full form. Ex: Monday)
MM Month in numeric value
yyyy Year in numeric value
LLL Month in String (short form. Ex: Mar)
LLLL Month in String (full form. Ex: March)
HH Hour in numeric value (24hrs timing format)

import androidx.appcompat.app.AppCompatActivity; import java.text.SimpleDateFormat; import


java.util.Calendar;

public class MainActivity extends AppCompatActivity {

TextView dateTimeInLongTextView, format1, format2, format3, format4, format5,


format6, format7;

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

String dateTime;
Calendar calendar;
SimpleDateFormat simpleDateFormat;

// register all the text view with appropriate IDs


dateTimeInLongTextView = (TextView) findViewById(R.id.dateTimeLongValue);
format1 = (TextView) findViewById(R.id.format1); format2 = (TextView)
findViewById(R.id.format2); format3 = (TextView) findViewById(R.id.format3); format4 =
(TextView) findViewById(R.id.format4); format5 = (TextView) findViewById(R.id.format5);
format6 = (TextView) findViewById(R.id.format6); format7 = (TextView)
findViewById(R.id.format7);

// get the Long type value of the current system date Long dateValueInLong =
System.currentTimeMillis();
dateTimeInLongTextView.setText(dateValueInLong.toString());

// different format type to format the


// current date and time of the system
// format type 1
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format1.setText(dateTime);

// format type 2
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format2.setText(dateTime);

// format type 3
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format3.setText(dateTime);

// format type 4
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.LLL.yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format4.setText(dateTime);

// format type 5
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.LLLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format5.setText(dateTime);

// format type 6
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("E.LLLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format6.setText(dateTime);

// format type 7
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("EEEE.LLLL.yyyy KK:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format7.setText(dateTime);
}
}
Retrieving Data
SQLite is an open source SQL database that stores data to a text file on a device. Android comes in
with built in SQLite database implementation. SQLite supports all the relational database features. In
order to access this database, you don't need to establish any kind of connections for it like
JDBC,ODBC e.t.c

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
SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);
Database - Insertion
We can create tables or insert data into tables using the execSQL method defined in SQLiteDatabase
class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS Tbl_Login(Username VARCHAR,Password
VARCHAR);"); mydatabase.execSQL("INSERT INTO Tbl_Login VALUES('admin','admin');"); Database
- Fetching
We can retrieve anything from the database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to the
table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from Tbl_Login",null); resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
Database - Helper class
For managing all the operations related to the database , a helper class has been given and is called
SQLiteOpenHelper. It automatically manages the creation and update of the database. Its syntax is
given below public class DBHelper extends SQLiteOpenHelper { public DBHelper(){
super(context,DATABASE_NAME,null,1);
} public void onCreate(SQLiteDatabase db) {} public void onUpgrade(SQLiteDatabase database, int
oldVersion, int newVersion) {} }

Unit: 3 Exploring User Interface Screen Elements


3.1 Introducing Android Views, Layouts, TextView, Buttons, Check Boxes, Radio Groups, Indicators,
SeekBar, Context Menus, User Events, Styles and Themes, Dates and Times, Retrieving Data.
What is Android Views?
A View is a simple building block of a user interface. It is a small rectangular box that can be
TextView, EditText, or even a button. It occupies the area on the screen in a rectangular area and is
responsible for drawing and event handling. View is a superclass of all the graphical user interface
components.
The Android SDK has a Java package name android.view. This package contains a number of
interfaces and classes related to drawing on the screen. However, when we refer to the View object,
we actually refer to onl y one of the classes within this package: the android.view.View class. View is
the basic building block of UI (User Interface) in android. View refers to the android.view.View class,
which is the super class for all the GUI components like TextView, ImageView, Button etc. View class
extends Object class and Implements Drawable.Callback, KeyEvent.Callback and
AccessibilityEventSource.
The question that might be bothering you would be, what can be the size of this rectangle? The
answer is either we can set it manually, by specifying the exact size (with proper units) or by
using some predefined values. These predefined values are match_parent and wrap_content.
match_parent means it will occupy the complete space available on the display of the device.
Whereas, wrap_content means it will occupy only that much space as required for its content to
display.

ViewGroup
View Group is a subclass of the ViewClass and can be considered as a superclass of Layouts. It
provides an invisible co0ntainer to hold the views or layouts. ViewGroup instances and views work
together as a container for Layouts. To understand in simpler words it can be understood as a
special view that can hold other views that are often known as a child view.

The Android framework will allow us to use UI elements or widgets in two ways:
• Use UI elements in the XML file
• Create elements in the Kotlin file dynamically
Introducing Android Layouts
A layout defines the structure for a user interface in your app, such as in an activity. All elements in
the layout are built using a hierarchy of View and ViewGroup objects. A View usually draws
something the user can see and interact with. Whereas a ViewGroup is an invisible container that
defines the layout structure for View and other ViewGroup objects.
One special type of control found within the android.widget package is called a layout. A layout
control is still a View object, but it doesn’t actually draw anything specific on the screen. Instead, it is
a parent container for organizing other controls (children). Layout controls determine how and
where on the screen child controls are drawn. Each type of layout control draws its children using
particular rules. For instance, the LinearLayout control draws its child controls in a single horizontal
row or a single vertical column. Similarly, a TableLayout control displays each child control in tabular
format(in cells within specific rows and columns).
In “Designing User Interfaces with Layouts,” we organize various controls within layouts and other
containers. These special View controls, which are derived from the android.view.ViewGroup class,
are useful only after you understand the various display controls these containers can hold. By
necessity, we use some of the layout View objects within this chapter to illustrate how to use the
controls previously mentioned.
Types of Layouts
• Linear Layout
• Relative Layout
• Constraint Layout
• Table Layout
• Frame Layout
• List View
• Grid View
• Absolute Layout
• WebView
• ScrollView
• Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View
elements one by one either in a particular direction either horizontally or vertically based on
the orientation property.
• Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the
position of child View elements relative to each other like (A to the right of B) or relative to
the parent (fix to the top of the parent).
• Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to specify the
position of layout constraints for every child View relative to other views present. A
ConstraintLayout is similar to a RelativeLayout, but having more power.
• Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the position of
View elements it contains on the top of each other to display only a single View inside the
FrameLayout.
• Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child View
elements in rows and columns.
• Android Web View: WebView is a browser that is used to display the web pages in our
activity layout.
• Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in a single
column.
• Android Grid View: GridView is a ViewGroup that is used to display a scrollable list of items
in a grid view of rows and columns.

Layout params
This tutorial is more about creating your GUI based on layouts defined in XML file. A layout may
contain any type of widgets such as buttons, labels, textboxes, and so on. Following is a simple
example of XML file having LinearLayout −

Once your layout has created, you can load the layout resource from your application code, in your
Activity.onCreate() callback implementation as shown below −

Attributes of Layout in Android


The following are the attributes for customizing a Layout while defining it:
• android:id: It uniquely identifies the Android Layout.
• android:hint: It shows the hint of what to fill inside the EditText.
• android:layout_height: It sets the height of the layout.
• android:layout_width: It sets the width of the layout.
• android:layout_gravity: It sets the position of the child view.
• android:layout_marginTop: It sets the margin of the from the top of the layout.
• android:layout_marginBottom: It sets the margin of the from the bottom of the layout.
• android:layout_marginLeft: It sets the margin of the from the left of the layout.
• android:layout_marginRight: It sets the margin of the from the right of the layout.
• android:layout_x: It specifies the x coordinates of the layout. • android:layout_y: It
specifies the y coordinates of the layout.
Types of Android Views(Control,palette)
Another thing that might now come to your mind must be, “what are the available types of view in
Android that we can use?”
For that, we’ll see all these types one by one as follows:
• TextView
• EditText
• Button
• Image Button
• Date Picker
• RadioButton
• CheckBox buttons
• Image View

1).TextView :-
A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete
text editor, however the basic class is configured to not allow editing.
TextView Attributes
Attribute & Description android:id This is the ID
which uniquely identifies the control.
android:capitalize If set, specifies that this TextView has a textual input method and should
automatically capitalize what the user types. • Don't automatically capitalize anything - 0
• Capitalize the first word of each sentence - 1
• Capitalize the first letter of every word - 2 • Capitalize every character - 3
android:cursorVisible Makes the cursor visible (the default) or invisible. Default is
false. android:editable If set to true, specifies that this TextView has an input
method.
android:fontFamily Font family (named by string) for the text.
android:gravity Specifies how to align the text by the view's x- and/or y-axis when the text is smaller
than the view.
android:hint Hint text to display when the text is empty.
android:inputType The type of data being placed in a text field. Phone, Date, Time, Number,
Password etc.
android:password Whether the characters of the field are displayed as password dots instead
of themselves. Possible value either "true" or "false".
android:phoneNumber If set, specifies that this TextView has a phone number input method.
Possible value either "true" or "false". android:text Text to display. android:textAllCaps
Present the text in ALL CAPS. Possible value either "true" or "false". android:textSize
Size of the text. Recommended dimension type for text is "sp" for scaledpixels
(example: 15sp).
Example
MainActivity.java
package com.example.demo;

import android.os.Bundle; import android.app.Activity; import android.view.Menu; import


android.view.View; import android.widget.TextView; import android.widget.Toast;

public class MainActivity extends Activity {


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

//--- text view---


TextView txtView = (TextView) findViewById(R.id.text_id);
}
}

activity_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView android:id="@+id/text_id" android:layout_width="300dp"


android:layout_height="200dp" android:capitalize="characters" android:text="hello_world"
android:textColor="@android:color/holo_blue_dark"
android:textColorHighlight="@android:color/primary_text_dark"
android:layout_centerVertical="true" android:layout_alignParentEnd="true"
android:textSize="50dp"/>

</RelativeLayout>

2).EditText
A EditText is an overlay over TextView that configures itself to be editable. It is the predefined
subclass of TextView that includes rich editing capabilities.

Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method. android:text
This is the Text to display.
Inherited from android.view.View Class –

Attribute Description android:background This is a drawable to use as the


background. android:contentDescription This defines text that briefly describes
content of the view. android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke when the
view is clicked. android:visibility This controls the initial visibility of the view.

Example activity_main.xml file –

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" android:layout_marginLeft="14dp"
android:layout_marginTop="18dp" android:text="@string/example_edittext" />

<Button
android:id="@+id/button" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1" android:layout_marginTop="130dp"
android:text="@string/show_the_text" />
<EditText android:id="@+id/edittext" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1" android:layout_marginTop="61dp"
android:ems="10"
android:text="@string/enter_text" android:inputType="text" />
</RelativeLayout>

MainActivity.java file-

package com.example.demo; import android.os.Bundle; import android.app.Activity; import


android.view.View; import android.view.View.OnClickListener; import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


EditText eText;
Button btn; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);0 eText = (EditText) findViewById(R.id.edittext); btn =
(Button) findViewById(R.id.button); btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) { String str = eText.getText().toString();
Toast msg = Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG); msg.show();
}
});
}
}

3).Button:-
A Button is a Push-button which can be pressed, or clicked, by the user to perform an action.

Button Attributes
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom
This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text. android:editable
If set, specifies that this TextView has an input method.
android:text
This is the Text to display

Inherited from android.view.View Class –


android:background
This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke when the
view is clicked. android:visibility
This controls the initial visibility of the view.

Button Example

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:id="@+id/btn_next" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" android:layout_centerInParent="true"
android:layout_marginStart="172dp" android:layout_marginEnd="151dp"
android:text="NEXT" tools:layout_editor_absoluteX="149dp"
tools:layout_editor_absoluteY="80dp" android:onClick="btn_next"/>
<Button android:id="@+id/btn_previous" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@id/btn_next"
android:layout_alignParentEnd="true" android:layout_alignParentBottom="true"
android:layout_marginTop="67dp" android:layout_marginEnd="140dp"
android:layout_marginBottom="225dp" android:text="PREVIOUS"
android:onClick="btn_previous"/>
</RelativeLayout>

MainActivity.java

package com.example.exampleofbutton; 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 btn_next(View view) {
Toast.makeText(this,"Next Button Clicked", Toast.LENGTH_SHORT).show();
}

public void btn_previous(View view) {


Toast.makeText(this,"Previous Button Clicked", Toast.LENGTH_SHORT).show();
}
}

Example of TextView,EditText and Button

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:id="@+id/parentRelative"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center" tools:context=".MainActivity">

<EditText android:id="@+id/editTextName" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_below="@id/textviewname"
android:layout_marginTop="-249dp" android:ems="10" android:hint="Enter Your Name"
android:inputType="textPersonName" android:padding="20dp"
android:textColor="#F44336" />

<Button android:id="@+id/btnclickhere" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_below="@id/editTextName"
android:layout_marginTop="29dp" android:padding="20dp" android:text="ClickMe" />
<TextView
android:id="@+id/textviewname" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:padding="20dp" android:text="TextView"
/>
</RelativeLayout>

MainActivity.java

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


import android.os.Bundle; import android.view.View; import android.widget.Button; import
android.widget.EditText; import android.widget.TextView; import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText editTextName;
Button btnclickhere;
TextView textviewname;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName=(EditText)findViewById(R.id.editTextName);
btnclickhere=(Button)findViewById(R.id.btnclickhere);
textviewname=(TextView)findViewById(R.id.textviewname);
btnclickhere.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name=editTextName.getText().toString();
textviewname.setText("Hi"+name);

}
});
}
}

4). CheckBox:- Android CheckBox is a type of two state button either checked or unchecked.There
can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the user,
activate/deactivate the specific action etc.Android CheckBox class is the subclass of
CompoundButton class.
The android.widget.CheckBox class provides the facility of creating the CheckBoxes.
Method:-There are many inherited methods of View, TextView, and Button classes in the CheckBox
class. Some of them are as follows:
1).public boolean isChecked():-Returns true if it is checked otherwise false.
2).public void setChecked(boolean status):- Changes the state of the CheckBox.
CheckBox Attributes
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom
This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text. android:editable
If set, specifies that this TextView has an input method.
android:text
This is the Text to display Inherited
from android.view.View Class –
android:background
This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke when the
view is clicked. android:visibility
This controls the initial visibility of the view.
Example
MainActivity.java
package com.example.checkboxexample; import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import
android.widget.Toast; public class MainActivity extends AppCompatActivity {
CheckBox ch,ch1,ch2,ch3;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); ch=(CheckBox)findViewById(R.id.checkBox);
ch1=(CheckBox)findViewById(R.id.checkBox3); ch2=(CheckBox)findViewById(R.id.checkBox4);
ch3=(CheckBox)findViewById(R.id.checkBox5);
}
// This function is invoked when the button is pressed.
public void Check(View view) { /* Finding CheckBox by its unique ID */
String msg="";
// Concatenation of the checked options in if // isChecked() is used to check whether //
the CheckBox is in true state or not.
if(ch.isChecked()) msg = msg + " Painting "; if(ch1.isChecked()) msg = msg + "
Dancing "; if(ch2.isChecked()) msg = msg + " Reading "; if(ch3.isChecked()) msg
= msg + " Surfing ";
// Toast is created to display the // message using show() method.
Toast.makeText(this, msg+"Are Selected", Toast.LENGTH_LONG).show();
}
}

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">
<TextView android:layout_width="398dp" android:layout_height="wrap_content"
android:layout_marginStart="8dp" android:layout_marginTop="48dp"
android:layout_marginEnd="8dp" android:text="Choose your hobbies:"
android:textSize="24sp" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
<CheckBox android:id="@+id/checkBox" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="16dp"
android:text="Painting" android:textSize="18sp" />
<CheckBox android:id="@+id/checkBox3" android:layout_width="match_parent"
android:layout_height="37dp" android:text="Dancing" android:textSize="18sp" />
<CheckBox
android:id="@+id/checkBox4" android:layout_width="match_parent"
android:layout_height="37dp" android:text="Reading" android:textSize="18sp" />
<CheckBox android:id="@+id/checkBox5" android:layout_width="match_parent"
android:layout_height="37dp" android:text="Surfing" android:textSize="18sp" />
<Button android:id="@+id/button" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="16dp"
android:onClick="Check" android:text="@string/submit"/>
</LinearLayout>

5).Radio Group and Radio Button


RadioButton is a two states button which is either checked or unchecked. If a single radio button is
unchecked, we can click it to make checked radio button. Once a radio button is checked, it cannot
be marked as unchecked by user.
RadioButton is generally used with RadioGroup. RadioGroup contains several radio buttons, marking
one radio button as checked makes all other radio buttons as unchecked.
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" >

<TextView android:id="@+id/textView" android:layout_width="fill_parent"


android:layout_height="wrap_content" android:layout_marginTop="30dp"
android:gravity="center_horizontal" android:textSize="22dp"
android:text="Single Radio Buttons"/>
<!-- Default RadioButtons -->
<RadioButton android:id="@+id/radioButton1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_gravity="center_horizontal"
android:text="B.Com" android:layout_marginTop="20dp" android:textSize="20dp" />
<RadioButton android:id="@+id/radioButton2" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="B.C.A"
android:layout_marginTop="10dp" android:textSize="20dp" /> <RadioButton
android:id="@+id/radioButton3" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="B.B.A"
android:layout_marginTop="10dp" android:textSize="20dp" />

<View android:layout_width="fill_parent" android:layout_height="1dp"


android:layout_marginTop="20dp" android:background="#B8B894" />
<TextView android:id="@+id/textView2"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_marginTop="30dp" android:gravity="center_horizontal"
android:textSize="22dp" android:text="Radio button inside RadioGroup" />
<!-- Customized RadioButtons -->
<RadioGroup android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/radioGroup">
<RadioButton android:id="@+id/radioMale" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Male"
android:layout_marginTop="10dp" android:checked="false" android:textSize="20dp"
/> <RadioButton android:id="@+id/radioFemale"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text=" Female" android:layout_marginTop="20dp" android:checked="false"
android:textSize="20dp" />
</RadioGroup> <Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Show Selected"
android:id="@+id/button" android:onClick="onclickbuttonMethod"
android:layout_gravity="center_horizontal" /> </LinearLayout> MainActivity.java package
com.example.radiobuttondemo; 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 btn;
RadioButton genderradioButton;
RadioGroup rGroup; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rGroup=(RadioGroup)findViewById(R.id.radioGroup);
}
public void onclickbuttonMethod(View view) { int selectedId =
rGroup.getCheckedRadioButtonId(); genderradioButton = (RadioButton)
findViewById(selectedId);
// Toast.makeText(this, "genderradioButton", Toast.LENGTH_SHORT).show();
if(selectedId==-1) {
Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this,genderradioButton.getText(),
Toast.LENGTH_SHORT).show();
}
}
}

Indicators
The Android SDK provides a number of controls that can be used to visually show some form of
information to the user. These indicator controls include progress bars, clocks, and other similar
controls.
ProgressBars
Android ProgressBar is a graphical view indicator that shows some progress. Android progress bar
displays a bar representing the completing of the task. Progress bar in android is useful since it gives
the user an idea of time to finish its task.
Progress bars are used to show progress of a task. For example, when you are uploading or
downloading something from the internet, it is better to show the progress of download/upload to
the user.
Android ProgressBar attributes
Some important attributes used to describe a ProgressBar are given below.
• android:max : We can set the maximum value of the ProgressBar using this attribute. By
default the progress bar maximum value is 100
• android:indeterminate : A boolean value is set depending on whether the time is
determinate or not. Setting this attribute to false would show the actual progress. Else if it’s
set to true a cyclic animation is displayed to show that progress is happening •
android:minHeight :
It’s used to set the height of the ProgressBar
• android:minWidth : It’s used to set the width of the ProgressBar
• android:progress : It’s used to set the number by which the progress bar value will be
incremented
• style : By default the progress bar will be displayed as a spinning wheel. If we want it to be
displayed as a horizontal bar, we need to set the attribute as :
style=”?android:attr/progressBarStyleHorizontal”
Method
1).getMax():-This method returns the maximum value of the progress.
2). incrementProgressBy(int diff):-This method increments the progress bar by the difference of
value passed as a parameter.
3). setIndeterminate(boolean indeterminate):-This method sets the progress indicator as
determinate or indeterminate.
4). setMax(int max):-This method sets the maximum value of the progress dialog.
5). setProgress(int value):-This method is used to update the progress dialog with some specific
value.
6). show(Context context, CharSequence title, CharSequence message):-This is a static method, used
to display progress dialog.
Example
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">
<ProgressBar
android:id="@+id/simpleProgressBar" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:layout_centerHorizontal="true"/> <Button
android:id="@+id/startButton" android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Start" android:textSize="20sp" android:textStyle="bold"
android:layout_centerHorizontal="true" android:layout_marginTop="100dp"
android:padding="10dp" android:background="#0f0" android:textColor="#fff"/>
</RelativeLayout> Mainactivity.java
package com.example.textviewdemo; import androidx.appcompat.app.AppCompatActivity; import
android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import
android.view.View; import android.widget.Button; import android.widget.ProgressBar; public
class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // initiate progress bar and start button
final ProgressBar simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar);
Button startButton = (Button) findViewById(R.id.startButton);
// perform click event on button
startButton.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { // visible the progress bar
simpleProgressBar.setVisibility(View.VISIBLE);
}
});
}
}

SeekBar:-
Android SeekBar is a type of ProgressBar. On touching the thumb on seekbar and dragging it to the
right or left, the current value of the progress changes. SeekBar is used for forwarding or
backwarding the songs, Video etc. In the setOnSeekBarChangeListener interface is used which
provides three methods.
• onProgressChanged: In this method progress is changed and then according to this change
the progress value can used in our logic.
• onStartTrackingTouch: In this method when the user has started dragging, then this method
will be called automatically.
• onStopTrackingTouch: In this method, when the user stops dragging, then this method will
called automatically. Example
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">

<TextView
android:id="@+id/textView" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true" android:layout_marginEnd="180dp"
android:layout_marginBottom="460dp" android:text="Example of Seekbar" />

<SeekBar
android:id="@+id/seekBar" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginEnd="8dp"
android:layout_marginStart="8dp" android:layout_marginTop="372dp"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="#0F0"/><!-- set green color in the background of seek bar-->
</RelativeLayout> MainActivity.java
package com.example.seekbarexample; import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color; import android.os.Bundle; import android.widget.SeekBar;
import android.widget.TextView; import android.widget.Toast; public class MainActivity extends
AppCompatActivity {
// Define the global variable
SeekBar seekbar;
TextView Text_message;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// use findViewById() to get the Button
Text_message= (TextView)findViewById(R.id.textView); seekbar=
(SeekBar)findViewById(R.id.seekBar); //SeekBar.setBackgroundColor(Color.GREEN);
seekbar.setBackgroundColor(Color.GREEN);// green background color for the seek bar
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
Toast.makeText(getApplicationContext(),"seekbar progress: "+progress,
Toast.LENGTH_SHORT).show();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch started!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch stopped!",
Toast.LENGTH_SHORT).show();
}
});
}
}

Context menus:-
In Android, the context menu is like a floating menu and arises when the user has long
pressed or clicks on an item and is beneficial for implementing functions that define the specific
content or reference frame effect. The Android context menu is similar to the right-click menu in
Windows or Linux. In the Android system, the context menu provides actions that change a specific
element or context frame in the user interface and one can provide a context menu for any view.
The context menu will not support any object shortcuts and object icons. Note that we are going to
implement this project using the Java language.
Example
Step 1: Create a New Project
Step 2: Working with the activity_main.xml file Open res -> Layout -> activity_main.xml and write the
following code. In this file add only a TextView to display a simple text.

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">
<TextView
android:id="@+id/textView" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" android:text="Long press me!" android:textColor="#000"
android:textSize="20sp" android:textStyle="bold" />
</RelativeLayout>

Step 3: Working with the Mainactivity.java file Open the app -> Java -> Package -> Mainactivity.java
file. In this step, add the code to show the ContextMenu. Whenever the app will start make a long
click on a text and display the number of options to select them for specific purposes.

MainActivity.java

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


import android.graphics.Color; import android.os.Bundle; import android.view.ContextMenu;
import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Link those objects with their respective id's
// that we have given in .XML file
textView = (TextView) findViewById(R.id.textView);
relativeLayout = (RelativeLayout) findViewById(R.id.relLayout);
// here you have to register a view for context menu
// you can register any view like listview, image view,
// textview, button etc
registerForContextMenu(textView);
}
@Override public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// you can set menu header with title icon etc menu.setHeaderTitle("Choose a color");
// add menu items
menu.add(0, v.getId(), 0, "Yellow"); menu.add(0, v.getId(), 0, "Gray");
menu.add(0, v.getId(), 0, "Cyan");
}
// menu item select listener
@Override
public boolean onContextItemSelected(MenuItem item) { if (item.getTitle() == "Yellow") {
relativeLayout.setBackgroundColor(Color.YELLOW);
} else if (item.getTitle() == "Gray") {
relativeLayout.setBackgroundColor(Color.GRAY);
} else if (item.getTitle() == "Cyan") {
relativeLayout.setBackgroundColor(Color.CYAN);
}
return true;
}
}

User Event

Events are a useful way to collect data about a user's interaction with interactive components of
Applications. Like button presses or screen touch etc. The Android framework maintains an event
queue as a first-in, first-out (FIFO) basis. You can capture these events in your program and take
appropriate action as per requirements.

There are following three concepts related to Android Event Management –


● Event Listeners − An event listener is an interface in the View class that contains a single
callback method. These methods will be called by the Android framework when the View to which
the listener has been registered is triggered by user interaction with the item in the UI.
● Event Listeners Registration − Event Registration is the process by which an Event Handler
gets registered with an Event Listener so that the handler is called when the Event Listener fires the
event.
● Event Handlers − When an event happens and we have registered an event listener for the
event, the event listener calls the Event Handlers, which is the method that actually handles the
event.
Event Listeners & Event Handlers
Event Handler Event Listener & Description onClick()
OnClickListener()
This is called when the user either clicks or touches or focuses upon any widget like button, text,
image etc. You will use onClick() event handler to handle such event.
onLongClick() OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget like button, text,
image etc. for one or more seconds. You will use onLongClick() event handler to handle such event.
onFocusChange() OnFocusChangeListener()
This is called when the widget loses its focus ie. user goes away from the view item. You will use the
onFocusChange() event handler to handle such an event.
onKey() OnFocusChangeListener()
This is called when the user is focused on the item and presses or releases a hardware key on the
device. You will use onKey() event handler to handle such an event.
onTouch() OnTouchListener()
This is called when the user presses the key, releases the key, or any movement gesture on the
screen. You will use onTouch() event handler to handle such event.
onMenuItemClick() OnMenuItemClickListener()
This is called when the user selects a menu item. You will use onMenuItemClick() event handler to
handle such event.
onCreateContextMenu() onCreateContextMenuItemListener()
This is called when the context menu is being built(as the result of a sustained "long click)

Event Listeners Registration


Event Registration is the process by which an Event Handler gets registered with an Event
Listener so that the handler is called when the Event Listener fires the event. Though there are
several tricky ways to register your event listener for any event, I'm going to list down only top 3
ways, out of which you can use any of them based on the situation.
● Using an Anonymous Inner Class
● Activity class implements the Listener interface.
● Using Layout file activity_main.xml to specify event handler directly.

Touch Mode
Users can interact with their devices by using hardware keys or buttons or touching the
screen.Touching the screen puts the device into touch mode. The user can then interact with it by
touching the on-screen virtual buttons, images, etc.You can check if the device is in touch mode by
calling the View class's InTouchMode() method.

Focus
A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This
indicates that it’s ready to accept input from the user.
● isFocusable() − it returns true or false
● isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A view
may be focusable when using a hardware key but not when the device is in touch mode)

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


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

android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >

android:layout_height="wrap_content" android:text="Click Event"


android:layout_marginTop="200dp" android:layout_marginLeft="130dp"/>

android:id="@+id/txtResult" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp"
android:textColor="#86AD33" android:textSize="20dp"
android:textStyle="bold" android:layout_marginTop="12dp"/> </LinearLayout>
MainActivity.java
package com.tutlane.inputeventsexample; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.view.View; import android.widget.Button; import
android.widget.TextView;

public class MainActivity extends AppCompatActivity { Button btn;


TextView tView; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); btn = (Button)findViewById(R.id.btnClick); tView =
(TextView)findViewById(R.id.txtResult); btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

tView.setText("You Clicked On Button");


}
});
}
}
Styles and Themes
A style resource defines the format and looks for a UI. A style can be applied to an individual
View (from within a layout file) or to an entire Activity or application (from within the manifest file).
Defining Styles
A style is defined in an XML resource that is separate from the XML that specifies the layout. This
XML file resides under the res/values/ directory of your project and will have as the root node which
is mandatory for the style file. The name of the XML file is arbitrary, but it must use the .xml
extension.
You can define multiple styles per file using tag as shown below – <?xml
version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomFontStyle">

<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>

<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>

<item name="android:textColor">#00FF00</item>/>
</style>
</resources>
Using Styles Once your style is defined, you can use it in your XML Layout file using style attribute as
follows –

Theme is a style that is applied to an entire activity or app, instead of an individual View like as
mentioned above. When we applied a style as a theme, the views in activity or app apply to the all
style attributes that supports. For example. If we apply TextviewStyle as a theme for an activity, then
the text of all the views in activity appears in the same style.
Following is the example of defining a theme in the android application.
<color name="custom_theme_color">#b0b0ff</color>
<style name="CustomTheme" parent="Theme.AppCompat.Light">
<item name="android:windowBackground">@color/custom_theme_color</item>
<item name="android:colorBackground">@color/custom_theme_color</item> </style> The
above code overrides windowBackground and colorBackground properties of
Theme.AppCompat.Light theme.
To set a theme for a particular activity, open AndroidManifest.xml file and write the code like as
shown below
<activity android:theme="@android:style/CustomTheme">
In case, if we want to set the theme for all the activities in android application, open
AndroidManifest.xml file and write the code like as shown below.
<application android:theme="@android:style/CustomTheme">
Android Styling Color Palette
In android, we can customize the application basic theme colors based on our requirements.
Following is the example of basic material design in the android application.

Generally, the above layout defined in styles.xml file like as shown below and it resides in res/values
folder.
<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>
We can customize the application basic theme colors based on our requirements. Now we will see
how to use these styles and themes in android applications with examples.
Android Styles and Themes Example
Following is the example of defining a custom style for controls in LinearLayout to apply different
styles for controls in the android application.
Create a new android application using android studio and give names as StylesThemesExample. In
case if you are not aware of creating an app in android studio check this article Android Hello World
App.
Now we need to define our styles in styles.xml file, for that open styles.xml file from \res\values
folder and write the code like as shown below.
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="TextviewStyle" parent="@android:style/Widget.TextView">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">100dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textColor">#86AD33</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">20dp</item>
</style>
<style name="ButtonStyle" parent="@android:style/Widget.Button">
<item name="android:layout_width">200dp</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">100dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android:background">#F1511B</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">15dp</item>
</style>
<string name="wlcmsg">welcome </string> </resources>
If you observe above code, we defined a two styles (TextViewStyle, ButtonStyle) and we can apply
these styles for required controls in android application.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="@+id/TextView1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp"
android:layout_marginTop="200dp" android:textColor="#00ADEF" android:textSize="15dp"
android:text="@string/wlcmsg"/>
<TextView
android:id="@+id/TextView2" style="@style/TextviewStyle" android:text="Welcome to
Tutlane"/>
<Button android:id="@+id/btnShow" android:text="Click on Button"
style="@style/ButtonStyle" /> </LinearLayout>
If you observe above code we are referring our styles to required controls using style attribute.
Dates and Times
Date and Time in Android are formatted using the SimpleDateFormat library from Java, using
Calendar instance which helps to get the current system date and time. The current date and time
are of the type Long which can be converted to a human-readable date and time. In this article, it’s
been discussed how the Date and Time values can be formatted in various formats and displayed.
Have a look at the following image to get an idea of the entire discussion.

Steps to Format the Date and Time in Android


Step 1: Create an empty activity project
• Using Android Studio create an empty activity project. Refer to Android | How to
Create/Start a New Project in Android Studio?
Step 2: Working with the activity_main.xml file
• The main layout of the activity file containing 8 TextViews. One to show the current system
date and time value in Long type, and others to display the same date and time value in a
formatted human-readable way.
• To implement the UI invoke the following code inside the activity_main.xml file.
Activity_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:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity"
tools:ignore="HardcodedText">

<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="32dp"
android:text="Date and Time value in Long type :" android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" /> <!--text view to show the current date and
time in Long type-->
<TextView android:id="@+id/dateTimeLongValue"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="64dp"
android:textSize="18sp" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView android:id="@+id/textView" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="64dp" android:text="Date and Time formatted :"
android:textSize="18sp" android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/dateTimeLongValue" />

<!--text views to show the current date and time in formatted and human readable way-->
<TextView android:id="@+id/format1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<TextView android:id="@+id/format2" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format1" />
<TextView android:id="@+id/format3" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format2" />

<TextView android:id="@+id/format4" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format3" />

<TextView
android:id="@+id/format5" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format4" />

<TextView
android:id="@+id/format6" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format5" /> <TextView
android:id="@+id/format7" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format6" />

</androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Working with the MainActivity file
Understanding the way of formatting the date and time in Android using SimpleDateFormat •
Firstly, the instance of the Calendar is created and the desired format of the date and time
to be shown is passed to the SimpleDateFormat method. The String should include the following
characters and one may include the separators like -, / etc.
• The below table includes the characters to be used to generate the most used common
pattern of date and time.
Character to be used Output
dd Date in numeric value
E Day in String (short form. Ex: Mon)
EEEE Day in String (full form. Ex: Monday)
MM Month in numeric value
yyyy Year in numeric value
LLL Month in String (short form. Ex: Mar)
LLLL Month in String (full form. Ex: March)
HH Hour in numeric value (24hrs timing format)

import androidx.appcompat.app.AppCompatActivity; import java.text.SimpleDateFormat; import


java.util.Calendar;

public class MainActivity extends AppCompatActivity {

TextView dateTimeInLongTextView, format1, format2, format3, format4, format5,


format6, format7;

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

String dateTime;
Calendar calendar;
SimpleDateFormat simpleDateFormat;

// register all the text view with appropriate IDs


dateTimeInLongTextView = (TextView) findViewById(R.id.dateTimeLongValue);
format1 = (TextView) findViewById(R.id.format1); format2 = (TextView)
findViewById(R.id.format2); format3 = (TextView) findViewById(R.id.format3); format4 =
(TextView) findViewById(R.id.format4); format5 = (TextView) findViewById(R.id.format5);
format6 = (TextView) findViewById(R.id.format6); format7 = (TextView)
findViewById(R.id.format7);

// get the Long type value of the current system date Long dateValueInLong =
System.currentTimeMillis();
dateTimeInLongTextView.setText(dateValueInLong.toString());

// different format type to format the


// current date and time of the system
// format type 1
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format1.setText(dateTime);

// format type 2
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format2.setText(dateTime);

// format type 3
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format3.setText(dateTime);

// format type 4
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.LLL.yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format4.setText(dateTime);

// format type 5
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.LLLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format5.setText(dateTime);

// format type 6
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("E.LLLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format6.setText(dateTime);

// format type 7
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("EEEE.LLLL.yyyy KK:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format7.setText(dateTime);
}
}
Retrieving Data
SQLite is an open source SQL database that stores data to a text file on a device. Android comes in
with built in SQLite database implementation. SQLite supports all the relational database features. In
order to access this database, you don't need to establish any kind of connections for it like
JDBC,ODBC e.t.c

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
SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);
Database - Insertion
We can create tables or insert data into tables using the execSQL method defined in SQLiteDatabase
class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS Tbl_Login(Username VARCHAR,Password
VARCHAR);"); mydatabase.execSQL("INSERT INTO Tbl_Login VALUES('admin','admin');"); Database
- Fetching
We can retrieve anything from the database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to the
table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from Tbl_Login",null); resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
Database - Helper class
For managing all the operations related to the database , a helper class has been given and is called
SQLiteOpenHelper. It automatically manages the creation and update of the database. Its syntax is
given below public class DBHelper extends SQLiteOpenHelper { public DBHelper(){
super(context,DATABASE_NAME,null,1);
} public void onCreate(SQLiteDatabase db) {} public void onUpgrade(SQLiteDatabase database, int
oldVersion, int newVersion) {} }

Unit: 3 Exploring User Interface Screen Elements


3.1 Introducing Android Views, Layouts, TextView, Buttons, Check Boxes, Radio Groups, Indicators,
SeekBar, Context Menus, User Events, Styles and Themes, Dates and Times, Retrieving Data.
What is Android Views?
A View is a simple building block of a user interface. It is a small rectangular box that can be
TextView, EditText, or even a button. It occupies the area on the screen in a rectangular area and is
responsible for drawing and event handling. View is a superclass of all the graphical user interface
components.
The Android SDK has a Java package name android.view. This package contains a number of
interfaces and classes related to drawing on the screen. However, when we refer to the View object,
we actually refer to onl y one of the classes within this package: the android.view.View class. View is
the basic building block of UI (User Interface) in android. View refers to the android.view.View class,
which is the super class for all the GUI components like TextView, ImageView, Button etc. View class
extends Object class and Implements Drawable.Callback, KeyEvent.Callback and
AccessibilityEventSource.
The question that might be bothering you would be, what can be the size of this rectangle? The
answer is either we can set it manually, by specifying the exact size (with proper units) or by
using some predefined values. These predefined values are match_parent and wrap_content.
match_parent means it will occupy the complete space available on the display of the device.
Whereas, wrap_content means it will occupy only that much space as required for its content to
display.

ViewGroup
View Group is a subclass of the ViewClass and can be considered as a superclass of Layouts. It
provides an invisible co0ntainer to hold the views or layouts. ViewGroup instances and views work
together as a container for Layouts. To understand in simpler words it can be understood as a
special view that can hold other views that are often known as a child view.

The Android framework will allow us to use UI elements or widgets in two ways:
• Use UI elements in the XML file
• Create elements in the Kotlin file dynamically
Introducing Android Layouts
A layout defines the structure for a user interface in your app, such as in an activity. All elements in
the layout are built using a hierarchy of View and ViewGroup objects. A View usually draws
something the user can see and interact with. Whereas a ViewGroup is an invisible container that
defines the layout structure for View and other ViewGroup objects.
One special type of control found within the android.widget package is called a layout. A layout
control is still a View object, but it doesn’t actually draw anything specific on the screen. Instead, it is
a parent container for organizing other controls (children). Layout controls determine how and
where on the screen child controls are drawn. Each type of layout control draws its children using
particular rules. For instance, the LinearLayout control draws its child controls in a single horizontal
row or a single vertical column. Similarly, a TableLayout control displays each child control in tabular
format(in cells within specific rows and columns).
In “Designing User Interfaces with Layouts,” we organize various controls within layouts and other
containers. These special View controls, which are derived from the android.view.ViewGroup class,
are useful only after you understand the various display controls these containers can hold. By
necessity, we use some of the layout View objects within this chapter to illustrate how to use the
controls previously mentioned.
Types of Layouts
• Linear Layout
• Relative Layout
• Constraint Layout
• Table Layout
• Frame Layout
• List View
• Grid View
• Absolute Layout
• WebView
• ScrollView
• Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View
elements one by one either in a particular direction either horizontally or vertically based on
the orientation property.
• Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the
position of child View elements relative to each other like (A to the right of B) or relative to
the parent (fix to the top of the parent).
• Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to specify the
position of layout constraints for every child View relative to other views present. A
ConstraintLayout is similar to a RelativeLayout, but having more power.
• Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the position of
View elements it contains on the top of each other to display only a single View inside the
FrameLayout.
• Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child View
elements in rows and columns.
• Android Web View: WebView is a browser that is used to display the web pages in our
activity layout.
• Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in a single
column.
• Android Grid View: GridView is a ViewGroup that is used to display a scrollable list of items
in a grid view of rows and columns.

Layout params
This tutorial is more about creating your GUI based on layouts defined in XML file. A layout may
contain any type of widgets such as buttons, labels, textboxes, and so on. Following is a simple
example of XML file having LinearLayout −

Once your layout has created, you can load the layout resource from your application code, in your
Activity.onCreate() callback implementation as shown below −

Attributes of Layout in Android


The following are the attributes for customizing a Layout while defining it:
• android:id: It uniquely identifies the Android Layout.
• android:hint: It shows the hint of what to fill inside the EditText.
• android:layout_height: It sets the height of the layout.
• android:layout_width: It sets the width of the layout.
• android:layout_gravity: It sets the position of the child view.
• android:layout_marginTop: It sets the margin of the from the top of the layout.
• android:layout_marginBottom: It sets the margin of the from the bottom of the layout.
• android:layout_marginLeft: It sets the margin of the from the left of the layout.
• android:layout_marginRight: It sets the margin of the from the right of the layout.
• android:layout_x: It specifies the x coordinates of the layout. • android:layout_y: It
specifies the y coordinates of the layout.
Types of Android Views(Control,palette)
Another thing that might now come to your mind must be, “what are the available types of view in
Android that we can use?”
For that, we’ll see all these types one by one as follows:
• TextView
• EditText
• Button
• Image Button
• Date Picker
• RadioButton
• CheckBox buttons
• Image View

1).TextView :-
A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete
text editor, however the basic class is configured to not allow editing.
TextView Attributes
Attribute & Description android:id This is the ID
which uniquely identifies the control.
android:capitalize If set, specifies that this TextView has a textual input method and should
automatically capitalize what the user types. • Don't automatically capitalize anything - 0
• Capitalize the first word of each sentence - 1
• Capitalize the first letter of every word - 2 • Capitalize every character - 3
android:cursorVisible Makes the cursor visible (the default) or invisible. Default is
false. android:editable If set to true, specifies that this TextView has an input
method.
android:fontFamily Font family (named by string) for the text.
android:gravity Specifies how to align the text by the view's x- and/or y-axis when the text is smaller
than the view.
android:hint Hint text to display when the text is empty.
android:inputType The type of data being placed in a text field. Phone, Date, Time, Number,
Password etc.
android:password Whether the characters of the field are displayed as password dots instead
of themselves. Possible value either "true" or "false".
android:phoneNumber If set, specifies that this TextView has a phone number input method.
Possible value either "true" or "false". android:text Text to display. android:textAllCaps
Present the text in ALL CAPS. Possible value either "true" or "false". android:textSize
Size of the text. Recommended dimension type for text is "sp" for scaledpixels
(example: 15sp).
Example
MainActivity.java
package com.example.demo;

import android.os.Bundle; import android.app.Activity; import android.view.Menu; import


android.view.View; import android.widget.TextView; import android.widget.Toast;

public class MainActivity extends Activity {


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

//--- text view---


TextView txtView = (TextView) findViewById(R.id.text_id);
}
}

activity_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView android:id="@+id/text_id" android:layout_width="300dp"


android:layout_height="200dp" android:capitalize="characters" android:text="hello_world"
android:textColor="@android:color/holo_blue_dark"
android:textColorHighlight="@android:color/primary_text_dark"
android:layout_centerVertical="true" android:layout_alignParentEnd="true"
android:textSize="50dp"/>

</RelativeLayout>

2).EditText
A EditText is an overlay over TextView that configures itself to be editable. It is the predefined
subclass of TextView that includes rich editing capabilities.

Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method. android:text
This is the Text to display.
Inherited from android.view.View Class –

Attribute Description android:background This is a drawable to use as the


background. android:contentDescription This defines text that briefly describes
content of the view. android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke when the
view is clicked. android:visibility This controls the initial visibility of the view.

Example activity_main.xml file –

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" android:layout_marginLeft="14dp"
android:layout_marginTop="18dp" android:text="@string/example_edittext" />

<Button
android:id="@+id/button" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1" android:layout_marginTop="130dp"
android:text="@string/show_the_text" />
<EditText android:id="@+id/edittext" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1" android:layout_marginTop="61dp"
android:ems="10"
android:text="@string/enter_text" android:inputType="text" />
</RelativeLayout>

MainActivity.java file-

package com.example.demo; import android.os.Bundle; import android.app.Activity; import


android.view.View; import android.view.View.OnClickListener; import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


EditText eText;
Button btn; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);0 eText = (EditText) findViewById(R.id.edittext); btn =
(Button) findViewById(R.id.button); btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) { String str = eText.getText().toString();
Toast msg = Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG); msg.show();
}
});
}
}

3).Button:-
A Button is a Push-button which can be pressed, or clicked, by the user to perform an action.

Button Attributes
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom
This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text. android:editable
If set, specifies that this TextView has an input method.
android:text
This is the Text to display

Inherited from android.view.View Class –


android:background
This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke when the
view is clicked. android:visibility
This controls the initial visibility of the view.

Button Example

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:id="@+id/btn_next" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" android:layout_centerInParent="true"
android:layout_marginStart="172dp" android:layout_marginEnd="151dp"
android:text="NEXT" tools:layout_editor_absoluteX="149dp"
tools:layout_editor_absoluteY="80dp" android:onClick="btn_next"/>
<Button android:id="@+id/btn_previous" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@id/btn_next"
android:layout_alignParentEnd="true" android:layout_alignParentBottom="true"
android:layout_marginTop="67dp" android:layout_marginEnd="140dp"
android:layout_marginBottom="225dp" android:text="PREVIOUS"
android:onClick="btn_previous"/>
</RelativeLayout>

MainActivity.java

package com.example.exampleofbutton; 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 btn_next(View view) {
Toast.makeText(this,"Next Button Clicked", Toast.LENGTH_SHORT).show();
}

public void btn_previous(View view) {


Toast.makeText(this,"Previous Button Clicked", Toast.LENGTH_SHORT).show();
}
}

Example of TextView,EditText and Button

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:id="@+id/parentRelative"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center" tools:context=".MainActivity">

<EditText android:id="@+id/editTextName" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_below="@id/textviewname"
android:layout_marginTop="-249dp" android:ems="10" android:hint="Enter Your Name"
android:inputType="textPersonName" android:padding="20dp"
android:textColor="#F44336" />

<Button android:id="@+id/btnclickhere" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_below="@id/editTextName"
android:layout_marginTop="29dp" android:padding="20dp" android:text="ClickMe" />
<TextView
android:id="@+id/textviewname" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:padding="20dp" android:text="TextView"
/>
</RelativeLayout>

MainActivity.java

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


import android.os.Bundle; import android.view.View; import android.widget.Button; import
android.widget.EditText; import android.widget.TextView; import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText editTextName;
Button btnclickhere;
TextView textviewname;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName=(EditText)findViewById(R.id.editTextName);
btnclickhere=(Button)findViewById(R.id.btnclickhere);
textviewname=(TextView)findViewById(R.id.textviewname);
btnclickhere.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name=editTextName.getText().toString();
textviewname.setText("Hi"+name);

}
});
}
}

4). CheckBox:- Android CheckBox is a type of two state button either checked or unchecked.There
can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the user,
activate/deactivate the specific action etc.Android CheckBox class is the subclass of
CompoundButton class.
The android.widget.CheckBox class provides the facility of creating the CheckBoxes.
Method:-There are many inherited methods of View, TextView, and Button classes in the CheckBox
class. Some of them are as follows:
1).public boolean isChecked():-Returns true if it is checked otherwise false.
2).public void setChecked(boolean status):- Changes the state of the CheckBox.
CheckBox Attributes
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom
This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text. android:editable
If set, specifies that this TextView has an input method.
android:text
This is the Text to display Inherited
from android.view.View Class –
android:background
This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke when the
view is clicked. android:visibility
This controls the initial visibility of the view.
Example
MainActivity.java
package com.example.checkboxexample; import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import
android.widget.Toast; public class MainActivity extends AppCompatActivity {
CheckBox ch,ch1,ch2,ch3;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); ch=(CheckBox)findViewById(R.id.checkBox);
ch1=(CheckBox)findViewById(R.id.checkBox3); ch2=(CheckBox)findViewById(R.id.checkBox4);
ch3=(CheckBox)findViewById(R.id.checkBox5);
}
// This function is invoked when the button is pressed.
public void Check(View view) { /* Finding CheckBox by its unique ID */
String msg="";
// Concatenation of the checked options in if // isChecked() is used to check whether //
the CheckBox is in true state or not.
if(ch.isChecked()) msg = msg + " Painting "; if(ch1.isChecked()) msg = msg + "
Dancing "; if(ch2.isChecked()) msg = msg + " Reading "; if(ch3.isChecked()) msg
= msg + " Surfing ";
// Toast is created to display the // message using show() method.
Toast.makeText(this, msg+"Are Selected", Toast.LENGTH_LONG).show();
}
}

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">
<TextView android:layout_width="398dp" android:layout_height="wrap_content"
android:layout_marginStart="8dp" android:layout_marginTop="48dp"
android:layout_marginEnd="8dp" android:text="Choose your hobbies:"
android:textSize="24sp" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
<CheckBox android:id="@+id/checkBox" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="16dp"
android:text="Painting" android:textSize="18sp" />
<CheckBox android:id="@+id/checkBox3" android:layout_width="match_parent"
android:layout_height="37dp" android:text="Dancing" android:textSize="18sp" />
<CheckBox
android:id="@+id/checkBox4" android:layout_width="match_parent"
android:layout_height="37dp" android:text="Reading" android:textSize="18sp" />
<CheckBox android:id="@+id/checkBox5" android:layout_width="match_parent"
android:layout_height="37dp" android:text="Surfing" android:textSize="18sp" />
<Button android:id="@+id/button" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginTop="16dp"
android:onClick="Check" android:text="@string/submit"/>
</LinearLayout>

5).Radio Group and Radio Button


RadioButton is a two states button which is either checked or unchecked. If a single radio button is
unchecked, we can click it to make checked radio button. Once a radio button is checked, it cannot
be marked as unchecked by user.
RadioButton is generally used with RadioGroup. RadioGroup contains several radio buttons, marking
one radio button as checked makes all other radio buttons as unchecked.
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" >

<TextView android:id="@+id/textView" android:layout_width="fill_parent"


android:layout_height="wrap_content" android:layout_marginTop="30dp"
android:gravity="center_horizontal" android:textSize="22dp"
android:text="Single Radio Buttons"/>
<!-- Default RadioButtons -->
<RadioButton android:id="@+id/radioButton1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_gravity="center_horizontal"
android:text="B.Com" android:layout_marginTop="20dp" android:textSize="20dp" />
<RadioButton android:id="@+id/radioButton2" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="B.C.A"
android:layout_marginTop="10dp" android:textSize="20dp" /> <RadioButton
android:id="@+id/radioButton3" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="B.B.A"
android:layout_marginTop="10dp" android:textSize="20dp" />

<View android:layout_width="fill_parent" android:layout_height="1dp"


android:layout_marginTop="20dp" android:background="#B8B894" />
<TextView android:id="@+id/textView2"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_marginTop="30dp" android:gravity="center_horizontal"
android:textSize="22dp" android:text="Radio button inside RadioGroup" />
<!-- Customized RadioButtons -->
<RadioGroup android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/radioGroup">
<RadioButton android:id="@+id/radioMale" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Male"
android:layout_marginTop="10dp" android:checked="false" android:textSize="20dp"
/> <RadioButton android:id="@+id/radioFemale"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text=" Female" android:layout_marginTop="20dp" android:checked="false"
android:textSize="20dp" />
</RadioGroup> <Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Show Selected"
android:id="@+id/button" android:onClick="onclickbuttonMethod"
android:layout_gravity="center_horizontal" /> </LinearLayout> MainActivity.java package
com.example.radiobuttondemo; 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 btn;
RadioButton genderradioButton;
RadioGroup rGroup; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rGroup=(RadioGroup)findViewById(R.id.radioGroup);
}
public void onclickbuttonMethod(View view) { int selectedId =
rGroup.getCheckedRadioButtonId(); genderradioButton = (RadioButton)
findViewById(selectedId);
// Toast.makeText(this, "genderradioButton", Toast.LENGTH_SHORT).show();
if(selectedId==-1) {
Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this,genderradioButton.getText(),
Toast.LENGTH_SHORT).show();
}
}
}

Indicators
The Android SDK provides a number of controls that can be used to visually show some form of
information to the user. These indicator controls include progress bars, clocks, and other similar
controls.
ProgressBars
Android ProgressBar is a graphical view indicator that shows some progress. Android progress bar
displays a bar representing the completing of the task. Progress bar in android is useful since it gives
the user an idea of time to finish its task.
Progress bars are used to show progress of a task. For example, when you are uploading or
downloading something from the internet, it is better to show the progress of download/upload to
the user.
Android ProgressBar attributes
Some important attributes used to describe a ProgressBar are given below.
• android:max : We can set the maximum value of the ProgressBar using this attribute. By
default the progress bar maximum value is 100
• android:indeterminate : A boolean value is set depending on whether the time is
determinate or not. Setting this attribute to false would show the actual progress. Else if it’s
set to true a cyclic animation is displayed to show that progress is happening •
android:minHeight :
It’s used to set the height of the ProgressBar
• android:minWidth : It’s used to set the width of the ProgressBar
• android:progress : It’s used to set the number by which the progress bar value will be
incremented
• style : By default the progress bar will be displayed as a spinning wheel. If we want it to be
displayed as a horizontal bar, we need to set the attribute as :
style=”?android:attr/progressBarStyleHorizontal”
Method
1).getMax():-This method returns the maximum value of the progress.
2). incrementProgressBy(int diff):-This method increments the progress bar by the difference of
value passed as a parameter.
3). setIndeterminate(boolean indeterminate):-This method sets the progress indicator as
determinate or indeterminate.
4). setMax(int max):-This method sets the maximum value of the progress dialog.
5). setProgress(int value):-This method is used to update the progress dialog with some specific
value.
6). show(Context context, CharSequence title, CharSequence message):-This is a static method, used
to display progress dialog.
Example
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">
<ProgressBar
android:id="@+id/simpleProgressBar" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:layout_centerHorizontal="true"/> <Button
android:id="@+id/startButton" android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Start" android:textSize="20sp" android:textStyle="bold"
android:layout_centerHorizontal="true" android:layout_marginTop="100dp"
android:padding="10dp" android:background="#0f0" android:textColor="#fff"/>
</RelativeLayout> Mainactivity.java
package com.example.textviewdemo; import androidx.appcompat.app.AppCompatActivity; import
android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import
android.view.View; import android.widget.Button; import android.widget.ProgressBar; public
class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // initiate progress bar and start button
final ProgressBar simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar);
Button startButton = (Button) findViewById(R.id.startButton);
// perform click event on button
startButton.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { // visible the progress bar
simpleProgressBar.setVisibility(View.VISIBLE);
}
});
}
}

SeekBar:-
Android SeekBar is a type of ProgressBar. On touching the thumb on seekbar and dragging it to the
right or left, the current value of the progress changes. SeekBar is used for forwarding or
backwarding the songs, Video etc. In the setOnSeekBarChangeListener interface is used which
provides three methods.
• onProgressChanged: In this method progress is changed and then according to this change
the progress value can used in our logic.
• onStartTrackingTouch: In this method when the user has started dragging, then this method
will be called automatically.
• onStopTrackingTouch: In this method, when the user stops dragging, then this method will
called automatically. Example
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">

<TextView
android:id="@+id/textView" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true" android:layout_marginEnd="180dp"
android:layout_marginBottom="460dp" android:text="Example of Seekbar" />

<SeekBar
android:id="@+id/seekBar" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginEnd="8dp"
android:layout_marginStart="8dp" android:layout_marginTop="372dp"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="#0F0"/><!-- set green color in the background of seek bar-->
</RelativeLayout> MainActivity.java
package com.example.seekbarexample; import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color; import android.os.Bundle; import android.widget.SeekBar;
import android.widget.TextView; import android.widget.Toast; public class MainActivity extends
AppCompatActivity {
// Define the global variable
SeekBar seekbar;
TextView Text_message;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// use findViewById() to get the Button
Text_message= (TextView)findViewById(R.id.textView); seekbar=
(SeekBar)findViewById(R.id.seekBar); //SeekBar.setBackgroundColor(Color.GREEN);
seekbar.setBackgroundColor(Color.GREEN);// green background color for the seek bar
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
Toast.makeText(getApplicationContext(),"seekbar progress: "+progress,
Toast.LENGTH_SHORT).show();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch started!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch stopped!",
Toast.LENGTH_SHORT).show();
}
});
}
}

Context menus:-
In Android, the context menu is like a floating menu and arises when the user has long
pressed or clicks on an item and is beneficial for implementing functions that define the specific
content or reference frame effect. The Android context menu is similar to the right-click menu in
Windows or Linux. In the Android system, the context menu provides actions that change a specific
element or context frame in the user interface and one can provide a context menu for any view.
The context menu will not support any object shortcuts and object icons. Note that we are going to
implement this project using the Java language.
Example
Step 1: Create a New Project
Step 2: Working with the activity_main.xml file Open res -> Layout -> activity_main.xml and write the
following code. In this file add only a TextView to display a simple text.

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">
<TextView
android:id="@+id/textView" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" android:text="Long press me!" android:textColor="#000"
android:textSize="20sp" android:textStyle="bold" />
</RelativeLayout>

Step 3: Working with the Mainactivity.java file Open the app -> Java -> Package -> Mainactivity.java
file. In this step, add the code to show the ContextMenu. Whenever the app will start make a long
click on a text and display the number of options to select them for specific purposes.

MainActivity.java

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


import android.graphics.Color; import android.os.Bundle; import android.view.ContextMenu;
import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Link those objects with their respective id's
// that we have given in .XML file
textView = (TextView) findViewById(R.id.textView);
relativeLayout = (RelativeLayout) findViewById(R.id.relLayout);
// here you have to register a view for context menu
// you can register any view like listview, image view,
// textview, button etc
registerForContextMenu(textView);
}
@Override public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// you can set menu header with title icon etc menu.setHeaderTitle("Choose a color");
// add menu items
menu.add(0, v.getId(), 0, "Yellow"); menu.add(0, v.getId(), 0, "Gray");
menu.add(0, v.getId(), 0, "Cyan");
}
// menu item select listener
@Override
public boolean onContextItemSelected(MenuItem item) { if (item.getTitle() == "Yellow") {
relativeLayout.setBackgroundColor(Color.YELLOW);
} else if (item.getTitle() == "Gray") {
relativeLayout.setBackgroundColor(Color.GRAY);
} else if (item.getTitle() == "Cyan") {
relativeLayout.setBackgroundColor(Color.CYAN);
}
return true;
}
}

User Event

Events are a useful way to collect data about a user's interaction with interactive components of
Applications. Like button presses or screen touch etc. The Android framework maintains an event
queue as a first-in, first-out (FIFO) basis. You can capture these events in your program and take
appropriate action as per requirements.

There are following three concepts related to Android Event Management –


● Event Listeners − An event listener is an interface in the View class that contains a single
callback method. These methods will be called by the Android framework when the View to which
the listener has been registered is triggered by user interaction with the item in the UI.
● Event Listeners Registration − Event Registration is the process by which an Event Handler
gets registered with an Event Listener so that the handler is called when the Event Listener fires the
event.
● Event Handlers − When an event happens and we have registered an event listener for the
event, the event listener calls the Event Handlers, which is the method that actually handles the
event.
Event Listeners & Event Handlers
Event Handler Event Listener & Description onClick()
OnClickListener()
This is called when the user either clicks or touches or focuses upon any widget like button, text,
image etc. You will use onClick() event handler to handle such event.
onLongClick() OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget like button, text,
image etc. for one or more seconds. You will use onLongClick() event handler to handle such event.
onFocusChange() OnFocusChangeListener()
This is called when the widget loses its focus ie. user goes away from the view item. You will use the
onFocusChange() event handler to handle such an event.
onKey() OnFocusChangeListener()
This is called when the user is focused on the item and presses or releases a hardware key on the
device. You will use onKey() event handler to handle such an event.
onTouch() OnTouchListener()
This is called when the user presses the key, releases the key, or any movement gesture on the
screen. You will use onTouch() event handler to handle such event.
onMenuItemClick() OnMenuItemClickListener()
This is called when the user selects a menu item. You will use onMenuItemClick() event handler to
handle such event.
onCreateContextMenu() onCreateContextMenuItemListener()
This is called when the context menu is being built(as the result of a sustained "long click)

Event Listeners Registration


Event Registration is the process by which an Event Handler gets registered with an Event
Listener so that the handler is called when the Event Listener fires the event. Though there are
several tricky ways to register your event listener for any event, I'm going to list down only top 3
ways, out of which you can use any of them based on the situation.
● Using an Anonymous Inner Class
● Activity class implements the Listener interface.
● Using Layout file activity_main.xml to specify event handler directly.

Touch Mode
Users can interact with their devices by using hardware keys or buttons or touching the
screen.Touching the screen puts the device into touch mode. The user can then interact with it by
touching the on-screen virtual buttons, images, etc.You can check if the device is in touch mode by
calling the View class's InTouchMode() method.

Focus
A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This
indicates that it’s ready to accept input from the user.
● isFocusable() − it returns true or false
● isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A view
may be focusable when using a hardware key but not when the device is in touch mode)

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


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

android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >

android:layout_height="wrap_content" android:text="Click Event"


android:layout_marginTop="200dp" android:layout_marginLeft="130dp"/>

android:id="@+id/txtResult" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp"
android:textColor="#86AD33" android:textSize="20dp"
android:textStyle="bold" android:layout_marginTop="12dp"/> </LinearLayout>
MainActivity.java
package com.tutlane.inputeventsexample; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.view.View; import android.widget.Button; import
android.widget.TextView;

public class MainActivity extends AppCompatActivity { Button btn;


TextView tView; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); btn = (Button)findViewById(R.id.btnClick); tView =
(TextView)findViewById(R.id.txtResult); btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

tView.setText("You Clicked On Button");


}
});
}
}
Styles and Themes
A style resource defines the format and looks for a UI. A style can be applied to an individual
View (from within a layout file) or to an entire Activity or application (from within the manifest file).
Defining Styles
A style is defined in an XML resource that is separate from the XML that specifies the layout. This
XML file resides under the res/values/ directory of your project and will have as the root node which
is mandatory for the style file. The name of the XML file is arbitrary, but it must use the .xml
extension.
You can define multiple styles per file using tag as shown below – <?xml
version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomFontStyle">

<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>

<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>

<item name="android:textColor">#00FF00</item>/>
</style>
</resources>
Using Styles Once your style is defined, you can use it in your XML Layout file using style attribute as
follows –

Theme is a style that is applied to an entire activity or app, instead of an individual View like as
mentioned above. When we applied a style as a theme, the views in activity or app apply to the all
style attributes that supports. For example. If we apply TextviewStyle as a theme for an activity, then
the text of all the views in activity appears in the same style.
Following is the example of defining a theme in the android application.
<color name="custom_theme_color">#b0b0ff</color>
<style name="CustomTheme" parent="Theme.AppCompat.Light">
<item name="android:windowBackground">@color/custom_theme_color</item>
<item name="android:colorBackground">@color/custom_theme_color</item> </style> The
above code overrides windowBackground and colorBackground properties of
Theme.AppCompat.Light theme.
To set a theme for a particular activity, open AndroidManifest.xml file and write the code like as
shown below
<activity android:theme="@android:style/CustomTheme">
In case, if we want to set the theme for all the activities in android application, open
AndroidManifest.xml file and write the code like as shown below.
<application android:theme="@android:style/CustomTheme">
Android Styling Color Palette
In android, we can customize the application basic theme colors based on our requirements.
Following is the example of basic material design in the android application.

Generally, the above layout defined in styles.xml file like as shown below and it resides in res/values
folder.
<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>
We can customize the application basic theme colors based on our requirements. Now we will see
how to use these styles and themes in android applications with examples.
Android Styles and Themes Example
Following is the example of defining a custom style for controls in LinearLayout to apply different
styles for controls in the android application.
Create a new android application using android studio and give names as StylesThemesExample. In
case if you are not aware of creating an app in android studio check this article Android Hello World
App.
Now we need to define our styles in styles.xml file, for that open styles.xml file from \res\values
folder and write the code like as shown below.
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="TextviewStyle" parent="@android:style/Widget.TextView">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">100dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textColor">#86AD33</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">20dp</item>
</style>
<style name="ButtonStyle" parent="@android:style/Widget.Button">
<item name="android:layout_width">200dp</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">100dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android:background">#F1511B</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">15dp</item>
</style>
<string name="wlcmsg">welcome </string> </resources>
If you observe above code, we defined a two styles (TextViewStyle, ButtonStyle) and we can apply
these styles for required controls in android application.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="@+id/TextView1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp"
android:layout_marginTop="200dp" android:textColor="#00ADEF" android:textSize="15dp"
android:text="@string/wlcmsg"/>
<TextView
android:id="@+id/TextView2" style="@style/TextviewStyle" android:text="Welcome to
Tutlane"/>
<Button android:id="@+id/btnShow" android:text="Click on Button"
style="@style/ButtonStyle" /> </LinearLayout>
If you observe above code we are referring our styles to required controls using style attribute.
Dates and Times
Date and Time in Android are formatted using the SimpleDateFormat library from Java, using
Calendar instance which helps to get the current system date and time. The current date and time
are of the type Long which can be converted to a human-readable date and time. In this article, it’s
been discussed how the Date and Time values can be formatted in various formats and displayed.
Have a look at the following image to get an idea of the entire discussion.

Steps to Format the Date and Time in Android


Step 1: Create an empty activity project
• Using Android Studio create an empty activity project. Refer to Android | How to
Create/Start a New Project in Android Studio?
Step 2: Working with the activity_main.xml file
• The main layout of the activity file containing 8 TextViews. One to show the current system
date and time value in Long type, and others to display the same date and time value in a
formatted human-readable way.
• To implement the UI invoke the following code inside the activity_main.xml file.
Activity_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:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity"
tools:ignore="HardcodedText">

<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="32dp"
android:text="Date and Time value in Long type :" android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" /> <!--text view to show the current date and
time in Long type-->
<TextView android:id="@+id/dateTimeLongValue"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="64dp"
android:textSize="18sp" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView android:id="@+id/textView" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="64dp" android:text="Date and Time formatted :"
android:textSize="18sp" android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/dateTimeLongValue" />

<!--text views to show the current date and time in formatted and human readable way-->
<TextView android:id="@+id/format1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<TextView android:id="@+id/format2" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format1" />
<TextView android:id="@+id/format3" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format2" />

<TextView android:id="@+id/format4" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_marginStart="16dp"
android:layout_marginTop="16dp" android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format3" />

<TextView
android:id="@+id/format5" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format4" />

<TextView
android:id="@+id/format6" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format5" /> <TextView
android:id="@+id/format7" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp" android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format6" />

</androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Working with the MainActivity file
Understanding the way of formatting the date and time in Android using SimpleDateFormat •
Firstly, the instance of the Calendar is created and the desired format of the date and time
to be shown is passed to the SimpleDateFormat method. The String should include the following
characters and one may include the separators like -, / etc.
• The below table includes the characters to be used to generate the most used common
pattern of date and time.
Character to be used Output
dd Date in numeric value
E Day in String (short form. Ex: Mon)
EEEE Day in String (full form. Ex: Monday)
MM Month in numeric value
yyyy Year in numeric value
LLL Month in String (short form. Ex: Mar)
LLLL Month in String (full form. Ex: March)
HH Hour in numeric value (24hrs timing format)

import androidx.appcompat.app.AppCompatActivity; import java.text.SimpleDateFormat; import


java.util.Calendar;

public class MainActivity extends AppCompatActivity {

TextView dateTimeInLongTextView, format1, format2, format3, format4, format5,


format6, format7;

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

String dateTime;
Calendar calendar;
SimpleDateFormat simpleDateFormat;

// register all the text view with appropriate IDs


dateTimeInLongTextView = (TextView) findViewById(R.id.dateTimeLongValue);
format1 = (TextView) findViewById(R.id.format1); format2 = (TextView)
findViewById(R.id.format2); format3 = (TextView) findViewById(R.id.format3); format4 =
(TextView) findViewById(R.id.format4); format5 = (TextView) findViewById(R.id.format5);
format6 = (TextView) findViewById(R.id.format6); format7 = (TextView)
findViewById(R.id.format7);

// get the Long type value of the current system date Long dateValueInLong =
System.currentTimeMillis();
dateTimeInLongTextView.setText(dateValueInLong.toString());

// different format type to format the


// current date and time of the system
// format type 1
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format1.setText(dateTime);

// format type 2
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format2.setText(dateTime);

// format type 3
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format3.setText(dateTime);

// format type 4
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.LLL.yyyy HH:mm:ss aaa z"); dateTime =
simpleDateFormat.format(calendar.getTime()).toString(); format4.setText(dateTime);

// format type 5
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.LLLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format5.setText(dateTime);

// format type 6
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("E.LLLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format6.setText(dateTime);

// format type 7
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("EEEE.LLLL.yyyy KK:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format7.setText(dateTime);
}
}
Retrieving Data
SQLite is an open source SQL database that stores data to a text file on a device. Android comes in
with built in SQLite database implementation. SQLite supports all the relational database features. In
order to access this database, you don't need to establish any kind of connections for it like
JDBC,ODBC e.t.c

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
SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);
Database - Insertion
We can create tables or insert data into tables using the execSQL method defined in SQLiteDatabase
class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS Tbl_Login(Username VARCHAR,Password
VARCHAR);"); mydatabase.execSQL("INSERT INTO Tbl_Login VALUES('admin','admin');"); Database
- Fetching
We can retrieve anything from the database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to the
table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from Tbl_Login",null); resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
Database - Helper class
For managing all the operations related to the database , a helper class has been given and is called
SQLiteOpenHelper. It automatically manages the creation and update of the database. Its syntax is
given below public class DBHelper extends SQLiteOpenHelper { public DBHelper(){
super(context,DATABASE_NAME,null,1);
} public void onCreate(SQLiteDatabase db) {} public void onUpgrade(SQLiteDatabase database, int
oldVersion, int newVersion) {} }

Unit: 6: Android Storage APIs

6.1WorkingwithApplicationPreferencessuchasCreatingSharedPreferences,Adding,Upda
ting,andDeleting Preferences.

6.2 Working with Files and Directories, Storing SQLite Database such as Creating an
SQLite
Database, Creating, Updating, and Deleting Database Records,Closing and Deleting
a
SQLiteDatabase.

Working with Application Preferences such as Creating Shared Preferences

One of the most Interesting Data Storage options Android provides its users is
Shared Preferences. Shared Preferences is the way in which one can store and retrieve
small amounts of primitive data as key/value pairs to a file on the device storage such as
String, int, float, Boolean that make up your preferences in an XML file inside the app on the
device storage.

Shared Preferences can be thought of as a dictionary or a key/value pair. For


example, you might
have a key being “username” and for the value, you might store the user’s username. And
then you could retrieve that by its key (here username).

You can have a simple shared preference API that you can use to store preferences
and pull them back as and when needed. Shared Preferences class provides APIs for reading,
writing, and managing this data. A sample GIF is given below to get an idea about what we
are going to do in this article.

primitive data:-

A primitive data type is either a data type that is built into a programming language,
or one that could be characterized as a basic structure for building more sophisticated
data types.
Data types are divided into two groups: Primitive data types - includes byte , short , int ,
long , float , double , boolean and char.
Shared Preferences are suitable in different situations. For example, when the user’s
settings need to be saved or to store data that can be used in different activities within the app.
As you know, onPause() will always be called before your activity is placed in

the background or

destroyed, So for the data to be saved persistently, it’s preferred to save it in onPause(), which
could be restored in

onCreate() of the activity. The data stored using shared preferences are kept private
within the scope of the application. However, shared preferences are different from that
activity’s instance state.
In order to use shared preferences, you have to call a method getSharedPreferences()
that returns a SharedPreference instance pointing to the file that contains the values of
preferences.

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES,


Context.MODE_PRIVATE);

How is Shared Preferences different from Saved InstanceState?


How to Create Shared Preferences?

The first thing we need to do is to create one shared preferences file per app. So
name it with the package name of your app- unique and easy to associate with the app. When
you want to get the values, call the getSharedPreferences() method. Shared Preferences
provide modes of storing the data (private mode and public mode). It is for backward
compatibility- use only MODE_PRIVATE to be secure. public abstract
SharedPreferences getSharedPreferences (String name, int mode)

This method takes two arguments, the first being the name of the SharedPreference(SP) file
and the other is the context mode that we want to store our file in.

MODE_PUBLIC will make the file public which could be accessible by other applications
on the device

MODE_PRIVATE keeps the files private and secures the user’s data.
MODE_APPEND is used while reading the data from the SP file.

Nested classes of Shared Preferences

1. SharedPreferences.Editor: Interface used to write(edit) data in the SP file. Once


editing has been done, one must commit() or apply() the changes made to the file.
2. SharedPreferences.OnSharedPreferenceChangeListener(): Called when a shared
preference is changed, added, or removed. This may be called even if a preference is
set to its existing value. This callback will be run on your main thread.
Following are the methods of Shared Preferences

1. contains(String key): This method is used to check whether the preferences contain a
preference.

2. edit(): This method is used to create a new Editor for these preferences, through
which you can make modifications to the data in the preferences and atomically
commit those changes back to the SharedPreferences object.

3. getAll(): This method is used to retrieve all values from the preferences.

4. getBoolean(String key, boolean defValue): This method is used to retrieve a


boolean value from the preferences.

5. getFloat(String key, float defValue): This method is used to retrieve a float value
from the preferences.

6. getInt(String key, int defValue): This method is used to retrieve an int value from
the preferences.

7. getLong(String key, long defValue): This method is used to retrieve a long value
from the preferences.

8. getString(String key, String defValue): This method is used to retrieve a String


value from the preferences.

9. getStringSet(String key, Set defValues): This method is used to retrieve a set of


String values from the preferences.

10. registerOnSharedPreferencechangeListener(SharedPreferences.OnSharedPrefer
encechangeList ener listener): This method is used to registers a callback to be
invoked when a change happens to a preference.

11. unregisterOnSharedPreferencechangeListener(SharedPreferences.OnSharedPre
ferencechangeLi stener listener): This method is used to unregisters a previous
callback.

Static keyword:-The static keyword means the value is the same for every instance of the
class.

final keyword:-The final keyword means once the variable is assigned a value it can never
be changed.

Example

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">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" android:text="Shared
Preference "
android:textSize="35dp" />

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true
"
android:layout_marginTop="67dp"
android:height="50dp"

android:hint="Name"
android:minHeight="48dp" />
<EditText
android:id="@+id/editText2" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText
"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true
" android:hint="Pass"
android:minHeight="48dp" />

<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText
2"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true
" android:hint="Email"
android:minHeight="48dp" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText
3"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="tr
ue"
android:layout_marginStart="173dp"
android:layout_marginTop="138dp"
android:layout_marginEnd="150dp"
android:layout_marginBottom="332dp
" android:text="Save" />
</RelativeLayout> Activity_main.java

package com.example.sharedprefrences;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context; import


android.content.SharedPreferences;
import android.os.Bundle; import
android.view.Menu; import
android.view.View; import
android.widget.Button; import
android.widget.EditText; import
android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText ed1,ed2,ed3;
Button b1;

public static final String MyPREFERENCES = "MyPrefs" ;


public static final String Name =
"nameKey"; public static final String
Phone = "phoneKey"; public static final
String Email = "emailKey";
SharedPreferences sharedpreferences;
@Override protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);

b1=(Button)findViewById(R.id.button); sharedpreferences
= getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE); b1.setOnClickListener(new View.OnClickListener() {
@Override public void
onClick(View view) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();

SharedPreferences.Editor editor = sharedpreferences.edit();

editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
Adding,Updating, and Deleting Preferences Example:- 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">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shared Preference "
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textVie
w2"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true" android:layout_alignParentEnd="true"
android:layout_alignParentRight="true
"
android:layout_marginTop="67dp"
android:hint="Name" android:textSize="25sp"
/>

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content
"
android:layout_height="wrap_conten
t"
android:layout_below="@+id/editTe
xt"
android:layout_alignParentStart="tru
e"
android:layout_alignParentLeft="true
"
android:layout_alignParentEnd="true
"
android:layout_alignParentRight="tr
ue" android:hint="Pass"
android:textSize="25sp" />

<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content
"
android:layout_below="@+id/editTex
t2"
android:layout_alignParentStart="true
"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="tru
e" android:hint="Email"
android:textSize="25sp" />

<Button android:id="@+id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="tr
ue"
android:layout_marginTop="129dp" android:layout_marginEnd="261dp"
android:layout_marginBottom="230dp
"
android:text="Save" />

<Button
android:id="@+id/fatchbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="tr
ue"
android:layout_marginTop="129dp" android:layout_marginEnd="131dp"
android:layout_marginBottom="230dp
" android:text="Fatch" />

<Button
android:id="@+id/removebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="tr
ue"
android:layout_marginTop="227dp" android:layout_marginEnd="125dp"
android:layout_marginBottom="132dp
" android:text="Remove" />

<Button android:id="@+id/clearbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="tr
ue"
android:layout_marginTop="227dp" android:layout_marginEnd="268dp"
android:layout_marginBottom="132dp
" android:text="Clear"
/>

</RelativeLayout>

MainActivity.java

package com.example.sharedpreference;

import android.content.Context;
import
android.content.SharedPreferences;
import android.os.Bundle; import
android.view.View; import
android.widget.Button; import
android.widget.EditText; import
android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends


AppCompatActivity {
EditText ed1,ed2,ed3;
Button savebtn,fatchbtn,removebtn,clrbtn;

public static final String MyPREFERENCES = "MyPefrefs" ;


public static final String Name =
"nameKey"; public static final String
Phone = "phoneKey"; public static final
String Email = "emailKey";

SharedPreferences sharedpreferences; SharedPreferences.Editor editor;

@Override protected void onCreate(Bundle


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

ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);

savebtn=(Button)findViewById(R.id.savebtn);
fatchbtn=(Button)findViewById(R.id.fatchbtn);
removebtn=(Button)findViewById(R.id.removebtn);
clrbtn=(Button)findViewById(R.id.clearbtn);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);

savebtn.setOnClickListener(new View.OnClickListener() {
@Override public void
onClick(View v) { String n
= ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();

editor = sharedpreferences.edit();

editor.putString(Name, n);
editor.putString(Phone, ph); editor.putString(Email,
e);
editor.commit();

Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).sh
ow(); ed1.getText().clear(); ed2.getText().clear();
ed3.getText().clear();
}
});
fatchbtn.setOnClickListener(new View.OnClickListener() {
@Override public void
onClick(View view) { if
(sharedpreferences.contains(Name));
ed1.setText(sharedpreferences.getString(Name,""));
if (sharedpreferences.contains(Phone));
ed2.setText(sharedpreferences.getString(Phone,"")) ;
if (sharedpreferences.contains(Email));
ed3.setText(sharedpreferences.getString(Email,""));
}
});
clrbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ed1.setText(""); ed2.setText("");ed3.setText("");
}
});
removebtn.setOnClickListener(new View.OnClickListener() {
@Override public void
onClick(View view) {
editor.remove(Name);

editor.remove(Phone);editor.remove(Email);
editor.apply(); ed1.getText().clear();
ed2.getText().clear();
ed3.getText().clear();
}
});
}
}

6.2 Working with Files and Directories


Like other modern operating systems, Android has a disk-based file system. There are
two storage areas: internal and external. Internal storage refers to the built-in, non-volatile
memory. Devices also can come with removable memory (like a SD card), which is referred
to as external storage. The internal storage is also occasionally referred to as permanent
storage. Files saved in internal storage are accessible only to your app by default

External storage can be removed at any time and files saved here can be accessible to
everyone. Applications can allow themselves to be installed on the external storage by
specifying the android:installLocation attribute. (The default is internal storage.) When the
user uninstalls the application, if the app is installed on internal storage, all files are removed.
On the other hand, if the application was installed on external storage, the app files are moved
only if we save them in the directory that is obtained from calling API getExternalFilesDir().
To grant everyone permission to your files, you need to declare the following in your
manifest file. ...

• Internal storage directories: These directories include both a dedicated location for
storing persistent files, and another location for storing cache data. The system
prevents other apps from accessing these locations, and on Android 10 (API level 29)
and higher, these locations are encrypted. These characteristics make these locations a
good place to store sensitive data that only your app itself can access.
• External storage directories: These directories include both a dedicated location for
storing persistent files, and another location for storing cache data. Although it's
possible for another app to access these directories if that app has the proper
permissions, the files stored in these directories are meant for use only by your app. If
you specifically intend to create files that other apps should be able to access, your
app should store these files in the shared storage part of external storage instead.

When the user uninstalls your app, the files saved in app-specific storage are removed.
Because of this behavior, you shouldn't use this storage to save anything that the user expects
to persist independently of your app. For example, if your app allows users to capture photos,
the user would expect that they can access those photos even after they uninstall your app. So
you should instead use shared storage to save those types of files to the appropriate media
collection.

Access persistent files

Your app's ordinary, persistent files reside in a directory that you can access using the filesDir
property of a context object. The framework provides several methods to help you access and
store files in this directory.
Access and store files

You can use the File API to access and store files.

To help maintain your app's performance, don't open and close the same file multiple times.

The following code snippet demonstrates how to use the File API:

File file = new File(context.getFilesDir(), filename);

SQLite :
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 by default. So, there is no need to perform any database
setup or administration task. SQLiteOpenHelper class provides the functionality to use the
SQLite database.

SQLite is another data storage available in Android where we can store data in the user’s
device and can use it any time when required. In this article, we will take a look at creating an
SQLite database in the Android app and adding data to that database in the Android app. This
is a series of 4 articles in which we are going to perform the basic CRUD (Create, Read,
Update, and Delete) operation with SQLite Database in Android. We are going to cover the
following 4 articles in this series:

1. How to Create and Add Data to SQLite Database in Android?


2. How to Read Data from SQLite Database in Android?
3. How to Update Data to SQLite Database in Android?
4. How to Delete Data in SQLite Database in Android?

What is SQLite Database?

SQLite Database is an open-source database provided in Android which is used to


store data inside the user’s device in the form of a Text file. We can perform so many
operations on this data such as adding new data, updating, reading, and deleting this data.
SQLite is an offline database that is locally stored in the user’s device and we do not have to
create any connection to connect to this database.

How Data is Being Stored in the SQLite Database?

Data is stored in the SQLite database in the form of tables. When we stored this data
in our SQLite database it is arranged in the form of tables that are similar to that of an excel
sheet. Below is the representation of our SQLite database which we are storing in our SQLite
database.
Important Methods in SQLite Database

Below are the several important methods that we will be using in this SQLite database
integration in Android.

Insert, Read, Delete & Update Operation In SQLite

Android provides different ways to store data locally so using SQLite is one the way
to store data.
SQLite is a structure query base database, hence we can say it’s a relation database. Android
os has its own implementation to perform CRUD (Create, Read, Update, Delete)operations,
so Android provides set of classes available in android.database and android.database.sqlite
packages.

While using SQLite there could be two different ways to perform different operations
like create, read, update and delete. One writing raw queries and another is using
parameterized functions or we can say parametrized queries.

Create:
Creating a database is very simple in android by using SQLiteOpenHelper class.
SQLiteOpenHelper is an abstract class with two abstract methods onCreate(SQLiteDatabase
db) and onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) and many more
database helpful functions. Whenever we need to create a database we have to extend
SQLiteOpenHelper class as follows:

/**A helper class to perform database related queries*/

public class SqliteManager extends SQLiteOpenHelper {


public static final String DATABASE_NAME =
"Student.db"; public static final int version = 1;

public SqliteManager(Context context) {


super(context, DATABASE_NAME, null, version); }

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String dbQuery = "CREATE TABLE Items (id INTEGER PRIMARY KEY
AUTOINCREMENT,name TEXT, description TEXT)";
sqLiteDatabase.execSQL(dbQuery);
}

@Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int


oldVersion, int
newVersion) {
}
}

onCreate(SQLiteDatabase sqLiteDatabase) method is called only for once throughout the


application lifecycle, it will be called whenever there is first call to getReadableDatabase() or
getWritableDatabase() function available in super SQLiteOpenHelper class so
SQLiteOpenHelper class call the onCreate() method after creating database and instantiate
SQLiteDatabase object. Database name is passed in constructor call.

onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) is only called whenever


there is a updation in existing version so to update a version we have to increment the value
of version variable passed in the superclass constructor. In onUpgrade method we can write
queries to perform whatever action is required. In most example you will see that existing
table(s) are being dropped and again onCreate() method is being called to create tables again.
But it’s not mandatory to do so it all depends upon your requirements. We have to change
database version if we have added a new row in the database table in this case if we have
requirement that we don’t want to lost existing data in the table then we can write alter table
query in the onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) method.
Likewise if there is no requirement of existing data whenever we upgrade database version
then we can write drop table query in onUpgrade(SQLiteDatabase db,int oldVersion, int
newVersion) method and call onCreate(SQLiteDatabase sqLiteDatabase) method again to
create table again. Remember never call onCreate(SQLiteDatabase sqLiteDatabase) method if
you have written alter table query in onUpgrade(SQLiteDatabase db,int oldVersion, int
newVersion) method.
To perform insert, read, delete, update operation there are two different ways:
Write parameterized queries
(Recommended) Write raw queries
Parameterized Queries: These are those queries which are performed using inbuilt functions
to insert, read, delete or update data. These operation related functions are provided in
SQLiteDatabase class.

Raw Queries: These are simple sql queries similar to other databases like MySql, Sql Server
etc, In this case user will have to write query as text and passed the query string in
rawQuery(String sql,String [] selectionArgs) or execSQL(String sql,Object [] bindArgs)
method to perform operations.

Important Note: Android documentation don’t recommend to use raw queries to perform
insert, read, update, delete operations, always use SQLiteDatabase class’s insert, query,
update, delete functions.

public void insertItem(Item item) {


String query = "INSERT INTO " + ItemTable.NAME + " VALUES (0,?,?)";
SQLiteDatabase db = getWritableDatabase(); db.execSQL(query, new
String[]{item.name,
item.description}); db.close(); }

While using raw queries we never come to know the result of operation, however with
parameterized queries function a value is returned for success or failure of operation.

Insert: To perform insert operation using parameterized query we have to call insert
function available in SQLiteDatabase class. insert() function has three parameters like
public long insert(String tableName,String nullColumnHack,ContentValues values) where
tableName is name of table in which data to be inserted. public long insert(String
tableName,String nullColumnHack,ContentValues values)

NullColumnHack may be passed null, it require table column value in case we don’t put
column name in ContentValues object so a null value must be inserted for that particular
column, values are those values that needs to be inserted- ContentValues is a key-pair based
object which accepts all primitive type values so whenever data is being put in ContentValues
object it should be put again table column name as key and data as value. insert function will
return a long value i.e number of inserted row if successfully inserted, – 1 otherwise.

Here is simple example:

//Item is a class representing any item with id, name and description. public
void addItem(Item item) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name",item.name);
// name - column
contentValues.put("description",item.description);
// description is column in items table, item.description has
value for description db.insert("Items", null,
contentValues);//Items is table name db.close(); }
Update: Update function is quite similar to insert but it requires two additional parameters,
it doesn’t required nullColumnHack. It has total four parameters two are similar to insert
function that is tableName and contentValues. Another two are whereClause(String) and
whereArgs(String[]).

Update function is available in SQLiteDatabase class it looks as follows:


public int update(String tableName,ContentValues contentValues,String
whereClause,String[] whereArgs)

Here whereClause is tell the database where to update data in table, it’s recommended to pass
?s (questions) along with column name in whereClause String. Similarly whereArgs array
will contain values for those columns whose against ?s has been put in whereClause. Update
function will return number of rows affected if success, 0 otherwise. Here is simple use of
update:

//Item is a class representing any item with id, name and description public
void updateItem(Item item) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new
ContentValues();
contentValues.put("id", item.id);
contentValues.put("name", item.name);
contentValues.put("description", item.description);
String whereClause = "id=?";
String whereArgs[] = {item.id.toString()};
db.update("Items", contentValues, whereClause,
whereArgs); }

Delete: Similar to insert and update, delete function is available in SQLiteDatabase class, So
delete is very similar to update function apart from ContentValues object as it’s not required
in delete. public int delete(String tableName,String whereClause,String [] whereArgs)
function has three parameters these are totally similar to update function’s parameters and are
used in same way as in update function.

Here is simple use of delete:

public void deleteItem(Item item) {


SQLiteDatabase db = getWritableDatabase();
String whereClause = "id=?";
String whereArgs[] =
{item.id.toString()};
db.delete("Items", whereClause, whereArgs); }

Here whereClause is optional, passing null will delete all rows in table. delete function will
return number of affected row if whereClause passed otherwise will return 0.
Important Note: If you want to remove all rows and require count of deleted ones also then
pass 1 as whereClause.

Read(select): Reading from a database table is bit different from other functions like
insert,update and delete. SQLiteDatabase class provides query() method to read data from
table. query() method is overloaded with different set of parameters. It returns Cursor object
so Cursor is a result-set with queried data, it provides different functions really helpful while
reading data.

Following are some overloaded query functions:

• public Cursor query (String table, String[] columns, String selection, String[]
selectionArgs, String groupBy, String having, String orderBy, String limit)

• public Cursor query (String table, String[] columns, String selection, String[]
selectionArgs, String groupBy, String having, String orderBy)
• public Cursor query (boolean distinct, String table, String[] columns, String
selection, String[] selectionArgs, String groupBy, String having, String orderBy,
String limit)

Most of the parameters in query overloaded functions are optional except from table and
distinct any of other parameters can be passed as null. if distinct is passed as true Cursor data
set will not have any duplicate row.

public ArrayList<Item> readAllItems() {


ArrayList<Item> items = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
//see above point 2 function
Cursor cursor = db.query("Items"
, null// columns - null will give all
, null// selection
, null// selection arguments
, null// groupBy
, null// having
, null// no need or order by for
now; if (cursor != null) {
while (cursor.moveToNext()) {
// move the cursor to next row if there is any to read it's data
Item item = readItem(cursor);
items.add(item);
}
}
return items;
}

private Item readItem(Cursor


cursor) { Item item = new Item();
item.id = cursor.getInt(cursor.getColumnIndex(ItemTable.COL_ID));
item.name = cursor.getString(cursor.getColumnIndex(ItemTable.COL_NAME));
item.description =
cursor.getString(cursor.getColumnIndex(ItemTable.COL_DESCRIPTION)); return
item;
}
Example Database(Crud Operation)

DBHelper.java

package com.example.dboperations;

import android.content.ContentValues;
import android.content.Context; import
android.database.Cursor; import
android.database.sqlite.SQLiteDatabase; import
android.database.sqlite.SQLiteOpenHelper
;

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DB_NAME =


"PersonsDB.db"; public static final String
TABLE_NAME = "Perons"; public static final
String COLUMN_ID = "id"; public static final
String COLUMN_NAME = "name"; public
static final String COLUMN_ADD = "address";
public static final int DB_VER =
1;

public DatabaseHelper(Context context) {


super(context, DB_NAME, null, DB_VER);
}

@Override public void


onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + "
INTEGER
PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME + " TEXT," +
COLUMN_ADD + " TEXT)";
db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int old_ver, int new_ver) {
String sql = "DROP TABLE IF EXISTS Persons";
db.execSQL(sql);
onCreate(db);
}
public boolean addPerson(String nam, String add) {
SQLiteDatabase db =
this.getWritableDatabase(); ContentValues cv
= new ContentValues(); cv.put(COLUMN_NAME,
nam); cv.put(COLUMN_ADD, add);
db.insert(TABLE_NAME, null, cv);
db.close();
return true;
}

public Cursor getPerson(int id) {


SQLiteDatabase db = this.getReadableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " where id=" + id;
Cursor c = db.rawQuery(sql, null);
return c;
}

public boolean removePersonbyID(int id) {


SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, "id=?", new
String[]{String.valueOf(id)}); return true;
}

public boolean removeallPersons() {


SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
return true;
}

public boolean updatePersonbyID(int id, String nam, String addr)


{ SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, nam); cv.put(COLUMN_ADD, addr);
db.update(TABLE_NAME, cv, "id=?", new String[]{String.valueOf(id)});
return true;
}

public boolean updateAllPerson(int id, String nam, String addr)


{ SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, nam); cv.put(COLUMN_ADD,
addr); db.update(TABLE_NAME, cv, null, null); return
true;
}

}
main_activity.xml

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


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

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" android:orientation="vertical"
tools:context=".MainActivity">

<EditText
android:id="@+id/edName"
android:layout_width="wrap_conten
t"
android:layout_height="wrap_conte
nt"
android:layout_marginBottom="10d
p"
android:ems="10"
android:hint="Enter Name"
android:inputType="textPersonName
" />

<EditText
android:id="@+id/edAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:ems="10"
android:hint="Enter Adress"
android:inputType="textPersonName
" />

<LinearLayout android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="horizontal">

<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content
"
android:layout_height="wrap_content
"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:onClick="saveRecord" android:text="save"
/>
<Button
android:id="@+id/btnView"
android:layout_width="wrap_content
"
android:layout_height="wrap_content
"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:onClick="viewRecord" android:text="view
" />

<Button
android:id="@+id/btnReset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:onClick="resetRecord"
android:text="reset" /> </LinearLayout>
</LinearLayout>

Activity.java

package com.example.dboperations;

import
android.content.Intent;
import android.os.Bundle;
import android.view.View;
import
android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


EditText edName, edAdd;
DatabaseHelper db;

@Override protected void onCreate(Bundle


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

db = new DatabaseHelper(this);
edName = findViewById(R.id.edName);
edAdd = findViewById(R.id.edAdd);
}
public void saveRecord(View view)
{ String n =
edName.getText().toString(); String
a = edAdd.getText().toString();
db.addPerson(n, a);
Toast.makeText(MainActivity.this, "Insert Sucess", Toast.LENGTH_SHORT).show();
}

public void viewRecord(View view) {


Intent intent = new Intent(MainActivity.this, ViewPersonActivity.class);
startActivity(intent);
}

public void resetRecord(View view) {


edName.setText("");
edAdd.setText("");
}
}

activity_view_person.xml

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


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

<EditText
android:id="@+id/edId"
android:layout_width="wrap_content
"
android:layout_height="wrap_content
"
android:layout_marginBottom="10dp
" android:ems="10"
android:hint="Enter ID"
android:inputType="textPersonName
" />

<Button
android:id="@+id/btnShow"
android:layout_width="wrap_conten
t"
android:layout_height="wrap_conte
nt"
android:layout_marginBottom="50d
p"
android:onClick="showRecord" android:text="show"
/>

<EditText
android:id="@+id/edName" android:layout_width="wrap_content
"
android:layout_height="wrap_content
"
android:layout_marginBottom="10dp
" android:ems="10" android:hint="Name
View"
android:inputType="textPersonName
" />

<EditText
android:id="@+id/edAdd"
android:layout_width="wrap_content
"
android:layout_height="wrap_content
"
android:layout_marginBottom="20dp
" android:ems="10" android:hint="Address
View"
android:inputType="textPersonName
" />

<Button
android:id="@+id/btnBack" android:layout_width="wrap_conten
t"
android:layout_height="wrap_conte
nt"
android:layout_marginBottom="10d
p" android:onClick="goBack" android:text="back"
/>

<Button
android:id="@+id/btnDel"
android:layout_width="wrap_conten
t"
android:layout_height="wrap_conte
nt"
android:layout_marginBottom="10d
p"
android:onClick="deleteRecord" android:text="Delete
by ID" />

<Button
android:id="@+id/btnUpd"
android:layout_width="wrap_conten
t"
android:layout_height="wrap_conte
nt"
android:onClick="updateRecord" android:text="update
by id" />

</LinearLayout>

Viewpersonactivity.java

package com.example.dboperations;

import
android.content.Intent;
import
android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import
android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class ViewPersonActivity extends AppCompatActivity {


EditText edId, edName, edAdd;
DatabaseHelper db;

@Override protected void onCreate(Bundle


savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_person);

db = new DatabaseHelper(this);
edId = findViewById(R.id.edId);
edName = findViewById(R.id.edName);
edAdd = findViewById(R.id.edAdd);

public void showRecord(View view) {


int id =
Integer.parseInt(edId.getText().toString());
Cursor c = db.getPerson(id);
c.moveToFirst(); if (c.getCount() == 1) {
edName.setText(c.getString(c.getColumnIndex(DatabaseHelper.COLUMN_NAME)));
edAdd.setText(c.getString(c.getColumnIndex(DatabaseHelper.COLUMN_ADD)));
} else {
Toast.makeText(this, "no Record Found", Toast.LENGTH_SHORT).show();
edName.setText("");
edAdd.setText("");
}
}

public void goBack(View view) {


Intent intent = new Intent(ViewPersonActivity.this, MainActivity.class);
startActivity(intent);
}

public void deleteRecord(View view) {


int id =
Integer.parseInt(edId.getText().toString());
db.removePersonbyID(id);
Toast.makeText(this, "Record Deleted", Toast.LENGTH_SHORT).show();
edId.setText("");
}

public void updateRecord(View view) {


int id =
Integer.parseInt(edId.getText().toString()); String
n = edName.getText().toString(); String a
= edAdd.getText().toString();
db.updatePersonbyID(id, n, a);
Toast.makeText(this, "Record Updated", Toast.LENGTH_SHORT).show();
edId.setText("");
}
}
Unit 7. Content Providers

7.1 Exploring Android’s Content Providers, Modifying Content Providers


Data
7.2 Enhancing Applications using Content Providers, acting as a Content
Provider
7.3 Working with Live Folders.

Exploring Android’s Content Providers, Modifying Content Providers Data

In Android, Content Providers are a very important component that serves


the purpose of a relational database to store the data of applications. The role of
the content provider in the android system is like a central repository in which
data of the applications are stored, and it facilitates other applications to securely
access and modifies that data based on the user requirements.
Android system allows the content provider to store the application data in
several ways. Users can manage to store the application data like images, audio,
videos, and personal contact information by storing them in SQLite Database,
in files, or even on a network. In order to share the data, content providers
have certain permissions that are used to grant or restrict the rights to other
applications to interfere with the data.
A content provider component supplies data from one application to
others on request. Such requests are handled by the methods of the
ContentResolver class. A content provider can use different ways to store its
data and the data can be stored in a database, in files, or even over a network.
Example of content Provider o
Media Player o Calls
logs o Contact List o
Gallery Application o
File Manager o
Browser

Note:-sometimes it is required to share data across applications. This is


where content providers become very useful.
Content providers let you centralize content in one place and have many
different applications access it as needed. A content provider behaves very
much like a database where you can query it, edit its content, as well as add or
delete content using insert(), update(), delete(), and query() methods. In most
cases this data is stored in an SQlite database.

public class My Application extends ContentProvider {


}

Sr.No Part & Description

Prefix
1
This is always set to content://

Authority

2 This specifies the name of the content provider, for example contacts, browser
etc. For third-party content providers, this could be the fully qualified name,
such as com.tutorialspoint.statusprovider

data_type
This indicates the type of data that this particular provider provides. For
3 example, if you are getting all the contacts from the Contacts content
provider, then the data path would be people and URI would look like
thiscontent://contacts/people

Id

4 This specifies the specific record requested. For example, if you are looking
for contact number 5 in the Contacts content provider then URI would look
like this content://contacts/people/5.

Create Content Provider

This involves number of simple steps to create your own content provider.
• First of all you need to create a Content Provider class that extends
the ContentProviderbaseclass.
• Second, you need to define your content provider URI address
which will be used to access the content.
• Next you will need to create your own database to keep the content.
Usually, Android uses SQLite database and framework needs to
override onCreate() method which will use SQLite Open Helper
method to create or open the provider's database. When your
application is launched, the onCreate() handler of each of its
Content Providers is called on the main application thread.
• Next you will have to implement Content Provider queries to
perform different database specific operations.
• Finally register your Content Provider in your activity file using
<provider> tag.
Here is the list of methods which you need to override in Content Provider class
to have your Content Provider working −

ContentProvider
• onCreate() This method is called when the provider is started.
• query() This method receives a request from a client. The result is
returned as a Cursor object.
• insert()This method inserts a new record into the content provider.
• delete() This method deletes an existing record from the content
provider.
• update() This method updates an existing record from the content
provider.
• getType() This method returns the MIME type of the data at the
given URI.

Content URI

Content URI(Uniform Resource Identifier) is the key concept of Content


providers. To access the data from a content provider, URI is used as a query
string. Structure of a Content URI:
content://authority/optionalPath/optionalID Details of different parts of Content
URI:
● content:// – Mandatory part of the URI as it represents that the given

URI is a Content URI.

● authority – Signifies the name of the content provider like contacts,

browser, etc. This part must be unique for every content provider. ●

optionalPath – Specifies the type of data provided by the content

provider. It is essential as this part helps content providers to support different

types of data that are not related to each other like audio and video files. ●

optionalID – It is a numeric value that is used when there is a need to

access a particular record.

If an ID is mentioned in a URI then it is an id-based URI otherwise a


directorybased URI.
Operations in Content Provider

Four fundamental operations are possible in Content Provider namely Create,


Read,

Update, and Delete. These operations are often termed as CRUD operations.

● Create: Operation to create data in a content provider.

● Read: Used to fetch data from a content provider.

● Update: To modify existing data.

● Delete: To remove existing data from the storage.

Working of the Content Provider

UI components of android applications like Activity and Fragments use an


object CursorLoader to send query requests to ContentResolver. The
ContentResolver object sends requests (like create, read, update, and delete) to
the ContentProvider as a client. After receiving a request, ContentProvider
process it and returns the desired result. Below is a diagram to represent these
processes in pictorial form.
Creating a Content Provider

Following are the steps which are essential to follow in order to create a Content
Provider:
• Create a class in the same directory where the that MainActivity file resides
and this class must extend the ContentProvider base class.
• To access the content, define a content provider URI address.
• Create a database to store the application data.
• Implement the six abstract methods of ContentProvider class.
• Register the content provider in AndroidManifest.xml file using
<provider> tag.

Example MainActivity.Java

package com.example.readcontacts;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity; import
android.database.Cursor; import
android.net.Uri; import
android.os.Bundle;
import android.provider.ContactsContract.PhoneLookup; import
android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {


ListView lvContacts;

/** Called when the activity is first created. */


@Override public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvContacts = (ListView) findViewById(R.id.lvContacts);
Cursor c = managedQuery(Uri.parse("content://contacts/phones"), null, null, null, null);
String names[] = new String[ c.getCount() ]; int
i=0;
while (c.moveToNext())
names[i++] = c.getString(c.getColumnIndex(PhoneLookup.DISPLAY_NAME)) + "\n"
+ c.getString(c.getColumnIndex(PhoneLookup.NUMBER));
ArrayAdapter<String> adpt = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names);
lvContacts.setAdapter(adpt);
} }

Activitymain.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">

<ListView
android:id="@+id/lvContacts"
android:layout_width="match_parent"
android:layout_height="442dp"
android:layout_x="26dp"
android:layout_y="34dp"></ListView>
</LinearLayout>

AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.readcontacts" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.READ_CONTACTS">
</uses-permission> <application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ReadContacts"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Working with Live Folders

A LiveFolder (android.provider.LiveFolders) is a powerful feature that


complements the content provider interface. A LiveFolder is a special folder
containing content generated by a content provider. For example, a user might
want to create a LiveFolder with favorite contacts (“Fave Five”), most
frequently viewed emails in a custom email application, or high-priority tasks in
a task management application.
When the user chooses to create a LiveFolder, the Android system provides a
list of all
activities that respond to the ACTION_CREATE_LIVE_FOLDER Intent. If the
user chooses
your Activity, that Activity creates the LiveFolder and passes it back to the
system using the setResult() method.
The LiveFolder consists of the following components:

● Folder name
● Folder icon
● Display mode (grid or list)
● Content provider URI for the folder contents
The first task when enabling a content provider to serve up data to a LiveFolder
is to provide an <intent-filter> for an Activity that handles enabling the
LiveFolder. This is done within the AndroidManifest.xml file as follows:
<intent-filter>
<action android:name=“android.intent.action.CREATE_LIVE_FOLDER” />
<category android:name=”android.intent.category.DEFAULT” />
</intent-filter>
Next, this action needs to be handled within the onCreate() method of the
Activity it has been defined for. Within the preceding provider example, you
can place the following code to handle this action:
super.onCreate(savedInstanceState);
final Intent intent = getIntent(); final String action = intent.getAction();
if (LiveFolders.ACTION_CREATE_LIVE_FOLDER.equals(action)) {
final Intent resultIntent = new Intent();
resultIntent.setData(TrackPointProvider.LIVE_URI); resultIntent.putExtra(
LiveFolders.EXTRA_LIVE_FOLDER_NAME, “GPX Sample”);
resultIntent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON,
Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
resultIntent.putExtra
(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
LiveFolders.DISPLAY_MODE_LIST);
setResult(RESULT_OK, resultIntent);
} // ... rest of onCreate()

This defines the core components of the LiveFolder: its name, icon, display
mode, and Uri. The Uri is not the same as one that already existed because it
needs certain specific fields to work properly. This leads directly to the next
task: modifying the content provider to prepare it for serving up data to the
LiveFolder.

Example

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">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:background="#008080"
android:padding="5dp"
android:text="Android Write Text to a File"
android:textColor="#fff" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1" android:layout_marginTop="22dp"
android:ems="10"
android:layout_margin="5dp">
<requestFocus />
</EditText> <Button
android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/editText1" android:text="Write Text into File"
android:onClick="WriteBtn" android:layout_margin="5dp"/>
<Button android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1" android:text="Read
Text from File" android:layout_margin="5dp"/>

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button2"
android:text="TextView" />

</RelativeLayout>

MainActivity.java

package com.example.writefile;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle; import


android.os.Bundle;

import java.io.File; import


java.io.FileInputStream; import
java.io.FileNotFoundException; import
java.io.FileOutputStream; import
java.io.IOException; import
java.io.InputStreamReader; import
java.io.OutputStreamWriter; import
android.app.Activity; import android.view.View;
import android.widget.Button; import
android.widget.EditText; import
android.widget.TextView; import
android.widget.Toast;
public class MainActivity extends AppCompatActivity { EditText textmsg;
Button readbtn;
TextView text; @Override protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg=(EditText)findViewById(R.id.editText1); text=(TextView)
findViewById(R.id.textView); readbtn =
(Button) findViewById(R.id.button2); readbtn.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
String content=readFromFile("mytextfile.txt");
text.setText(content);
}
});
}
public void WriteBtn(View v) { //
add-write text into file try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close(); //display
file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) { e.printStackTrace();
}
}

public String readFromFile(String fileName)


{
File path=getApplicationContext().getFilesDir();
File readFrom=new File(path,fileName); byte[] content=
new byte[(int) readFrom.length()]; try {
FileInputStream stream = new FileInputStream(readFrom);
stream.read(content);
return new String(content);
} catch (IOException e) { e.printStackTrace();
return
e.toString();
}
}
}

Unit-8 Networking, Web and Multimedia APIs

8.1 Understanding Mobile Networking Fundamentals, Accessing the Internet


(HTTP),
8.2 Browsing the Web with WebView, Building Web Extensions using WebKit,
Working with Flash, Multimedia, Still Images, Video and Audio.

8.1 Understanding Mobile Networking Fundamentals


Android lets your application connect to the internet or any other local network and allows
you to perform network operations.

A device can have various types of network connections. This chapter focuses on using either
a Wi-Fi or a mobile network connection.

Checking Network Connection


Before you perform any network operations, you must first check that are you connected to
that network or internet e.t.c. For this android provides ConnectivityManager class.

You need to instantiate an object of this class by calling getSystemService() method. Its
syntax is given below −

ConnectivityManager check = (ConnectivityManager)


this.context.getSystemService(Context.CONNECTIVITY_SERVICE);

Once you instantiate the object of ConnectivityManager class, you can


use getAllNetworkInfo method to get the information of all the networks.

This method returns an array of NetworkInfo. So you have to receive it like this.

NetworkInfo[] info = check.getAllNetworkInfo();


The last thing you need to do is to check Connected State of the network. Its syntax is given
below −

for (int i = 0; i<info.length; i++){


if (info[i].getState() == NetworkInfo.State.CONNECTED){
Toast.makeText(context, "Internet is connected
Toast.LENGTH_SHORT).show();
}
}
Apart from this connected states, there are other states a network can achieve. They are
listed below −
Sr.No State
1 Connecting
2 Disconnected
3 Disconnecting
4 Suspended 5 Unknown

Performing Network Operations


After checking that you are connected to the internet, you can perform any network operation.
Here we are fetching the html of a website from a url.

Android provides HttpURLConnection and URL class to handle these operations. You need
to instantiate an object of URL class by providing the link of website. Its syntax is as
follows−

String link = "http://www.google.com";


URL url = new URL(link);
After that you need to call openConnection method of url class and receive it in a
HttpURLConnection object. After that you need to call the connect method of
HttpURLConnection class.

HttpURLConnection conn = (HttpURLConnection) url.openConnection();


conn.connect();

Accessing the Internet (HTTP)

you need to put extra permission to access internet in your app?


You need to add this permission for user security. Whenever you download an app from play
store, it asks for permission that application will use.

Let’s say you are downloading an application which must not use internet at all and if you
don’t require any permission for that, it might be secretly putting data on some server.

You need to explicitly put internet permission in AndroidManifest.xml, so user of your app
will be aware of it.

How to add internet permission in AndroidManifest.xml in android studio.


Step 1: Go to app -> src -> main -> AndroidManifest.xml.
Step 2: <uses-permission android:name="android.permission.INTERNET" />
Browsing the Web with WebView The WebKit Browser
• In Android you can embed the built-in Web browser as a widget in your own activities, for
displaying HTML material or perform Internet browsing.
• The Android browser is based on WebKit, the same engine that powers Apple's Safari Web
browser.
• Android uses the WebView widget to host the browser’s pages
• Applications using the WebView component must request INTERNET permission.
Browsing Power
The browser will access the Internet through whatever means are available to that specific
device at the present time (WiFi, cellular network, Bluetooth-tethered phone,etc.) .The
WebKit rendering engine used to display webpages includes methods to

1.navigate forward and backward through a history,


2.zoom in and out,
3.perform text searches,
4.load data
5.stop loading and more.
Note
In order for your Activity to access the Internet and load web pages in a WebView, you must
add the INTERNET permissions to your Android Manifest file:

<uses-permission android:name="android.permission.INTERNET"/> This


must be a child of the <manifest> element.
Default settings:
• no zoom controls,
• JavaScript disabled, • default font sizes, • and so on.
You can change the settings of a WebView control using the getSettings() The getSettings()
method returns a Web Settings object that can be used to configure the desired WebView
settings.

Change Default Setting

• Enabling and disabling zoom controls using thesetSupportZoom() and


setBuiltInZoomControls()methods
• Enabling and disabling JavaScript using the setJavaScriptEnabled()
method
• Enabling and disabling mouse overs using the setLightTouchEnabled() method
• Configuring font families, text sizes, and other display characteristics
Browser Commands

There is no navigation toolbar with the WebView widget (saving space). You could supply
the UI –such as a Menu–to execute the following operations:
• reload() - to refresh the currently-viewed Web page
• goBack() - to go back one step in the browser history, and can GoBack() to determine if
there is any history to trace back
• goForward() - to go forward one step in the browser history, and can GoForward() to
determine if there is any history to go forward to
• goBackOrForward() - to go backwards or forwards in the browser history, where
negative/positive numbers represent a count of steps to go
• canGoBackOrForward() - to see if the browser can go backwards or forwards the stated
number of steps (following the same positive/negative convention as goBackOrForward())
• clearCache() - to clear the browser resource cache and
• clearHistory() - to clear the browsing history
Example AndroidManifestfile.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.webview">

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

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:usesCleartextTraffic="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WebView"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter> </activity>

</application> </manifest>

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">

<TextView android:text="WebView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview" android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WebView Example"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText" android:hint="Enter
Text" android:focusable="true"
android:textColorHighlight="#ff7eff15"
android:textColorHint="#ffff25e6"
android:layout_marginTop="46dp"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView" />

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter" android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView" />

<WebView android:id="@+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>

Mainactivity.java

package com.example.webview;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle; import android.view.View;
import android.webkit.WebView; import
android.webkit.WebViewClient; import
android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


Button b1;
EditText ed1;
WebView wv1; @Override protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
ed1=(EditText)findViewById(R.id.editText);

wv1 = (WebView) findViewById(R.id.webView);


wv1.setWebViewClient(new MyBrowser());

b1.setOnClickListener(new View.OnClickListener() {
@Override public void
onClick(View v) { String url =
ed1.getText().toString();
wv1.getSettings().setLoadsImagesAutomatica
lly(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl(url);
}
});
}
private class MyBrowser extends WebViewClient {
@Override public boolean shouldOverrideUrlLoading(WebView
view, String url) {
view.loadUrl(url); return true;
}
}
}

Still Image
Still images are visual representations that do not move. Text is ideal for transmitting
information in a highly articulate manner that can be consistently interpreted irrespective of
the
user. Still images, however, allow the content creator to convey information which can be more
freely interpreted by the user. A picture does indeed paint a thousand words but the meaning
of the picture will vary from user to user.
A type of digital object that is created from the digitization of still image (textual documents
and photographs) originals.

A still image is data in which a grid or raster of picture elements (pixels) has been mapped to
represent a visual subject, e.g., the page of a book or a photograph. The term raster data is
often contrasted with vector data, in which geometrical points, lines, curves, and shapes are
based upon mathematical equations, thus creating an image without specific mapping of data
to pixels. Bit-depth, spatial resolution, and color encoding, for example, are all important
characteristics of still images. Raster images can be stored in a variety of data formats, such
as TIFF (.tif).
• JPEG: Joint Photographic Experts Group
• TIFF: Tagged Image File Format PDF: Portable Document Format

Video

MainActivity.java

package com.example.videoplayer;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle; import


android.net.Uri; import android.os.Bundle;
import android.view.View; import
android.widget.Button; import
android.widget.MediaController; import
android.widget.VideoView;
import androidx.appcompat.app.AppCompatActivity; public
class MainActivity extends AppCompatActivity {
private VideoView videoView;
Button Playbtn;
String videoUrl = "F:\\BMU\\Android\\Videos\\Tutorial Install Android.mp4";
@Override protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); videoView
= findViewById(R.id.idVideoView);
Playbtn =findViewById(R.id.Playbtn);

Playbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" +
R.raw.tutorialinstallandroid);
videoView.setVideoURI(uri);
MediaController mediaController = new MediaController(MainActivity.this);
mediaController.setAnchorView(videoView);
mediaController.setMediaPlayer(videoView);
videoView.setMediaController(mediaController); videoView.start();
}
});
}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.videoplayer">

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.VideoPlayer"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter> </activity> </application>

</manifest>

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">

<!-- adding VideoView to the layout -->

<TextView
android:id="@+id/idTVHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp" android:text="Video
View in Android"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="20sp"
android:textStyle="bold" />
<VideoView
android:id="@+id/idVideoView"
android:layout_width="354dp"
android:layout_height="357dp"
android:layout_below="@id/idTVHeading"
android:layout_centerVertical="true"
android:layout_marginTop="257dp" />

<Button android:id="@+id/Playbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="184dp"
android:layout_marginBottom="496dp"
android:text="Play Video" />

</RelativeLayout>

Unit-9. Telephony APIs

9.1 Working with Telephony Utilities, Using SMS, Making and Receiving
Phone Calls, Notifying a User, Notifying with Status Bar,
9.2 Vibrating the Phone, Blinking the Lights, Making Noise, Customizing the
Notification, Designing Useful Notification.

APIs-Application Programming Interface Telephony APIs

The telephony API is used to among other things monitor phone information
including the current states of the phone, connections, network etc. In this example, we
want to utilize the telephone manager part of the Application Framework and use phone
listeners (PhoneStateListener) to retrieve various phone states.
Android Telephony framework provides us the functionalities of the mobile. It gives
us information about functionalities like calls, SMS, MMS, network, data services, IMEI
number, and so on.

For better understanding, you can consider Dialer, Browser, Sim App toolkit, Broadcast
receivers, and so on.

Android Telephony and Telephony Manager

Android Telephony is a package provided by Android to operate and get information


about the network interfaces and device details. It has several interfaces and classes that are
used to provide various functionalities.

Android Telephony Manager is one such class that is present in the


android.telephony package. It provides you with several methods to get the network or
telephony information and know its current state. Along with this, you also get the subscriber
information using the Telephony Manager methods.

To access the Telephony Manager in your programming, you can simply import the
android.telphony.TelephonyManager class.

After that, you need to use the getSystemService() to create the TelephonyManager
object, and then you can use it to get system information.

Android TelephonyManager

The android.telephony.TelephonyManager class provides information about the telephony


services such as subscriber id, sim serial number, phone network type etc. Moreover, you can
determine the phone state etc.

val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as


TelephonyManager

Architecture of Android Telephony

The architecture of Android Telephony is subdivided into four layers. These four layers
help it interact with users and low-level devices like your network adapters.
The four layers involved in the Android Telephony are described below:
1. Communication Processor
The communication processor is used to communicate and collect data from various
peripherals. It usually takes input and processes and distributes it among the communication
network.
2. Radio Interface Layer (RIL)
The Radio Interface Layer is an interface through which the hardware components
interact with the frameworks. It’s a bridge with protocols for the Telephony services and is
therefore known as protocol stack for Telephone. The RIL consist of two components that are
as follows:
a. RIL Daemon –

RIL Daemon starts up immediately when your device starts. The RIL Daemon reads
system properties and makes the libraries ready that are required by Vendor RIL.
b. Vendor RIL –

Vendor RIL is a library that is specific to each network modem.


3. Framework Services
Framework services consist of various packages and assists the Telephony Manager in
directing all the application API requests to RIL. The framework services start immediately
when the device boots up.
4. Application
Applications are the last layer of the Telephony architecture. The applications are
used directly by the user to interact with the Telephony Services. Some of the standard
applications are IMEI checker, Dialer, SIM Toolkit, Browser, etc.

Example

AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.example.telephonyutilites"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.TelephonyUtilites"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter> </activity>
<service android:name=".MyService"
android:enabled="true" android:exported="true"/>
</application>

</manifest>

Activitymain.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">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="150dp"
android:fontFamily="adamina"
android:text="Mobile Details:"
android:textSize="20dp" />

</RelativeLayout>

ActivityMain.java

package com.example.telephonyutilites;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint; import


android.os.Bundle; import android.app.Activity;
import android.content.Context; import
android.os.Bundle;
import android.telephony.TelephonyManager; import
android.widget.TextView;

public class MainActivity extends AppCompatActivity {


TextView tv; @Override protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
tv =
findViewById(R.id.textView);
//instance of TelephonyManager
TelephonyManager tele_man = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
String nwcountryISO = tele_man.getNetworkCountryIso();
String SIMCountryISO = tele_man.getSimCountryIso();

String PhoneType = ""; // it'll hold the type of phone i.e CDMA / GSM/ None
int phoneType = tele_man.getPhoneType(); switch (phoneType) { case
(TelephonyManager.PHONE_TYPE_CDMA): PhoneType =
"CDMA";
break; case
(TelephonyManager.PHONE_TYPE_GSM): PhoneType
= "GSM";
break; case
(TelephonyManager.PHONE_TYPE_NONE):
PhoneType = "NONE"; break;

}
// true or false for roaming or not
boolean checkRoaming = tele_man.isNetworkRoaming();
String data = "Your Mobile Details are enlisted below: \n";
data += "\n Network Country ISO is - " + nwcountryISO; data
+= "\n SIM Country ISO is - " + SIMCountryISO; data
+= "\n Network type is - " + PhoneType; data
+= "\n Roaming on is - " + checkRoaming;
//Now we'll display the information
tv.setText(data);//displaying the information in the textView
}}

Using SMS
SMSManager class manages operations like sending a text message, data message, and
multimedia messages (MMS). For sending a text message method sendTextMessage() is used
likewise for multimedia message sendMultimediaMessage() and for data message
sendDataMessage() method is used. The details of each function are:

Function Description

sendTextMessage(String destinationAddress,
sendTextMessage() String scAddress, String text, PendingIntent sentIntent,
PendingIntent deliveryIntent, long messageId)

sendDataMessage(String destinationAddress, String


sendDataMessage() scAddress, short destinationPort, byte[] data,
PendingIntent sentIntent, PendingIntent deliveryIntent)
sendMultimediaMessage(Context context,
sendMultimediaMessage() Uri contentUri, String locationUrl,
Bundle configOverrides, PendingIntent sentIntent

You can create a 2 emulator and Send SMS,Receive SMS 1st emulator to 2nd emulator
calling no-5554 and 5556

Note:-Set the permission in emulator->setting->apps & Notifications->Click


sendSms(applicationname)->click permission->allow.

Activitymain.xml

package com.example.sendsms;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle; import
android.telephony.SmsManager; import
android.view.View; import android.widget.Button; import
android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText phonenumber,message;
Button send; @Override protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); send=findViewById(R.id.button);
phonenumber=findViewById(R.id.editText); message=findViewById(R.id.editText2);
send.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {


String number=phonenumber.getText().toString(); String
msg=message.getText().toString(); try {
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(number,null,msg,null,null);
Toast.makeText(getApplicationContext(),"Message
Sent",Toast.LENGTH_LONG).show();
}catch (Exception e)
{
Toast.makeText(getApplicationContext(),"Some fiedls is
Empty",Toast.LENGTH_LONG).show();
}
}
});
}
}
Androidmanifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.sendsms">
<uses-permission android:name="android.permission.SEND_SMS"/>
<dist:module dist:instant="true" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.SendSMS"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter> </activity> </application>

</manifest>

Mainactivity,java

<?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">

<EditText

android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" android:hint="Enter number"
android:inputType="textPersonName" />
<EditText

android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" android:hint="Enter message"
android:inputType="textPersonName" />

<Button

android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" android:layout_marginLeft="60dp"
android:layout_marginRight="60dp"
android:text="SEND" />

</LinearLayout>

Making and Receiving Phone Calls

Android provides Built-in applications for phone calls, in some occasions we may need to
make a phone call through our application. This could easily be done by using implicit Intent with
appropriate actions. Also, we can use PhoneStateListener and TelephonyManager classes, in order to
monitor the changes in some telephony states on the device.

This chapter lists down all the simple steps to create an application which can be used
to make a Phone Call. You can use Android Intent to make phone call by calling built-in
Phone Call functionality of the Android. Following section explains different parts of our
Intent object required to make a call.
Intent Object - Action to make Phone Call

You will use ACTION_CALL action to trigger built-in phone call functionality
available in Android device. Following is simple syntax to create an intent with
ACTION_CALL action

Intent phoneIntent = new Intent(Intent.ACTION_CALL);

You can use ACTION_DIAL action instead of ACTION_CALL, in that case you
will have option to modify hardcoded phone number before making a call instead of making a
direct call.

Intent Object - Data/Type to make Phone Call

To make a phone call at a given number 91-000-000-0000, you need to specify tel: as
URI using setData() method as follows −
phoneIntent.setData(Uri.parse("tel:91-000-000-0000"));

The interesting point is that, to make a phone call, you do not need to specify any extra data
or data type.

You can create a 2 emulator and calling 1st emulator to 2nd emulator calling no-5554 and
5556.

Note:-Set the permission in emulator->setting->apps & Notifications->Click


sendSms(applicationname)->click permission->allow.

Example MainActivity.java
package com.example.callingapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat; import
android.Manifest; import android.content.Intent; import
android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import android.view.View; import android.widget.Button;


import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


private Button button;
EditText edittext; @Override protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); button = (Button)
findViewById(R.id.buttonCall); edittext =
findViewById(R.id.editText);

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phone_number = edittext.getText().toString();
callIntent.setData(Uri.parse("tel:" + phone_number));

if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(callIntent);
}
});
}
}

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"
android:orientation="vertical" tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_alignParentTop="true" android:hint="Enter
Number" android:layout_marginTop="98dp" />

<Button android:id="@+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="164dp"
android:layout_marginBottom="505dp"
android:text="Call " />

</RelativeLayout>

Activitymanifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.callingapp" android:versionCode="1"
android:versionName="1.0">

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

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.CallingApp"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </activity> </application> </manifest>

Notifying a User, Notifying with Status Bar

A Notification is a message you can display to the user outside of your application's
normal UI. When you tell the system to issue a notification, it first appears as an icon in the
notification area.
To see the details of the notification, the user opens the notification drawer. Both the
notification area and the notification drawer are system-controlled areas that the user can
view at any time.

Activity_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: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="ANDROID NOTIFICATION"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.091"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/button"
android:layout_marginBottom="112dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Notify"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Activitymain.java

package com.example.notification;

import androidx.appcompat.app.AppCompatActivity; import


androidx.core.app.NotificationCompat;

import android.app.NotificationChannel;
import android.os.Build; import android.os.Bundle;
import android.app.NotificationManager;
import android.app.PendingIntent; import
android.content.Context; import
android.content.Intent; import
android.view.View; import
android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button; @Override protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel channel = new NotificationChannel("My Notification","My
Notification",NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNotification();
}
});
}

private void addNotification() { NotificationCompat.Builder builder =


new NotificationCompat.Builder(MainActivity.this,"My Notification")
.setSmallIcon(R.drawable.ic_launcher_background) //set icon for notification
.setContentTitle("Display Notification Tittle") //set title of
notification
.setContentText("This is a notification message,also display
Notification")//this is notification message
.setAutoCancel(true) // makes auto cancel of notification
.setPriority(NotificationCompat.PRIORITY_DEFAULT); //set priority of
notification

// Add as notification
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}}

Vibrating the Phone

In android, using vibrate service, we can vibrate android mobile. This example
demonstrate about how to make an Android device vibrate

Mainactivity.java

package com.example.vibratingphone;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle; import
android.content.Context; import
android.content.Intent; import android.os.Build;
import android.os.VibrationEffect; import
android.os.Vibrator; import android.view.View;
import android.widget.Button; import
android.widget.LinearLayout; import
android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


int view = R.layout.activity_main;
Button textView;
@Override protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
final LinearLayout parent = findViewById(R.id.parent); textView
= findViewById(R.id.text);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(500,
VibrationEffect.DEFAULT_AMPLITUDE));
} else {
vibrator.vibrate(500);
}
}
});
}
}

androidmanifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.vibratingphone">

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


<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.VibratingPhone"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </activity> </application>

</manifest>

Activitymain.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"
android:id="@+id/parent" android:gravity="center"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">

<Button android:id="@+id/text"
android:textSize="18sp" android:text="Click
here to vibrate"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

Blinking the Lights

All the beginners who are into the android development world should build a simple
android application that can turn on/off the flashlight or torchlight by clicking a Button. So at
the end of this article, one will be able to build their own android flashlight application with a
simple layout.
Activitymain.xml

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


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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="100dp"
android:text="Flashlight" android:textSize="50sp"
android:textStyle="bold|italic" />

<!--This is the simple divider between above


TextView and ToggleButton-->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginStart="32dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="32dp"
android:background="@android:color/darker_gray" />

<!--This toggle button by default toggles


between the ON and OFF we no need to set
separate TextView for it--> <ToggleButton
android:id="@+id/toggle_flashlight"
android:layout_width="200dp"
android:layout_height="75dp"
android:layout_gravity="center"
android:layout_marginTop="32dp"
android:onClick="toggleFlashLight"
android:textSize="25sp" />

</LinearLayout>

MainActivity.java

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

import android.content.Context; import


android.hardware.camera2.CameraAccessException; import
android.hardware.camera2.CameraManager;
import android.os.Build; import
android.os.Bundle; import android.view.View;
import android.widget.Toast; import
android.widget.ToggleButton;
import androidx.annotation.RequiresApi;

public class MainActivity extends AppCompatActivity {


private ToggleButton toggleFlashLightOnOff; private
CameraManager cameraManager; private String
getCameraID;
@Override protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
toggleFlashLightOnOff = findViewById(R.id.toggle_flashlight);
cameraManager = (CameraManager)
getSystemService(Context.CAMERA_SERVICE);
try {
getCameraID = cameraManager.getCameraIdList()[0]; }
catch (CameraAccessException e) {
e.printStackTrace();
}
}
@RequiresApi(api = Build.VERSION_CODES.M) public
void toggleFlashLight(View view) {
if (toggleFlashLightOnOff.isChecked()) {
try {

cameraManager.setTorchMode(getCameraID, true);
Toast.makeText(MainActivity.this, "Flashlight is turned ON",
Toast.LENGTH_SHORT).show();
} catch (CameraAccessException e) {

e.printStackTrace();
}
} else { try
{

cameraManager.setTorchMode(getCameraID, false);
Toast.makeText(MainActivity.this, "Flashlight is turned OFF",
Toast.LENGTH_SHORT).show();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override public
void finish() {
super.finish();
try {

cameraManager.setTorchMode(getCameraID, false);
Toast.makeText(MainActivity.this, "Flashlight is turned OFF",
Toast.LENGTH_SHORT).show();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
Androidmanifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.flashlight">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.flash" />
<application

android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.FlashLight"
tools:targetApi="31">
<activity

android:name=".MainActivity"
android:exported="true"> <intent-
filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter> </activity> </application>
</manifest>

Making Noise

1.First Add a button in Android Studio.


2.Go to MainActivity.java. text and give an id to the button
3.Now add the media player.
4.Go to res > New > Android resource directory

5.Now you can find raw under the res category.


6.Add a sample.mp3 file under raw.
7.Add the setOnclicklistener, so that when the button is pressed you will hear the sound.
8.Go to the live device view. On pressing the button, you will hear a long sound.

Example

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">

<TextView

android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" android:layout_marginTop="30dp"
android:text="Audio Controller" />

<Button

android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="48dp"
android:text="start" />

<Button

android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="pause" />

</RelativeLayout>

MainActivity.java

package com.example.mediaplayer; import


androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle; import android.media.MediaPlayer;
import
android.os.Environment; import android.view.View;
import android.view.View.OnClickListener; import
android.widget.Button;

public class MainActivity extends AppCompatActivity {


Button start,pause;
@Override protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.button1);
pause=(Button)findViewById(R.id.button2);

//creating media player final MediaPlayer mp=


MediaPlayer.create(MainActivity.this, R.raw.kesariya);

start.setOnClickListener(new OnClickListener() {
@Override public void
onClick(View v) { mp.start();
}
});
pause.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.pause();
}
});

}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.mediaplayer">

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MediaPlayer"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

You might also like