0% found this document useful (0 votes)
2 views110 pages

Application Development Using Advanced Android

The document provides an overview of Android, an open-source operating system developed by the Open Handset Alliance led by Google, highlighting its history, features, architecture, and development tools. It details the Android SDK, including its components like build tools and emulators, and explains the structure of an Android application, including the AndroidManifest.xml file and its elements. The document serves as a foundational guide for mobile application development using Android, aimed at students and developers in the field.

Uploaded by

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

Application Development Using Advanced Android

The document provides an overview of Android, an open-source operating system developed by the Open Handset Alliance led by Google, highlighting its history, features, architecture, and development tools. It details the Android SDK, including its components like build tools and emulators, and explains the structure of an Android application, including the AndroidManifest.xml file and its elements. The document serves as a foundational guide for mobile application development using Android, aimed at students and developers in the field.

Uploaded by

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

Application Development using

Advanced Android
Mobile Application Development using Android

UNIT : 1 Introduction to Android & Android


Application Design

What is Android?
● Android is an open-source operating system based on Linux with a Java programming
interface for mobile devices such as Smartphone (Touch Screen Devices who supports
Android OS) as well for Tablets too.
● Android was developed by the Open Handset Alliance (OHA), which is led by Google.
The Open Handset Alliance (OHA) is a consortium of multiple companies like Samsung,
Sony, Intel and many more to provide services and deploy handsets using the android
platform.
● On September 23, 2008, Android was introduced by Andy Rubin, Larry Page, Sergey Brin,
Cole Brodman, Christopher Schlaeffer and Peter Chou at a press conference in a New
York subway station

The Open Handset Alliance


● The Open Handset Alliance (OHA) is a consortium of 84 firms to develop open standards
for mobile devices.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 2
Mobile Application Development using Android
● The Open Handset Alliance (OHA) is a consortium whose goal is to develop open
standards for mobile devices, promote innovation in mobile phones and provide a better
experience for consumers at a lower cost.
● Member firms include HTC, Sony, Dell, Intel, Motorola, Qualcomm, Texas Corporation,
Nvidia, and Wind River Systems.
● The OHA was established on 5 November 2007, led by Google with 34
members, including mobile handset makers, application developers, some mobile
carriers and chip makers.
● Android, the flagship software of the alliance (first developed by Google in 2007), is
based on an open-source license and has competed against mobile platforms from
Apple (iOS), Microsoft (WindowsPhone), Nokia (Symbian), HP (formerly Palm), Samsung
Electronics / Intel (Tizen, bada), and BlackBerry (BlackBerry OS).
● As part of its efforts to promote a unified Android platform, OHA members are
contractually forbidden from producing devices that are based on competing forks of
Android.
● The first phone was released in September 2008 by HTC. It was called T Mobile g1 in
the US and HTC dream in other parts of the world.

Android History
● Initially, Google launched the first version of Android platform on Nov 5, 2007, from that
onwards Google released a lot of android versions under a codename based on desserts,
such as Apple Pie, Banana Bread, Cupcake, Donut, Éclair, Froyo, Gingerbread, Jellybeans,
Kitkat, Lollipop, marshmallow, etc. and made a lot of changes and additions to the
android platform.
● The following table lists the different version details of android which was released by
Google from 2007 to till date.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 3
Mobile Application Development using Android

Android Features
Android is a powerful open-source operating system which provides a lot of great features,
those are
● It’s open-source and we can customize the OS based on our requirements.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 4
Mobile Application Development using Android
● It supports connectivity for GSM, CDMA, WIFI, NFC, Bluetooth, etc. for telephony or
data transfer. It will allow us to make or receive a calls / SMS messages and we can send
or retrieve data across mobile networks
● By using WIFI technology we can pair with other devices using apps
● Android has multiple APIs to support location-based services such as GPS
● We can perform all data storage related activities by using lightweight database SQLite.
● It has a wide range of media supports like AVI, MKV, FLV, MPEG4, etc. to play or record a
variety of audio/video and having a different image format like JPEG, PNG, GIF, BMP,
MP3, etc.
● It has extensive support for multimedia hardware control to perform playback or
recording using camera and microphone
● It has an integrated open-source WebKit layout based web browser to support HTML5,
CSS3
● It supports a multi-tasking, we can move from one task window to another and multiple
applications can run simultaneously
● It will give a chance to reuse the application components and the replacement of native
applications.
● We can access the hardware components like Camera, GPS, and Accelerometer
● It has support for 2D/3D Graphics

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 5
Mobile Application Development using Android

Android Architecture(Architecture Stack)


● Android architecture is a software stack of components to support mobile device needs.
Android software stack contains a Linux Kernel, a collection of c/c++ libraries which are
exposed through an application framework services, runtime, and application.
● Following are main components of android architecture those are:
○ Applications
○ Android Framework
○ Android Runtime
○ Platform Libraries
○ Linux Kernel
● In these components, the Linux Kernel is the main component in android to provide its
operating system functions to mobile and Dalvik Virtual Machine (DVM) which is
responsible for running a mobile application.
● Following is the pictorial representation of android architecture with different
components.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 6
Mobile Application Development using Android

Applications
● The top layer of the android architecture is Applications. The native and third-party
applications like contacts, email, music, gallery, clock, games, etc. whatever we will build
those will be installed on this layer only.
● The application layer runs within the Android run time using the classes and services
made available from the application framework.
Application Framework
● The Application Framework provides the classes used to create Android applications. It
also provides a generic abstraction for hardware access and manages the user interface
and application resources. It basically provides the services through which we can create
a particular class and make that class helpful for the Application creation.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 7
Mobile Application Development using Android
● The application framework includes services like telephony service, location services,
notification manager, NFC service, view system, etc. which we can use for application
development as per our requirements.
Android Runtime
● The Android Runtime environment is an important part of Android rather than an
internal part and it contains components like core libraries and the Dalvik virtual
machine. The Android run time is the engine that powers our applications along with the
libraries and it forms the basis for the application framework.
● Dalvik Virtual Machine (DVM) is a register-based virtual machine like Java Virtual
Machine (JVM). It is specially designed and optimized for android to ensure that a device
can run multiple instances efficiently. It relies on the Linux kernel for threading and
low-level memory management.
● The core libraries in android runtime will enable us to implement android applications
using standard JAVA programming language.
Platform Libraries
● The Platform Libraries include various C/C++ core libraries and Java-based libraries such
as SSL, libc, Graphics, SQLite, Webkit, Media, Surface Manger, OpenGL, etc. to provide
support for Android development.
● The following are the summary details of some core android libraries available for
android development.
○ Media library for playing and recording audio and video formats
○ The Surface manager library to provide a display management
○ SGL and OpenGL Graphics libraries for 2D and 3D graphics
○ SQLite is for database support and FreeType for font support
○ Web-Kit for web browser support and SSL for Internet security.
Linux Kernel

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 8
Mobile Application Development using Android
● Linux Kernel is a bottom layer and heart of the android architecture. It manages all the
drivers such as display drivers, camera drivers, Bluetooth drivers, audio drivers, memory
drivers, etc. which are mainly required for the android device during the runtime.
● The Linux Kernel will provide an abstraction layer between the device hardware and the
remainder of the stack. It is responsible for memory management, power management,
device management, resource access, etc.

Android SDK
● Android SDK stands for Android Software Development Kit which is developed by
Google for Android Platform. With the help of Android SDK, we can create Android Apps
easily.
● Android SDK is a collection of libraries and Software Development tools that are
essential for Developing Android Applications. Whenever Google releases a new version
or update of Android Software, a corresponding SDK also releases with it. In the updated
or new version of SDK, some more features are included which are not present in the
previous version.
● Android SDK consists of some tools which are very essential for the development of
Android Application. These tools provide a smooth flow of the development process
from developing and debugging.
● Android SDK is compatible with all operating systems such as Windows, Linux, macOS,
etc.

Android SDK Tools


● Android SDK tool is an important component of Android SDK. It consists of a complete
set of development and debugging tools. Below are the SDK developer tools:
● Android SDK Build tool.
○ Android Emulator.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 9
Mobile Application Development using Android
○ Android SDK Platform-tools.
○ Android SDK Tools.

Android SDK Build-Tools


● Android SDK build tools are used for building actual binaries of Android Apps. The main
functions of Android SDK Build tools are built, debug, run and test Android applications.
The latest version of the Android SDK Build tool is 30.0.3. While downloading or
updating Android in our System, one must ensure that its latest version is downloaded
in SDK Components.

Android Emulator
● An Android Emulator is a device that simulates an Android device on your system.
Suppose we want to run our android application that we code. One option is that we will
run this on our Android Mobile by Enabling USB Debugging on our mobile. Another
option is using Android Emulator. In Android Emulator the virtual android device is
shown on our system on which we run the Android application that we code.
● Thus, it simply means that without needing any physical device Android SDK component
“Android Emulator” provides a virtual device on the System where we run our
Application. The emulator’s come with the configuration for Various android phones,
tablets, Wear OS, and Android TV devices.

