ch1 9
ch1 9
5. Installation
6. Android SDK
8. Application Context
9. Application Tasks
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 –
Android Architecture:-
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.
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.
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.
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
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.
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.
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 −
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.
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.
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
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.
Psion
EPOC
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-
OHA member companies back the open platform concept for a number of reasons, as follows:
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.
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.
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.
―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.
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
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
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
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.
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.
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
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.
The AndroidManifest.xml file contains information of your package, including components of the
application such as activities, services, broadcast receivers, content providers etc.
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.
<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>
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.
<intent-filter> intent-filter is the sub-element of activity that describes the type of intent 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
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
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.
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.
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
android:name="android.hardware.sensor.proximity" />
android:reqTouchScreen="stylus" />
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.
<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.
using the Android manifest tag <intent-filter> in the application’s AndroidManifest.xml file
The following tag of XML configures the Activity class called MultimediaMenuActivity as the
<activity android:name=".MultimediaMenuActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</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
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>
<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
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.
App permissions help support user privacy by protecting access to the following:
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
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.
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.
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 −
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;
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" >
</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 –
<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" >
<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-
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
Button Example
Activity_main.xml
MainActivity.java
Activity_main.xml
MainActivity.java
}
});
}
}
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>
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
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
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.
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)
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >
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;
<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.
<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" />
<!--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/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)
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String dateTime;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
// get the Long type value of the current system date Long dateValueInLong =
System.currentTimeMillis();
dateTimeInLongTextView.setText(dateValueInLong.toString());
// 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) {} }
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 −
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;
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" >
</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 –
<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" >
<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-
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
Button Example
Activity_main.xml
MainActivity.java
Activity_main.xml
MainActivity.java
}
});
}
}
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>
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
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
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.
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)
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >
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;
<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.
<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" />
<!--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/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)
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String dateTime;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
// get the Long type value of the current system date Long dateValueInLong =
System.currentTimeMillis();
dateTimeInLongTextView.setText(dateValueInLong.toString());
// 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) {} }
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 −
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;
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" >
</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 –
<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" >
<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-
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
Button Example
Activity_main.xml
MainActivity.java
Activity_main.xml
MainActivity.java
}
});
}
}
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>
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
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
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.
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)
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >
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;
<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.
<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" />
<!--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/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)
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String dateTime;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
// get the Long type value of the current system date Long dateValueInLong =
System.currentTimeMillis();
dateTimeInLongTextView.setText(dateValueInLong.toString());
// 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) {} }
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.
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.
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.
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.
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.
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.
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
<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;
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();
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;
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();
}
});
}
}
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.
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:
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:
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.
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:
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String dbQuery = "CREATE TABLE Items (id INTEGER PRIMARY KEY
AUTOINCREMENT,name TEXT, description TEXT)";
sqLiteDatabase.execSQL(dbQuery);
}
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.
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.
//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[]).
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 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.
• 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.
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
;
@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;
}
}
main_activity.xml
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;
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();
}
activity_view_person.xml
<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;
db = new DatabaseHelper(this);
edId = findViewById(R.id.edId);
edName = findViewById(R.id.edName);
edAdd = findViewById(R.id.edAdd);
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.
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
browser, etc. This part must be unique for every content provider. ●
types of data that are not related to each other like audio and video files. ●
Update, and Delete. These operations are often termed as CRUD operations.
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;
Activitymain.xml
<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
● 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
<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;
A device can have various types of network connections. This chapter focuses on using either
a Wi-Fi or a mobile network connection.
You need to instantiate an object of this class by calling getSystemService() method. Its
syntax is given below −
This method returns an array of NetworkInfo. So you have to receive it like this.
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−
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.
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
<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" />
</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;
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;
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" />
</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: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>
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.
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.
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 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 –
Example
AndroidManifest.xml
<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" />
</manifest>
Activitymain.xml
<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;
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)
You can create a 2 emulator and Send SMS,Receive SMS 1st emulator to 2nd emulator
calling no-5554 and 5556
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;
</manifest>
Mainactivity,java
<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>
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
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.
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.
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;
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
<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
<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>
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
<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 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();
}
});
}
// Add as notification
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}}
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;
androidmanifest.xml
</manifest>
Activitymain.xml
<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>
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
<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" />
</LinearLayout>
MainActivity.java
package com.example.flashlight;
import androidx.appcompat.app.AppCompatActivity;
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
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>
Making Noise
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
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>