Android SDK Platform-tools


● Android SDK Platform-tools is helpful when we are working on a Project and they will
show the error messages at the same time. It is specifically used for testing. It includes:
● Android Debug Bridge (ADB), is a command-line tool that helps to communicate with
the device. It allows us to perform actions such as Installing Apps and Debugging Apps
etc.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 10
Mobile Application Development using Android
● Fastboot allows you to flash a device with a new system image.
● Systrace tools help to collect and inspect timing information. It is very crucial for App
Debugging.

AVD
● Android Virtual Device(AVD) is a software representation of an actual world physical
android device. In other words, it doesn’t have any physical existence but behaves like a
physical android device itself. It has everything which you think a physical machine
would have.
● Whether it’s storage, audio, notifications, applications, etc., all are present in the
android virtual device. Most of the android virtual devices are self-configurable. In other
words, you can configure the hardware and the version of android which you wish to
operate on.
● Android Virtual Device brings many features that make it so popular among developers,
gamers, and android users. Let’s see a few of the features of AVD before proceeding with
the setup.
○ It is self-configurable and allows users to pick up any android version of their
choice.
○ It provides storage and also allows applications to be installed.
○ This behaves mostly like your actual physical device and provides most of the
functionalities.
○ You can alter the appearance of your android virtual device depending on your
needs.
○ Android Virtual Device is as secure as your physical device.

Steps to create a new Android Project

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 11
Mobile Application Development using Android

● Step 1: Open Android Studio.


● Step 2: In the Welcome to Android Studio dialog, click Start a new Android Studio
project.
● Step 3: Select Empty Activity (not the default). ...
● Step 4: Give your application a name such as My First App.
● Step 5: Make sure the Language is set to Java.
● Step 6: Leave the defaults for the other fields.
● Step 7: Click Finish.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 12
Mobile Application Development using Android

Android IDE

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 13
Mobile Application Development using Android

Anatomy(Directory Structure) of android


application

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 14
Mobile Application Development using Android

Sr.N Folder, File & Description


o.

Java
This contains the .java source files for your project. By default, it includes an
1
MainActivity.java source file having an activity class that runs when your app is
launched using the app icon.

res/drawable-hdpi
2
This is a directory for drawable objects that are designed for high-density screens.

res/layout
3
This is a directory for files that define your app's user interface.

res/values
4 This is a directory for other various XML files that contain a collection of resources,
such as strings and colors definitions.

AndroidManifest.xml
5 This is the manifest file which describes the fundamental characteristics of the app
and defines each of its components.

Build.gradle
6 This is an auto generated file which contains compileSdkVersion, buildToolsVersion,
applicationId, minSdkVersion, targetSdkVersion, versionCode and versionName

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 15
Mobile Application Development using Android

Android Manifest File, Permissions and its


common settings
● The AndroidManifest.xml file contains information about 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 provide profiling and other information. ∙ This information
is removed just before the application is published etc.
● A Closer Look at the Application Manifest The following XML snippet shows a typical
manifest node:

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 16
Mobile Application Development using Android

Elements of the AndroidManifest.xml file


● The elements used in the above xml file are described below.
● <manifest>
○ manifest is the root element of the AndroidManifest.xml file. It has a 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.
○ The commonly used attributes 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 an application and represents an activity that must
be defined in the AndroidManifest.xml file.
○ It has many attributes such as label, name, theme, launchMode etc. ∙
● android:label represents a label i.e. displayed on the screen.
● android:name represents a name for the activity class. It is a required attribute.
● <intent-filter>
○ intent-filter is the sub-element of activity that describes the type of intent to
which activity, service or broadcast receiver can respond to.
● <action>
○ It adds an action for the intent-filter. The intent-filter must have at least one
action element.
● <category>
○ It adds a category name to an intent-filter.
● <uses-permissions>
○ used to specify permissions that are requested for the purpose of security.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 17
Mobile Application Development using Android

Working with different types of resources


● String : XML resource that carries a string value.
● Bool : XML resource that carries a boolean value.
● Color : XML resource that carries a color value (a hexadecimal color).
● Dimension : XML resource that carries a dimension value (with a unit of measure).
● ID : XML resource that provides a unique identifier for application resources and
components.
● Integer : XML resource that carries an integer value.
● Integer Array : XML resource that provides an array of integers.

A Simple Example
<resources>
<string name=”app_name”>To Do List</string>
<color name=”app_background”>#000</color>
<dimen name=”default_border”>5px</dimen>
<string-array name=“string_array“>
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</string-array>
<array name=“integer_array“>
<item>3</item>
<item>2</item>
<item>1</item>
</array>
</resources>

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 18
Mobile Application Development using Android
● Bool : A boolean value defined in XML. A bool is a simple resource that is referenced
using the value provided in the name attribute.
Syntax
<?xml version="1.0" encoding="utf-8"?>
<resources>

<bool name="bool_name">[true | false]</bool>


</resources>

EXAMPLE:
XML file saved at res/values-small/bools.xml:

<resources>
<bool name="screen_small">true</bool>
<bool name="adjust_view_bounds">true</bool>
</resources>

● This application code retrieves the Boolean:


Resources res =getResources();
boolean b=res.getBoolean(R.bool.screen_small);

Color Resource

● A color value defined in XML.


● The color is specified with an RGB value and alpha channel.
● You can use a color resource any place that accepts a hexadecimal color value.
● You can also use a color resource when a drawable resource is expected in XML (for
example, android:drawable="@color/green".
● The value always begins with a pound (#) character and then followed by the Alpha
Red-Green-Blue information in one of the following formats:

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 19
Mobile Application Development using Android
#RGB
#ARGB
#RRGGBB
#AARRGGBB

Syntax
<resources>
<color name="color_name">hex_color</color>
</resources>

EXAMPLE:
XML file saved at res/values/colors.xml:
<resources>
<color name="opaque_red">#f00</color>
</resources>

● This application code retrieves the color resource:


Resources res =getResources();
int color=res.getColor(R.color.opaque_red);

Dimension

● A dimension value defined in XML.


● A dimension is specified with a number followed by a unit of measure.
● For example: 10px, 2in, 5sp.
● The following units of measure are supported by Android:
○ dp : Density-independent Pixels – An abstract unit that is based on the physical
density of the screen. ∙ These units are relative to a 160 dpi (dots per inch)
screen, on which 1dp is roughly equal to 1px.
○ sp : Scale-independent Pixels - This is like the dp unit, but it is also scaled by the

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 20
Mobile Application Development using Android
user's font size preference. It is recommended you use this unit when specifying
font sizes, so they will be adjusted for both the screen density and the user's
preference.
○ pt : Points - 1/72 of an inch based on the physical size of the screen, assuming a
72dpi density screen.
○ px : Pixels - Corresponds to actual pixels on the screen. This unit of measure is
not recommended because the actual representation can vary across devices;
each device may have a different number of pixels per inch and may have more
or fewer total pixels available on the screen.
○ in : Inches - Based on the physical size of the screen.

Working with Style


● A style is a group of common View attribute values.
● You can apply the style to individual View controls.
● Styles can include such settings as the font to draw with or the color of text. ∙ The
specific attributes depend on the View drawn.
● In essence though each style attribute can change the look and feel of the particular
object drawn.
● Android user interface designers can group layout element attributes together in styles.
● Layout controls are all derived from the View base class,which has many useful
attributes.
● Individual controls,such as Checkbox,Button, and TextViewhave specialized attributes
associated with their behavior.
● Styles are tagged with the <style> tag and should be stored in the /res/values/ directory.
● Style resources are defined in XML and compiled into the application binary at build
time.
● Here’s an example of a simple style resource file /res/values/styles.xml containing two
styles.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 21
Mobile Application Development using Android
● one for mandatory form fields,and one for optional form fields on TextView and EditText
objects:

<resources>
<style name=”mandatory_text_field_style”>
<item name=”android:textColor”>#000000</item>
<item name=”android:textSize”>16dp</item>
<item name=”android:textStyle”>bold</item>
</style>

<style name=”optional_text_field_style”>
<item name=”android:textColor”>#0F0F0F</item>
<item name=”android:textSize”>12dp</item>
<item name=”android:textStyle”>italic</item>
</style>

</resources>

Android terminologies
The following terminologies are used in Android:

● XML: In Android, XML is used for designing the application’s UI like creating
layouts,views, buttons, text fields etc. and also used in parsing data feeds from the
internet.

● View(Widgets): A view is an UI which occupies a rectangular area on the screen to draw

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 22
Mobile Application Development using Android
and handle user events.

● Layout(ViewGroup): Layout is the parent of view. It arranges all the views in a proper
manner on the screen.

● Activity: An activity can be referred to as your device’s screen which you see. Users can
place UI elements in any order in the created window of the user's choice.

● Emulator: An emulator is an Android virtual device through which you can select the
target Android version or platform to run and test your developed application.

● Manifest file: Manifest file acts as a metadata for every application. This file contains all
the essential information about the application like app icon, app name, launcher
activity, and required permissions etc.

● Service: Service is an application component that can be used for long-running


background processes. It is not bound with any activity as there is no UI.Any other
application component can start a service and this service will continue to run even
when the user switches from one application to another.

● Broadcast Receiver: Broadcast Receiver is another building block of Android application


development which allows you to register for system and application events. It works in
such a way that, when the event triggers for the first time all the registered receivers
through this broadcast receiver will get notified for all the events by Android Runtime. To
know more about the broadcast receivers, kindly refer to Android Basic Building Blocks.

● Content Providers: Content Providers are used to share data between two
applications. This can be implemented in two ways:

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 23
Mobile Application Development using Android
○ When you want to implement the existing content provider in another
application.
○ When you want to create a new content provider that can share its data with
other applications

● Intent: Intent is a messaging object which can be used to communicate between two or
more components like activities, services, broadcast receiver etc. Intent can also be used
to start an activity or service or to deliver a broadcast message.

● Context: Object containing the global state of an application development.

● Gravity: Determine alignment of text within a view of android size. Value can include
top, bottom, left, right, center.

Activity
● An activity is the single screen in android. It is like a window or frame of Java.
● By the help of activity, you can place all your UI components or widgets in a single
screen.

Activity Life Cycle


● Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The
android Activity is the subclass of ContextThemeWrapper class.
● The 7 lifecycle method of Activity describes how activity will behave at different states.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 24
Mobile Application Development using Android

● The activity lifecycle is composed of the following states:


● onCreate(): This method is called when the activity is first created. It is responsible for
initializing the activity’s UI, such as inflating the layout and finding the views.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 25
Mobile Application Development using Android

● onStart(): This method is called when the activity becomes visible to the user. It is a
good place to start animations and other visual changes.

● onResume(): This method is called when the activity becomes the foreground activity. It
is the state in which the user can interact with the activity. This is where you should
register any listeners or start any services that need to be running while the activity is in
the foreground.

● onPause(): This method is called when the activity is no longer the foreground activity. It
is a good place to unregister listeners, save any data that needs to be saved, and stop

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 26
Mobile Application Development using Android
any services that don’t need to be running in the background.

● onStop(): This method is called when the activity is no longer visible to the user. It is a
good place to stop animations and other visual changes.

● onDestroy(): This method is called when the activity is about to be destroyed. It is a


good place to release any resources and clean up any remaining data.

● It’s important to note that an activity can also be in a “stopped” state if it is temporarily

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 27
Mobile Application Development using Android
obscured by another activity, but it will still retain its state and not be destroyed. In this
case, the onStop() method will be called, but not onDestroy(). The onRestart() method
will be called when the activity becomes visible again.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 28
Mobile Application Development using Android

Unit -2 Android User Interface Design

Basic Views

What is View?
● Views are the building block of an Android Application’s UI Interface (UI). In very blunt
terms it’s a box that users can interact with either for giving input or performing some
action. There are many views, but today we will highlight only a few most commonly
used views.
○ TextView: For displaying text contents in the UI.
○ EditTextView: For adding input area in the UI.
○ ImageView: For displaying Image contents in the UI.
○ ButtonView: For adding (action) buttons in the UI.
○ ImageButtonView: For adding (action) buttons with an image in the UI.
○ RadioButtonView: For adding radio buttons in the UI.
○ Checkbox ButtonView: For adding CheckBox buttons in the UI.

What is ViewGroup?

● ViewGroup, as the name suggests, is a special type of view that can contain
other views (children) one or more. It is an invisible container for other
views and can also contain another ViewGroup inside it. Below are some
ViewGroups

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 29
Mobile Application Development using Android

○ LinearLayout
○ RelativeLayout
○ FrameLayout
○ TableLayout
○ ConstraintLayout

Widgets(Views) of Android

TextView
● In android, TextView is a user interface control that is used to set and display the text to
the user based on our requirements. The TextView control will act as like label control
and it won’t allow users to edit the text.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 30
Mobile Application Development using Android
● In android, we can create a TextView control in two ways either in an XML layout file or
create it in an activity file programmatically.
● Attributes:

Attribute Description

android: id It is used to uniquely identify the control

android:autoLink It will automatically find and convert URLs and email addresses as
clickable links.

android: ems It is used to make the textview be exactly this many ems wide.

android:hint It is used to display the hint text when text is empty

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.

android:text It is used to display the text.

android:textColor It is used to change the color of the text.

android:gravity It is used to specify how to align the text by the view's x and y-axis.

android:maxWidth It is used to make the TextView be at most this many pixels wide.

android:minWidth It is used to make the TextView be at least this many pixels wide.

android:textSize It is used to specify the size of the text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 31
Mobile Application Development using Android

android:textAllCap It is used to present the text in all CAPS


s

android:typeface It is used to specify the Typeface (normal, sans, serif, monospace) for
the text.

android:textColor It is used to change the color of the text.

android:textColor It is used to change the color of text selection highlights.


Highlight

android:textColorL It is used to change the text color of links.


ink

android:inputType It is used to specify the type of text being placed in text fields.

android:fontFamil It is used to specify the fontFamily for the text.


y

android:editable If we set it, it specifies that this TextView has an input method.

● Create a TextView in Layout File

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 32
Mobile Application Development using Android

● In android, we can set the text of TextView control either while declaring it in the Layout
file or by using setText() method in the Activity file.
● Following is the example to set the text of TextView control while declaring it in the XML
Layout file.

● Following is another way to set the textview control programmatically in an activity file
using setText() method.

● Example

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 33
Mobile Application Development using Android
activity_main.xml

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 34
Mobile Application Development using Android
MainActivity.java

Output:

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 35
Mobile Application Development using Android

Button
● Button is a user interface control which is used to perform an action whenever the user
clicks or taps on it.
● Generally, Buttons in android will contain a text or an icon or both and perform an action
when the user touches it.
● We have a different type of buttons available to use based on our requirements, those
are ImageButton, ToggleButton, RadioButton.
● Whenever the user clicks on a Button, the Button object will receive an on-click event.
● We can define click event handler for button by adding android:onClick attribute to the
<Button> element in our XML layout file.
● The value of android:onClick attribute must be the name of the method which we need
to call in response to a click event and the Activity file which hosts the XML layout must
implement the corresponding method.
● Attributes:

Attribute Description

android: id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right, center,
top, etc.

android:text It is used to set the text.

android:textColor It is used to change the color of text.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 36
Mobile Application Development using Android

android:textSize It is used to specify the size of the text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for button control.

android:padding It is used to set the padding from left, right, top and bottom.

android:drawableBottom It’s drawable to be drawn at the bottom of text.

android:drawableRight It’s drawable to be drawn to the right of text.

android:drawableLeft It’s drawable to be drawn to the left of the text.

● Example:

activity_main.xml

MainActivity.java

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 37
Mobile Application Development using Android

Output:

AutoCompleteTextView

● In android, AutoCompleteTextView is an editable text view which is used to show the list
of suggestions based on the user typing text. The list of suggestions will be shown as a
dropdown menu from which the user can choose an item to replace the content of the
textbox.
● The AutoCompleteTextView is a subclass of the EditText class so we can inherit all the
properties of EditText in AutoCompleteTextView based on our requirements.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 38
Mobile Application Development using Android
● Generally, the dropdown list of suggestions can be obtained from the data adapter and
those suggestions will appear only after giving the number characters defined in the
Threshold limit.
● The Threshold property of AutoCompleteTextView is used to define the minimum
number of characters the user must type to see the list of suggestions.
● The dropdown list of suggestions can be closed at any time in case if no item is selected
from the list or by pressing the back or enter key.
● Attributes :

Attribute Description

android:id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right, center,
top, etc.

android:text It is used to set the text.

android:hint It is used to display the hint text when text is empty

android:textColor It is used to change the color of the text.

android:textColorHint It is used to change the text color of hint text.

android:textSize It is used to specify the size of text.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 39
Mobile Application Development using Android

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for autocomplete


textview control

android:ems It is used to make the textview be exactly this many ems wide.

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.

android:textColorHighlight It is used to change the color of the text selection highlight.

android:fontFamily It is used to specify the fontFamily for the text.

● Example:

activity_main.xml

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 40
Mobile Application Development using Android
MainActivity.java

Image Button

● In android, Image Button is a user interface control that is used to display a button with
an image and to perform an action when a user clicks or taps on it.
● By default, the ImageButton looks the same as a normal button and it performs an
action when a user clicks or touches it, but the only difference is we will add a custom
image to the button instead of text.
● In android, we have different types of buttons available to use based on our
requirements, those are Button, ImageButton, ToggleButton, and RadioButton.
● In android, we can add an image to the button by using <ImageButton> attribute
android:src in the XML layout file or by using the setImageResource() method.
● Attributes:

Attribute Description

android:id It is used to uniquely identify the control

android:src It is used to specify the source file of an image

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 41
Mobile Application Development using Android

android:background It is used to set the background color for an image button


control.

android:padding It is used to set the padding from left, right, top and bottom of
the image button.

● Example:

Activity_main.xml

MainActivity.java

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 42
Mobile Application Development using Android

EditText

● In android, EditText is a user interface control which is used to allow the user to enter or
modify the text. While using EditText control in our android applications, we need to
specify the type of data the text field can accept using the inputType attribute.
● For example, if it accepts plain text, then we need to specify the inputType as “text”. In
case if EditText field is for password, then we need to specify the inputType as
“textPassword”.
● In android, EditText control is an extended version of TextView control with additional
features and it is used to allow users to enter input values.
● Attributes:

Attribute Description

android:id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right, center,
top, etc.

android:text It is used to set the text.

android:hint It is used to display the hint text when text is empty

android:textColor It is used to change the color of the text.

android:textColorHint It is used to change the text color of hint text.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 43
Mobile Application Development using Android

android:textSize It is used to specify the size of the text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for edit text control

android:ems It is used to make the textview be exactly this many ems wide.

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.

android:maxWidth It is used to make the TextView be at most this many pixels


wide.

android:minWidth It is used to make the TextView be at least this many pixels


wide.

android:textAllCaps It is used to present the text in all CAPS

android:typeface It is used to specify the Typeface (normal, sans, serif,


monospace) for the text.

android:textColorHighlight It is used to change the color of text selection highlights.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 44
Mobile Application Development using Android

android:inputType It is used to specify the type of text being placed in text fields.

android:fontFamily It is used to specify the fontFamily for the text.

android:editable If we set false, EditText won't allow us to enter or modify the


text

● Example:

Activity_main.xml

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 45
Mobile Application Development using Android

MainActivity.java

ToggleButton

● In android, Toggle Button is a user interface control that is used to display ON (Checked)
or OFF (Unchecked) states as a button with a light indicator.
● The ToggleButton is useful for the users to change the settings between two states
either ON or OFF. We can add a ToggleButton to our application layout by using the
ToggleButton object.
● By default, the android ToggleButton will be in OFF (Unchecked) state. We can change
the default state of ToggleButton by using android:checked attribute.
● In case, if we want to change the state of ToggleButton to ON (Checked), then we need
to set android:checked = “true” in our XML layout file.
● Attributes:

Attribute Description

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 46
Mobile Application Development using Android

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of toggle button

android:gravity It is used to specify how to align the text like left, right, center,
top, etc.

android:text It is used to set the text.

android:textOn It is used to set the text when the toggle button is in the ON /
Checked state.

android:textOff It is used to set the text when the toggle button is in the OFF /
Unchecked state.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for toggle button control.

android:padding It is used to set the padding from left, right, top and bottom.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 47
Mobile Application Development using Android

● Example:

Activity_main.xml

MainActivity.java

CheckBox

● In android, CheckBox is a two-states button that can be either checked (ON) or


unchecked (OFF) and it will allow users to toggle between the two states (ON / OFF)
based on the requirements.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 48
Mobile Application Development using Android
● Generally, we can use multiple CheckBox controls in an android application to allow
users to select one or more options from the set of values.
● By default, the android CheckBox will be in the OFF (Unchecked) state. We can change
the default state of CheckBox by using android:checked attribute.
● In case, if we want to change the state of CheckBox to ON (Checked), then we need to
set android:checked = “true” in our XML layout file.
● Attributes:

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of checkbox

android:gravity It is used to specify how to align the text like left, right, center,
top, etc.

android:text It is used to set the text for a checkbox.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 49
Mobile Application Development using Android

android:background It is used to set the background color for checkbox control.

android:padding It is used to set the padding from left, right, top and bottom.

android:onClick It’s the name of the method to invoke when the checkbox is
clicked.

android:visibility It is used to control the visibility of control.

● Example:

Activity_main.xml

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 50
Mobile Application Development using Android

MainActivity.java

RadioButton

● In android, Radio Button is a two-states button that can be either checked or unchecked
and it’s the same as CheckBox control, except that it will allow only one option to select
from the group of options.
● The user can press or click on the radio button to make it select. In android, CheckBox
control allows users to change the state of control either Checked or Unchecked but the
radio button cannot be unchecked once it is checked.
● In android, we use radio buttons within a RadioGroup to combine multiple radio
buttons into one group and it will make sure that users can select only one option from
the group of multiple options.
● By default, the android RadioButton will be in OFF (Unchecked) state. We can change
the default state of RadioButton by using the android:checked attribute.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 51
Mobile Application Development using Android
● In case, if we want to change the state of RadioButton to ON (Checked), then we need to
set android:checked = “true” in our XML layout file.
● Attributes:

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of checkbox

android:gravity It is used to specify how to align the text like left, right, center,
top, etc.

android:text It is used to set the text for a checkbox.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for checkbox control.

android:padding It is used to set the padding from left, right, top and bottom.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 52
Mobile Application Development using Android

android:onClick It’s the name of the method to invoke when the checkbox is
clicked.

android:visibility It is used to control the visibility of control.

RadioGroup

● In android, Radio Group is used to group one or more radio buttons into separate
groups based on our requirements.
● If we group Radio Buttons using RadioGroup, at a time only one item can be selected
from the group of radio buttons. In this case, if we select one radio button that belongs
to a radio group it will unselect all other previously selected radio buttons within the
same group.
● Initially, all the radio buttons of the radio group are in the unchecked state, once we
select a radio button then it’s not possible for us to uncheck it like CheckBox control.

● Example:

Activity_main.xml

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 53
Mobile Application Development using Android

MainActivity.java

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 54
Mobile Application Development using Android

ProgressBar

● In android, ProgressBar is a user interface control that is used to indicate the progress of
an operation. For example, downloading a file, uploading a file.
● By default the ProgressBar will be displayed as a spinning wheel, in case if we want to
show it like a horizontal bar then we need to change the style property to horizontal like
style="?android:attr/progressBarStyleHorizontal".
● Attributes:

Attribute Description

android:id It is used to uniquely identify the control

android:minHeight It is used to set the height of the progress bar.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 55
Mobile Application Development using Android

android:minWidth It is used to set the width of the progress bar.

android:max It is used to set the maximum value of the progress bar.

android:progress It is used to set the default progress value between 0 and max.
It must be an integer value.

● Example:

Activity_main.xml

MainActivity.java

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 56
Mobile Application Development using Android

Spinner

● In android, Spinner is a view that allows a user to select one value from the list of
values. The spinner in android will behave the same as a dropdown list in other
programming languages.
● Generally, the android spinners will provide a quick way to select one item from the list
of values and it will show a dropdown menu with a list of all values when we click or tap
on it.
● We can populate our Spinner control with a list of choices by defining an ArrayAdapter
in our Activity file.

Android Adapter
● In android, Adapter will act as an intermediate between the data sources and adapter
views such as ListView, Gridview to fill the data into adapter views. The adapter will hold
the data and iterate through items in the data set and generate the views for each item
in the list.
● Generally, in android we have a different types of adapters available to fetch the data
from different data sources to fill the data into adapter views, those are

Attribute Description

ArrayAdapter It will expect an Array or List as input.

CursorAdapter It will accept an instance of a cursor as an input.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 57
Mobile Application Development using Android

SimpleAdapter It will accept static data defined in the resources.

BaseAdapter It is a generic implementation for all three adapter types and it


can be used for ListView, Gridview or Spinners based on our
requirements

● Example:

Activity_main.xml

MainActivity.java

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 58
Mobile Application Development using Android

Layouts(ViewGroup) in Android

Android Layout Attributes

Attribute Description

android:id It is used to uniquely identify the view and ViewGroups

android:layout_width It is used to define the width for View and ViewGroup


elements in a layout

android:layout_height It is used to define the height for View and ViewGroup


elements in a layout

android:layout_marginLeft It is used to define the extra space in the left side for View
and ViewGroup elements in a layout

android:layout_marginRight It is used to define the extra space in right side for View and
ViewGroup elements in layout

android:layout_marginTop It is used to define the extra space on top for View and
ViewGroup elements in layout

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 59
Mobile Application Development using Android

android:layout_marginBott It is used to define the extra space in the bottom side for
om View and ViewGroup elements in a layout

android:paddingLeft It is used to define the left side padding for View and
ViewGroup elements in layout files

android:paddingRight It is used to define the right side padding for View and
ViewGroup elements in layout files

android:paddingTop It is used to define padding for View and ViewGroup elements


in layout files on top side

android:paddingBottom It is used to define the bottom side padding for View and
ViewGroup elements in layout files

android:layout_gravity It is used to define how child Views are positioned

Linear Layout

● In android, LinearLayout is a ViewGroup subclass which is used to render all child View
instances one by one either in Horizontal direction or Vertical direction based on the
orientation property.
● In android, we can specify the linear layout orientation using android:orientation
attribute.
● In LinearLayout, the child View instances are arranged one by one, so the horizontal list

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 60
Mobile Application Development using Android
will have only one row of multiple columns and the vertical list will have one column of
multiple rows.
● Example:

Relative Layout

● In android, RelativeLayout is a ViewGroup which is used to specify the position of child

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 61
Mobile Application Development using Android
View instances relative to each other (Child A to the left of Child B) or relative to the
parent (Aligned to the top of parent).
● In android, RelativeLayout is very useful to design the user interface because by using
relative layout we can eliminate the nested view groups and keep our layout hierarchy
flat, which improves the performance of the application.
● In RelativeLayout we need to specify the position of child views relative to each other or
relative to the parent. In case if we didn’t specify the position of child views, by default
all child views are positioned to top-left of the layout.
● Attributes:

Attribute Description

ayout_alignParentTop If it specified “true”, the top edge of view will match the top
edge of the parent.

layout_alignParentBottom If it specified “true”, the bottom edge of view will match the
bottom edge of parent.

layout_alignParentLeft If it specified “true”, the left edge of view will match the left
edge of parent.

layout_alignParentRight If it specified “true”, the right edge of view will match the right
edge of the parent.

layout_centerInParent If it specified “true”, the view will be aligned to the centre of


parent.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 62
Mobile Application Development using Android

layout_centerHorizontal If it specified “true”, the view will be horizontally centre aligned


within its parent.

layout_centerVertical If it specified “true”, the view will be vertically centre aligned


within its parent.

layout_above It accepts another sibling view id and places the view above the
specified view id.

layout_below It accepts another sibling view id and places the view below the
specified view id.

layout_toLeftOf It accepts another sibling view id and places the view left of the
specified view id.

layout_toRightOf It accepts another sibling view id and places the view right of
the specified view id.

layout_toStartOf It accepts another sibling view id and places the view to start
off the specified view id.

layout_toEndOf It accepts another sibling view id and places the view to the
end of the specified view id.

● Example:

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 63
Mobile Application Development using Android

<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:orientation="vertical"
tools:context=".MainActivity">

<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Button" />
<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/b1"
android:layout_centerInParent="true"
android:text="Button" />
<Button
android:id="@+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/b1"

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 64
Mobile Application Development using Android

android:layout_centerInParent="true"
android:text="Button" />
<Button
android:id="@+id/b4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/b1"
android:layout_centerInParent="true"
android:text="Button" />
<Button
android:id="@+id/b5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/b1"
android:layout_centerInParent="true"
android:text="Button" />
</RelativeLayout>

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 65
Mobile Application Development using Android

Frame Layout

● In android, Framelayout is a ViewGroup subclass that is used to specify the position of


View instances it contains on the top of each other to display only a single View inside
the FrameLayout.
● In simple manner, we can say FrameLayout is designed to block out an area on the
screen to display a single item.
● In FrameLayout, the child views are added in a stack and the most recently added child
will show on the top. We can add multiple children views to FrameLayout and control
their position by using gravity attributes in FrameLayout.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imgvw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/flimg" />
<TextView
android:id="@+id/txtvw1"
android:layout_width="match_parent"
android:layout_height="wrap_content"

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 66
Mobile Application Development using Android

android:layout_marginTop="40dp"
android:background="#4C374A"
android:padding="10dp"
android:text="Grand Palace, Bangkok"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TextView
android:id="@+id/txtvw2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:background="#AA000000"
android:padding="10dp"
android:text="21/Aug/2017"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</FrameLayout>

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 67
Mobile Application Development using Android

Table Layout

● In android, TableLayout is a ViewGroup subclass that is used to display the child View
elements in rows and columns.
● In android, TableLayout will position its children elements into rows and columns and it
won’t display any border lines for rows, columns or cells.
● The TableLayout in android will work the same as the HTML table and the table will have
as many columns as the row with the most cells. The TableLayout can be explained as
<table> and TableRow is like <tr> element.
● Create a new android application using android studio and give names as TableLayout. In
case you are not aware of creating an app in android studio check this article Android
Hello World App.
● Example:

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 68
Mobile Application Development using Android

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


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="UserId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="User Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Location" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 69
Mobile Application Development using Android

android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Suresh Dasari" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Hyderabad" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Rohini Alavala" />
<TextView
android:layout_width="wrap_content"

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 70
Mobile Application Development using Android

android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Guntur" />
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Trishika Dasari" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Guntur" />
</TableRow>
</TableLayout>

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 71
Mobile Application Development using Android

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 72
Mobile Application Development using Android

Unit -3 Data Storage & SQLite Connectivity

Database Connectivity

● In android, we have different storage options such as shared preferences, internal


storage, external storage, SQLite storage, etc. to store and retrieve the application data
based on our requirements.
● In the previous topic, we learned how to use shared preferences, internal storage,
external storage and now we will see how to use SQLite Database option to store
structured data in a private database.
● SQLite is an open source lightweight relational database management system (RDBMS)
to perform database operations, such as storing, updating, retrieving data from a
database.
● Generally, in our android applications Shared Preferences, Internal Storage and External
Storage options are useful to store and maintain a small amount of data. In case, if we
want to deal with large amounts of data, then SQLite database is the preferable option
to store and maintain the data in structured format.
● By default, Android comes with built-in SQLite Database support so we don’t need to do
any configurations.
● Just like we save the files on device’s internal storage, Android stores our database in a
private disk space that’s associated with our application and the data is secure, because
by default this area is not accessible to other applications.
● The package android.database.sqlite contains all the required API’s to use SQLite
database in our android applications.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 73
Mobile Application Development using Android

Create Database and Tables using SQLiteOpenHelper

● In android, by using SQLiteOpenHelper class we can easily create required databases and
tables for our application. To use SQLiteOpenHelper, we need to create a subclass that
overrides the onCreate() and onUpgrade() call-back methods.

Method Description

onCreate() This method is called only once throughout the application after the
database is created and the table creation statements can be written in
this method.

onUpgrade() This method is called whenever there is an update in the database like
modifying the table structure, adding constraints to the database, etc.

execSQL( )

● To execute SQL statements in Android SQLite databases, you typically use methods
provided by the SQLiteDatabase class. One of these methods is execSQL, which is used
to execute a single SQL statement that is NOT a SELECT or any other SQL statement that
returns data.
● execSQL is used to execute the SQL statements for creating a table (CREATE TABLE) and
inserting data into that table (INSERT INTO). It's important to handle database
operations like opening, executing SQL, and closing the database properly to prevent
resource leaks and ensure data integrity.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 74
Mobile Application Development using Android

Database Helper File

● 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,student_DB,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}

Table Creation

public void onCreate(SQLiteDatabase db) {


db.execSQL("CREATE TABLE STUDENT(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME
TEXT)");
}

Data 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

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 75
Mobile Application Development using Android
pointing to the table. We can move the cursor forward and retrieve the data.

● rawQuery(query, selectionArgs)
○ In Android development, the rawQuery() method is used to execute a raw SQL
query on an SQLite database. This method allows you to run any SQL query
directly and retrieve the result set.
○ The rawQuery() method returns a Cursor object, which allows you to iterate over
the result set and access the retrieved data.
○ Here's a breakdown of the parameters used in the rawQuery() method:
■ query: The raw SQL query to execute.
■ selectionArgs: An optional array of strings that represent the values to
replace the placeholders (?) in the SQL query. This parameter is useful for
avoiding SQL injection vulnerabilities.
○ Using the rawQuery() method gives you flexibility in executing complex SQL
queries directly on an SQLite database in Android applications.

SQLiteDatabase db=this.getWritableDatabase();
Cursor resultSet = db.rawQuery("Select * from Student",null);
resultSet.moveToFirst();
String enrollmentNo= resultSet.getString(0);
String name= resultSet.getString(1);

Data Insertion

● We can insert anything into the database using an object of the Cursor class. We will call
a method of this class called insert and it will insert the data into a given table of the
database.we can create table or insert data into table using execSQL method defined in

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 76
Mobile Application Development using Android
SQLiteDatabase class.
● insert(table_name, nullcolumnHack, contentValues )
○ In Android development, the insert() method is commonly used to insert a new
row of data into an SQLite database table. Unlike the execSQL() method, which
executes raw SQL queries directly, insert() is a higher-level method that provides
a more structured way to insert data.
○ Instead of constructing an SQL query manually, you create a ContentValues
object and use the put() method to specify the column name and value pairs.
Then, you call the insert() method on the SQLiteDatabase object, passing the
table name, null for the second parameter (which is used for specifying the
column names to insert null values into, if any), and the ContentValues object
containing the data to insert.
○ Using insert() with ContentValues provides several advantages, including
automatic handling of data type conversion and prevention of SQL injection
vulnerabilities. It's a safer and more convenient approach compared to
constructing SQL queries manually with execSQL().

SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("ID",101);
values.put("NAME",”Meera”);
db.insert("STUDENT",null,values);

Data Updation

● update(table_name,content_values,selection,selectionArgs)
● In Android development, the update() method is used to modify existing rows of

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 77
Mobile Application Development using Android
data in an SQLite database table. It allows you to update one or more rows
based on a specified condition.
● Here's a breakdown of the parameters used in the update() method:
■ TABLE_NAME: The name of the table to update.
■ values: A ContentValues object containing the column name and value
pairs to update.
■ selection: The selection criteria for the rows to update. It specifies which
rows to modify based on a WHERE clause.
■ selectionArgs: An array of strings that represent the values to replace the
placeholders (?) in the selection parameter.
● Using the update() method with ContentValues provides a safe and efficient way
to update data in an SQLite database table in Android applications.

SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("ID",101);
values.put("NAME",”Meera”);
db.update("STUDENT",values,"ID=?",new String[]{Id});

Data Deletion
● delete(table_name,selection,selectionArgs)
● In Android development, the delete() method is used to remove rows from an
SQLite database table based on a specified condition. It allows you to delete one
or more rows that match the given criteria.
● Here's a breakdown of the parameters used in the delete() method:
■ TABLE_NAME: The name of the table from which to delete rows.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 78
Mobile Application Development using Android
■ selection: The selection criteria for the rows to delete. It specifies which
rows to delete based on a WHERE clause.
■ selectionArgs: An array of strings that represent the values to replace the
placeholders (?) in the selection parameter.
● Using the delete() method allows you to efficiently remove data from an SQLite
database table in Android applications.

SQLiteDatabase db=this.getWritableDatabase();
db.delete("STUDENT","ID=?",new String[]{Id});

Shared Preferences
● In android, Shared Preferences are used to save and retrieve the primitive data types
(integer, float,Boolean, string, long) data in the form of key-value pairs from a file within
an app's file structure.
● Generally, the Shared Preferences object will point to a file that contains a key-value
pair and provides a simple read and write method to save and retrieve the key-value
pairs from a file.
● The Shared Preferences file is managed by an android framework and it can be
accessed anywhere within the app to read or write data into the file, but it’s not
possible to access the file from any other app so it’s secured.
● The Shared Preferences are useful to store the small collection of key-values such as
user’s login information, app preferences related to users, etc. to maintain the state of
the app, next time when they login again to the app.

Handle a Shared Preferences

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 79
Mobile Application Development using Android
● In android, we can save the preferences data either in single or multiple files based on
our requirements.
● In case if we use single file to save the preferences, then we need to use
getPreferences() method to get the values from Shared Preferences file and for multiple
files we need to call a getSharedPreferences() method and pass a filename as a
parameter.

Method Description

getPreferences() This method is for activity level preferences and each


activity will have its own preference file and by default this
method retrieves a default shared preference file that
belongs to the activity.

getSharedPreferences() This method is useful to get the values from multiple shared
preference files by passing the name as parameter to
identify the file. We can call this from any Context in our
app.

● Following are the different ways to initialize the Shared Preferences in our application.
● If we are using a single shared preference file for our activity, then we need to initialize
the SharedPreferences object by using getPreferences() method as shown below.

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);

● In case, if we are using multiple shared preference files, then we need to initialize the
SharedPreferences object by using getSharedPreferences() method like shown below.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 80
Mobile Application Development using Android

SharedPreferences sharedPref = getSharedPreferences("filename1",Context.MODE_PRIVATE);

● Here, the name “filename1” is the preference file, which wants to read the values based
on our requirements and the context mode MODE_PRIVATE, will make sure that the file
can be accessed only within our application.

Write to Shared Preferences

● To store data in a shared preference file, we need an editor to edit and save the changes
in the SharedPreferences object. Following is the code snippet to store the data in a
shared preference file using editor.

SharedPreferences shared_pref= getPreferences(Context.MODE_PRIVATE);


SharedPreferences.Editor editor = shared_pref.edit();
editor.putBoolean("keyname",true);
editor.putString("keyname","string value");
editor.putInt("keyname","int value");
editor.putFloat("keyname","float value");
editor.putLong("keyname","long value");
editor.commit();

Read from Shared Preferences

● To read or retrieve a value from a Shared Preferences file, we need to call methods such
as getInt(), getString(), etc. by providing the key for the value which we want to get as
shown below.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 81
Mobile Application Development using Android

SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);


pref.getString("keyname",null);
pref.getInt("keyname",0);
pref.getFloat("keyname",0);
pref.getBoolean("keyname",true);
pref.getLong("keyname",0);

Deleting from Shared Preferences

● To delete a value from a Shared Preferences file, we need to call a remove() method by
providing the key for the value which we want to delete as shown below.

SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);


SharedPreferences.Editor editor = pref.edit();
editor.remove("keyname");
editor.commit();

● If you observe the above code snippet, we are deleting the values from shared
preferences using a method called remove() by providing the key for the value which we
want to delete and committing the changes to the shared preferences file using
commit() method.

Clearing from Shared Preferences :

● We can clear all the data from the Shared Preferences file using the clear() method like
shown below.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 82
Mobile Application Development using Android

SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);


SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();

● If you observe the above code snippet, we are clearing all the values from shared
preferences using a method called clear() and committing the changes to the shared
preferences file using commit() method.
● Now we will see how to store and retrieve primitive data type key-value pairs in a shared
preferences file using the SharedPreferences object in an android application with
examples.

File Storage
● Android provides many kinds of storage for applications to store their data. These
storage places are shared preferences, internal and external storage, SQLite storage, and
storage via network connection.
● In this topic we are going to look at the internal storage. Internal storage is the storage
of the private data on the device memory.
● By default these files are private and are accessed by only your application and get
deleted , when the user deletes your application.

Writing file

● In order to use internal storage to write some data in the file, call the openFileOutput()
method with the name of the file and the mode. The mode could be private , public

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 83
Mobile Application Development using Android
e.t.c.
● The method openFileOutput() returns an instance of FileOutputStream. So you receive
it in the object of FileInputStream. After that you can call the write method to write data
on the file.

FileOutputStream fos= openFileOutput("file_name",MODE_APPEND);


String str = "data";
fos.write(str.getBytes());
fos.close();

Reading file

● In order to read from the file you just created , call the openFileInput() method with the
name of the file. It returns an instance of FileInputStream.
● After that, you can call the read method to read one character at a time from the file
and then you can print it.

FileInputStream fin = openFileInput(file);


int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
fin.close();

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 84
Mobile Application Development using Android

Content Provider
● A content provider manages access to a central repository of data. A provider is part of
an Android application, which often provides its own UI for working with the data.
However, content providers are primarily used by other applications, which access the
provider using a provider client object.
● What is Content URI(Universal Resource Identifier)?
○ Content URI is the key concept of a content provider. To query a content provider,
you can specify the query string in the form of URI.
○ URI: content://authority/data_type/id
○ content:// →This is a prefix of all the URI and it is a mandatory part of URI.
○ authority →This part should be always unique for every content provider, it
specifies the name of the content provider. for example contacts, browsers etc.
○ data_type → This indicates the type of data provider by content provider.
● ContextCompat is a useful utility class in Android that allows you to work with the
Context object in a backward-compatible way. It provides methods for accessing
resources, performing permission checks, working with drawables, and more.
● A contract class is a public final class that contains constant definitions for the URIs,
column names, MIME types, and other meta-data about the ContentProvider. It can also
contain static helper methods to manipulate the URIs.
● ContentResolver is a “class that provides applications access to the content model”.
ContentResolvers expose methods to interact, fetch, or modify content provided from
the following: Installed apps ( content:// URI scheme) File systems ( file:// URI scheme).

if(ContextCompat.checkSelfPermission(getApplicationContext(), permission.READ_CONTACTS)!=
PackageManager.PERMISSION_GRANTED) {

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 85
Mobile Application Development using Android

ActivityCompat.requestPermissions (MainActivity.this,new String[]{permission.READ_CONTACTS},0 );


}else{
ArrayList<String> contacts=new ArrayList<>();
Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr=getContentResolver();
Cursor c=cr.query(uri,null,null,null,null);
if(c.getCount()>0){
while(c.moveToNext()){
@SuppressLint("Range")
String contact_name=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
@SuppressLint("Range")
String contact_number=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(contact_name+"\n"+contact_number);
lv.setAdapter(new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_expandable_list_item_1,contacts));

}
}

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 86
Mobile Application Development using Android

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 87
Mobile Application Development using Android

Unit - 4 API, Location Based Services(LBS) &


Notifications

Telephony Services(API)

● 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.
● Telephony Applications:
○ Dialer
○ Contacts
○ Messaging — SMS/MMS(BasicSmsReceiver)
○ Settings app — a) Airplane mode b) APN settings C)Network selection
(auto/manual) d) Call settings, such as, call waiting, call forwarding/diverting
○ SIM Application Toolkit (SAT)

Requesting Call State

● Gaining Permission to Access Phone State Information READ_PHONE_STATE


permission is required to retrieve information such as the call state, handset phone
number, and device identifiers or serial numbers.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 88
Mobile Application Development using Android

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

● Use the TelephonyManager object to retrieve the state of the phone and some
information about the phone service itself, such as the phone number of the handset.

TelephonyManager telManager= (TelephonyManager)


getSystemService(Context.TELEPHONY_SERVICE);

● One important method is getCallState().This method can determine the voice call status
of the handset.
● Various states are :
○ CALL_STATE_IDLE – when there is no incoming call
○ CALL_STATE_OFFHOOK – when the line is busy
○ CALL_STATE_RINGING – when call is incoming
● In addition to call and service state information, your application can retrieve other
information about the device like :

String phoneNumber = telManager.getLine1Number();


String providerName = telManager.getSimOperatorName();
String opName = telManager.getNetworkOperatorName();

● The network operator name is the descriptive name of the current provider that the
handset connects to.This is typically the current tower operator.
● The SIM operator name is typically the name of the provider that the user is subscribed
to for service.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 89
Mobile Application Development using Android
● The phone number for this application programming interface (API) is defined as the
MSISDN,typically the directory number of a GSM handset (that is, the number someone
would dial to reach that particular phone).

Working with phone number

● We can make a call on a particular phone number by using an intent.

Intent callIntent=new Intent(Intent.ACTION_CALL);


callIntent.setData(Uri.parse("tel:7896541236"));
startActivity(callIntent);

Using SMS

● SMS functionality is provided to applications through the android.telephony package.


Gaining Permission to Send and Receive SMS Messages:

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

● To send an SMS, an application first needs to get an instance of the SmsManager.


● The SmsManager has a method to send text messages.:
sendTextMessage(destinationAddress,scAddress,Message,sentIntent, deliveryIntent);

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 90
Mobile Application Development using Android

SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage("789654123",null,"Hello, This is Test Message",null,null);

● Applications can also receive SMS messages.


● To do so, your application must register a BroadcastReceiver to listen for the Intent
action associated with receiving an SMS.

public void onReceive(Context context, Intent intent)


{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) intent.getExtras().get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
//---display the new SMS message---

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 91
Mobile Application Development using Android

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


}
}

Web API
● Android applications can simply use the WebView control to display web content to the
screen, which can think of WebView control as a browser-like view.
● The WebView control uses the WebKit rendering engine to draw HTML content on the
screen.
● This content could be HTML pages on the Web or it can be locally sourced.
● It does not have all the features of a full browser.It does not display the title of a
webpage or provide buttons for reloading pages.
● If the user clicks on a link within the WebView control, that action does not load the new
page within the view. Instead, it fires up the Browser application.
● By default, all the WebView control does is display the web content provided by the
developer using its internal rendering engine,WebKit.
● Use three classes, in particular, to help modify the behavior of the control:
○ WebSettings class
○ WebViewClient class, and
○ WebChromeClient class.
● WebKit is an open source browser engine.Using the WebView control requires the
android.permission.INTERNET permission.
● You can add this permission to your application’s Android manifest file as follows:

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

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 92
Mobile Application Development using Android

WebView
● The WebView control can be added to a layout resource file like any other view.
● It can take up the entire screen or just a portion of it. A typical WebView definition in a
layout resource might look like this:

<WebView
android:id=”@+id/web_holder”
android:layout_height=”wrap_content”
android:layout_width=”fill_parent”
/>

● You can load content into a WebView control in a variety of ways.For example, WebView
control can load a specific website or render raw HTML content.
● Web pages can be stored on a remote web server or stored of the device.how to use a
WebView control to load content from a specific website:

WebView webview=findViewById(R.id.w1);
webview.setWebViewClient(new WebViewClient());
webview.loadUrl("https://www.w3schools.com");

● If, instead, you want to render raw HTML, you can use the loadData() method:

String data = "<html><body><h1>Hello, Javatpoint!</h1></body></html>";


webview.loadData(data, "text/html", "utf-8");

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 93
Mobile Application Development using Android

● Load an HTML file called demo.html stored in the application’s assets directory like this:

w1.loadUrl("file:///android_asset/demo.html");

URL Parsing
● When you want the user to have full access to all Browser features, such as bookmarking
and browsing, you’re better off launching the Browser application to a specific
website,letting users do their browsing, and having them return to your application
when they’re done.
● You can do this as follows:

Intent i=new Intent(Intent.ACTION_VIEW);


i.setData( Uri.parse(“http://www.w3school.com/”));
startActivity(i);

Network API
● Android network connectivity services allow us to check the network connectivity
information of the device. It is very important to check the internet connection of the
device while performing the task which is based on internet service such as fetching data
from the server (internet) or writing data to the server.
● Using Android Network Connectivity Services we can also determine the types of a
network of android devices. It may be of types TYPE_WIFI (wifi), TYPE_MOBILE
(mobile), TYPE_BLUETOOTH (Bluetooth), etc.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 94
Mobile Application Development using Android
● To access the network connectivity of a device, we need to provide the network access
permission in the AndroidMenifest.xml file.

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

● The code context.getSystemService(Context.CONNECTIVITY_SERVICE) is used to return


the instance of the ConnectivityManager class which accesses the network properties.

ConnectivityManager connectivityManager=
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

if (connectivityManager != null) {

NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();


if (networkInfo != null) {
Log.d("TYPE", "Type of network: " + networkInfo.getTypeName());
Log.d("STATE", "State of connection: " + networkInfo.getState());
Log.d("IS_CONNECTED", "Is connecting or connected: "
+networkInfo.isConnectedOrConnecting());
}
}

Sending Notifications

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 95
Mobile Application Development using Android
● 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.
● Android Notification provides short, timely information about the action happening in
the application, even if it is not running. The notification displays the icon, title and
some amount of the content text.
● The properties of Android notification are set using NotificationCompat.Builder objects.
Some of the notification properties are mentioned below:
○ setSmallIcon(): It sets the icon of notification.
○ setContentTitle(): It is used to set the title of notification.
○ setContentText(): It is used to set the text message.
○ setAutoCancel(): It sets the cancelable property of notification.
○ setPriority(): It sets the priority of notification.
● Once you have a Builder object, you can set its Notification properties using the Builder
object as per your requirement. But this is mandatory to set at least following −

NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(MainActivity.this);//4

Intent i = new Intent(getApplicationContext(),MainActivity.class);


PendingIntent pi = PendingIntent.getActivity(MainActivity.this,001,i,PendingIntent.FLAG_IMMUTABLE);

nBuilder.setSmallIcon(R.drawable.ic_launcher_background);
nBuilder.setContentTitle("TITLE");
nBuilder.setContentText("TEXT");

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 96
Mobile Application Development using Android

nBuilder.setChannelId("atmiya");
nBuilder.setContentIntent(pi);

// Create an explicit intent for an activity in your app


NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);//1
NotificationChannel nc = new
NotificationChannel("atmiya","AppName",NotificationManager.IMPORTANCE_DEFAULT);//3
nm.createNotificationChannel(nc);//2
nm.notify(001,nBuilder.build());//3

Vibrating Phone
● In android, using vibrate service, we can vibrate android mobile.
● To use the vibrator services , we have to add permission in android manifest file:

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

● In the code below, we have taken vibrate service, it is a system service as shown
below.we have given 500ms so it is going to vibrate 500ms continuously.

Vibrator vibrator = (Vibrator)


getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null) {
// Vibrate for the specified duration in milliseconds
vibrator.vibrate(500);

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 97
Mobile Application Development using Android

Blinking the Lights

Location Based Services


● Android provides the developers with its location API. This makes it easy for us to make
applications that support location. Location-based services in android are those services
that deal with the device’s geographical location.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 98
Mobile Application Development using Android
● Location-Based Services in Android provides us with this feature to help us in various
ways. It enables us to create an application that is capable of detecting the current
location of our devices. Android makes use of information from GPS and WiFi networks
to get the location of the device on this Earth.
● So LBS is the feature that Android provides us using the Location Framework. This
framework provides us basically with certain classes and interfaces, which are key
components. These components make it easier for us to implement the location feature
in our application.
Components of Location-Based Services in Android
● LocationManager Class – It helps to get the location service of the System.
● LocationListener Interface – It receives notification from the Manager.
● LocationProvider – Devices provide a location from a set of providers.
● Location Class – It represents the geographic location at a particular time.

● An instance of the LocationManager needs to be created as the first step in this


process.This is the main class through which the application gets access to the location
services in Android. A reference to this system service can be obtained by calling
getSystemService()method.

LocationManagerlocationManager=(LocationManager)getSystemService(Context.LOC
ATION_SERVICE);

● Next step is to identify the location provider you would like to use for retrieving location
details.The location providers actually provide the location data in Android. Android
exposes two main locations.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 99
Mobile Application Development using Android
● GPS Location Provider:This location provider provides location data with the highest
accuracy (~2 m – 20m). Location updates are provided through satellites.

● Drawbacks of using GPS


○ It is significantly slower than the network provider to get the initial connection
setup with the satellites.
○ This initial connection, also called Time to First Fix (TTFF) can be extremely slow
but once the connection is established, location updates are quite fast
○ The GPS provider also drains the battery very first. So, it is very important to
judiciously use this provider. Special care should be taken to ensure that this is
turned off when you are not using it.
○ The third drawback comes from the fact that GPS uses radio signals which are
obstructed by solid objects.
○ So, a GPS provider will not work if you are inside a building or in a basement.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 100
Mobile Application Development using Android

Unit - 5 Web Service and Development of


Application

Overview of Web Services


● Web services in Android enable applications to communicate with web servers over the
internet. They allow fetching data, sending data, and performing various operations over
HTTP or other network protocols. Here's an overview of web services in Android:
● RESTful Web Services: Representational State Transfer (REST) is an architectural style for
distributed hypermedia systems. In Android, you can consume RESTful APIs using HTTP
methods like GET, POST, PUT, DELETE. JSON (JavaScript Object Notation) is a commonly
used format for data exchange in RESTful web services due to its simplicity and
lightweight nature.
● SOAP Web Services: Simple Object Access Protocol (SOAP) is a protocol for exchanging
structured information in the implementation of web services. Android supports SOAP
web services, although it's less common compared to REST due to its complexity and
verbosity. SOAP typically uses XML for data exchange.
● HTTP Client Libraries: Android provides built-in support for making HTTP requests using
classes like HttpURLConnection and HttpClient. However, many developers prefer using
third-party libraries like OkHttp, Retrofit, or Volley for handling HTTP requests more
efficiently and with less boilerplate code.
● Authentication: Web services often require authentication to access protected
resources. Android supports various authentication mechanisms such as Basic
Authentication, OAuth, API keys, JWT (JSON Web Tokens), etc. Implementing

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 101
Mobile Application Development using Android
authentication in your Android app involves sending credentials securely to the server
and handling the authentication tokens or cookies returned by the server.
● Error Handling: Proper error handling is crucial when working with web services.
Android apps should gracefully handle network errors, server errors, timeouts, and
other exceptions that may occur during communication with the server. This involves
displaying meaningful error messages to users and implementing retry mechanisms
when appropriate.
● Security: Security considerations, such as SSL/TLS encryption, data encryption, and
secure storage of sensitive information, are essential when dealing with web services in
Android. Ensuring the confidentiality, integrity, and authenticity of data transmitted
between the app and the server is paramount to protect user privacy and prevent data
breaches.

JSON Data Parsing


What is JSON?
● JSON stands for JavaScript Object Notation. It is structured, light weight, human
readable and easy to parse.
● It’s a best alternative to XML when our android app needs to interchange data from the
server. XML parsing is very complex as compared to JSON parsing.
● JSON is a shorter, quicker and easier way to interchange data from the server. JSON is a
great success and most of the API available support JSON format.
● Android Provide us four different classes to manipulate JSON data. These classes are
JSONObject, JSONArray, JSONStringer and JSONTokenizer.
● Usually, JSON contains two types of nodes JSONArray and JSONObject so while parsing
we have to use the appropriate method.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 102
Mobile Application Development using Android
● If JSON starts from square bracket ([) we use getJSONArray() method and if it starts from
curly bracket ({) then we should use the getJSONObject() method. Apart from these
there are some other methods for better parsing JSON data.
● Sample JSON data:

{
employee: {
name: meera shah ,
salary:5000
}
}

How to parse JSON data in android?

String JSON_STRING = "{\"employee\":{\"name\":\"MeeraShah\",\"salary\":65000}}";


try {
// get JSONObject from JSON file
JSONObject obj = new JSONObject(JSON_STRING);
// fetch JSONObject named employee
JSONObject employee = obj.getJSONObject("employee");
// get employee name and salary
String name = employee.getString("name");
String salary = employee.getString("salary");
// set employee name and salary in TextView's
employeeName.setText("Name: "+name);
employeeSalary.setText("Salary: "+salary);
} catch (JSONException e) {

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 103
Mobile Application Development using Android

e.printStackTrace();
}

Create Restful web API using PHP, MySQL, JSON


● Creating a RESTful web service using MySQL, PHP, and JSON involves setting up a
server-side script in PHP to interact with the MySQL database and expose endpoints to
perform CRUD (Create, Read, Update, Delete) operations. Here's a basic example of how
you can achieve this:
● Database Setup: First, create a MySQL database and a table to work with. Let's say we
have a table called users with columns: id, name, and email.
● Create a PHP script to handle HTTP requests and interact with the database. Save this
script as data.php

<?php
header("Content-Type: application/json; charset=UTF-8");

// MySQL database credentials


$servername = "localhost";
$username = "root";
$password = "";
$database = "mydb";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 104
Mobile Application Development using Android

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Set up RESTful API endpoints


//$request_method = $_SERVER["REQUEST_METHOD"];
$request_method = 'GET';

switch ($request_method) {
case 'GET':
// Retrieve users
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);

$users = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$users[] = $row;
}
}
echo json_encode($users);
break;
case 'POST':
// Add a new user
$data = json_decode(file_get_contents("php://input"), true);
// $name = $data['name'];

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 105
Mobile Application Development using Android

// $email = $data['email'];
$name ="111";
$email = "[email protected]";

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";


if ($conn->query($sql) === TRUE) {
echo json_encode(array("message" => "User added successfully"));
} else {
echo json_encode(array("error" => $conn->error));
}
break;
// Handle other HTTP methods like PUT and DELETE as needed
default:
// Method not allowed
http_response_code(405);
echo json_encode(array("error" => "Method not allowed"));
break;
}

$conn->close();
?>

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 106
Mobile Application Development using Android

JSON Data Parsing using Restful API(Async Task)


● create an AsyncTask class in Android to interact with the RESTful API created using PHP.
Below is an example implementation:

public class MainActivity extends AppCompatActivity {


String url_API="http://10.0.2.2:80/data.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new syncData().execute();
}
public class syncData extends AsyncTask<String,String,String>
{
@Override
protected String doInBackground(String... strings) {
try {
URL url=new URL(url_API);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
BufferedReader r=new BufferedReader(new
InputStreamReader(con.getInputStream()));
while(true){
String readlines=r.readLine();
String data=readlines;

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 107
Mobile Application Development using Android

if(data==null){
break;
}

Log.d("data",data);
}

} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
}

Steps to Publish Android App on Play Store


● Publishing an Android application on the Google Play Store involves several steps. Below
are the general steps to publish an Android application on the Play Store, tailored for
students:
● Prepare Your App:
○ Ensure your Android application is fully developed and tested thoroughly on
different devices and screen sizes.
○ Optimize your app for performance, user experience, and compatibility with
various Android versions.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 108
Mobile Application Development using Android
○ Create engaging app screenshots, graphics, and promotional materials to attract
users.
● Create a Google Play Developer Account:
○ Go to the Google Play Console website (https://play.google.com/console) and
sign in with your Google account.
○ Follow the prompts to create a developer account. Note that there is a one-time
registration fee, but Google sometimes offers discounts for students.
● Set Up Your App Listing:
○ In the Google Play Console, click on "Create Application" and enter the details of
your app, such as title, description, category, and contact details.
● Upload your app's APK file:
○ Add high-quality app icons, feature graphics, and screenshots that accurately
represent your app.
○ Provide detailed information about your app's features, functionality, and any
permissions required.
● Set Pricing and Distribution:
○ Choose whether you want to distribute your app for free or set a price.
○ Select the countries where you want your app to be available.
○ Decide whether you want to target specific devices or restrict distribution based
on other criteria.
● Prepare Store Listing Content:
○ Write a compelling app description that highlights the key features and benefits
of your app.
○ Optimize your app's title, description, and keywords for better visibility in the
Play Store search results.
○ Provide accurate contact information and a privacy policy link.
● Test Your App:

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 109
Mobile Application Development using Android
○ Use the internal testing track in the Google Play Console to distribute your app to
a limited group of testers for feedback and testing.
○ Fix any bugs or issues identified during testing before proceeding to the next
step.
● Submit Your App for Review:
○ Once you're satisfied with your app and store listing, submit it for review by
clicking the "Submit to Review" button in the Google Play Console.
○ Google will review your app to ensure it complies with their policies and
guidelines.
● Launch Your App:
○ Once your app passes review, you can choose to publish it immediately or
schedule a release date.
Once published, your app will be available for download on the Google Play
Store.
● Promote Your App:
○ Share your app's link on social media, forums, and other platforms to increase
visibility and attract users.
○ Consider running ads or promotions to reach a larger audience.
● Monitor Performance and Feedback:
○ Use the Google Play Console to monitor your app's performance, including
downloads, ratings, and reviews.
○ Respond to user feedback and reviews promptly to address any issues and
improve your app's rating and user satisfaction.

Department of Computer Science, Faculty of Science, Atmiya University, Rajkot


Prepared By : (Dr.) Meera M. Shah 110

You might also like