0% found this document useful (0 votes)
25 views85 pages

Android Ebook

The document provides an overview of the subject 'Current Trends in IT' focusing on Mobile Computing, specifically covering HTML5, CSS, and Android programming. It details the use of various technologies and tools for developing Android applications, including Java and XML, while also introducing key features of HTML5 and CSS. Additionally, it discusses the latest trends in web development and offers practical examples to enhance learning and application development skills.

Uploaded by

Manish Parab
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)
25 views85 pages

Android Ebook

The document provides an overview of the subject 'Current Trends in IT' focusing on Mobile Computing, specifically covering HTML5, CSS, and Android programming. It details the use of various technologies and tools for developing Android applications, including Java and XML, while also introducing key features of HTML5 and CSS. Additionally, it discusses the latest trends in web development and offers practical examples to enhance learning and application development skills.

Uploaded by

Manish Parab
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/ 85

BCA-642 CTIT (Current Trends in IT) (Mobile Computing)

About The Subject


This study material titled Current Trends in IT will introduce you to the exciting world of the
Mobile Computing. The internet has become a very important communication medium
today and the technology is changing day by day.
The focus of the study material is on learning HTML5, CSS & Android programming. Android
is an open source and Linux-based operating system for mobile devices such as
smartphones and tablet computers. Android was developed by the Open Handset Alliance,
led by Google, and other companies.
To develop the android app we are going to use SDK, Java Programming language and
Extensible Mark-up Language (XML). By using a JAVA to write a code we will create single
app binary which can run on both phone and tablet.
An example has been provided to highlight each feature which is discussed. A detailed set of
practical will enable you to get an in-depth knowledge of how to make use of the various
elements you study. Once you get the feel of HTML5, CSS, JAVA Programming and UI, you
can create very attractive android application on your own.
Learning HTML5, CSS, JAVA Programming and SQLliteis definitely an interesting and
engrossing experience when creating android application.
At the end of the book we have discussed latest trends in web world.
Good wishes to all the students!
Chapter I
HTML5& CSS

1.0 Objective
1.1 Introduction
1.2 Features
1.3 Elements & attributes in HTML5 ,<canvas>, <video>, <audio>.
1.4 Introduction to Scalable Vector Graphics (SVG),Geolocation.
1.5 Form input types
1.6 HTML5 web storage
1.7 Introduction of HTML5 Web worker.
1.8 CSS
1.8.1 Introduction to Style Sheet
1.8.2 Types of style Sheets: Inline, External, Embedded CSS, Text formatting
properties, CSS Border, margin properties, Positioning.
1.8.3 Use of classes in CSS, color properties, use of <div>&<span>
1.9 Summary
1.10 Check Your Progress Answers

1.0 Objective
After studying this chapter you will be able to understand,
 Designing the webpage using HTML5
 Using SVG and Geolocations.
 How to use JAVA script in the background without affecting the performance of the
page
 How to use CSS for creating user interface.

1.1 Introduction:
HTML5 is the latest and most enhanced version of HTML.Technically, HTML is not a
programming language, but rather a mark up language. HTML5 is a standard for structuring
and presenting content on the World Wide Web. HTML5 is a response to the observation
that the HTML and XHTML in common use on the World Wide Web is a mixture of features
introduced by various specifications, along with those introduced by software products such
as web browsers, those established by common practice, together with many syntax errors
in existing web documents. It is also an attempt to define a single markup language that can
be written in either HTML or XHTML syntax. It includes detailed processing models to
encourage more interoperable implementations; it extends, improves and rationalises the
markup available for documents, and introduces markup and APIs for complex web
applications.
The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all
support many HTML5 features and Internet Explorer 9.0 will also have support for some
HTML5 functionality. The mobile web browsers that come pre-installed on iPhones, iPads,
and Android phones all have excellent support for HTML5.
1.2 Features:
Most of the new features of HTML5 are well supported by common browsers like Mozilla
Firefox, Google Chrome, Internet Explorer, Opera, Mobile Browsers etc. Here is a set of
some of the most prominent features introduced in HTML5.
- New Semantic Elements: These are like <header>, <footer>, and <section>.
- Forms 2.0: Improvements to HTML web forms where new attributes have been
introduced for <input> tag.
- Persistent Local Storage: To achieve without resorting to third-party plug-in.
- Web Socket: A next-generation bidirectional communication technology for web
applications.
- Server-Sent Events: HTML5 introduces events which flow from web server to the web
browsers and they are called Server-Sent Events (SSE).
- Canvas: This supports a two-dimensional drawing surface that you can program with
JavaScript.
- Audio & Video: You can embed audio or video on your web pages without resorting to
third-party plug-in.
- Geo location: Now visitors can choose to share their physical location with your web
application.
- Micro data: This lets you create your own vocabularies beyond HTML5 and extend your
web pages with custom semantics.
- Drag and drop: Drag and drop the items from one location to another location on the
same webpage.

HTML5 Elements:
HTML5 elements are marked up using start tags and end tags. Tags are delimited using
angle brackets with the tag name in between. The difference between start tags and end
tags is that the latter includes a slash before the tag name.
<tag name>Content goes here...</tag name>
Following is the example of an HTML5 element −
<p>...</p>
HTML5 tag names are case insensitive and may be written in all uppercase or mixed case,
although the most common convention is to stick with lowercase.
Most of the elements contain some content like <p>...</p> contains a paragraph. Some
elements, however, are forbidden from containing any content at all and these are known
as void elements. For example, br, hr, link, Meta, etc.

HTML5 Attributes:
Elements may contain attributes that are used to set various properties of an element.
Some attributes are defined globally and can be used on any element, while others are
defined for specific elements only. All attributes have a name and a value and look like as
shown below in the example.
Following is the example of an HTML5 attribute which illustrates how to mark up a div
element with an attribute named class using a value of "example"
<div class="example">...</div>
Attributes may only be specified within start tags and must never be used in end tags.
HTML5 attributes are case insensitive and may be written in all uppercase or mixed case,
although the most common convention is to stick with lowercase.

HTML5 Canvas:
HTML5 element <canvas> gives you an easy and powerful way to draw graphics. It
can be used to draw graphs, make photo compositions or do simple (and not so simple)
animations. Canvas has several methods for drawing paths, boxes, circles, text, and adding
images.
Example:
<canvas id="myCanvas" width="200" height="100"></canvas>

Note: Always specify an id attribute, and a width and height attribute to define the size of
the canvas. To add a border, use the style attribute.

HTML Video:
HTML5 features, include native video support without the need for Flash. In HTML5,
there are 3 supported video formats: MP4, WebM, and Ogg. The browser support for the
different formats is:

Browser MP4 WebM Ogg

Internet YES NO NO
Explorer

Chrome YES YES YES

Firefox YES YES YES

Safari YES NO NO
Opera YES (from YES YES
Opera 25)

Example:
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

The text between the <video> and </video> tags will only be displayed in browsers that do
not support the <video> element.

The controls attribute adds video controls, like play, pause, and volume.

It is a good idea to always include width and height attributes. If height and width are not
set, the page might flicker while the video loads.

The <source> element allows you to specify alternative video files which the browser may
choose from. The browser will use the first recognized format.

HTML5 Audio:
In HTML5, there are 3 supported audio formats: MP3, Wav, and Ogg.
The browser support for the different formats is:

Browser MP3 Wav Ogg

Internet Explorer YES NO NO

Chrome YES YES YES

Firefox YES YES YES

Safari YES YES NO

Opera YES YES YES

Example:
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

The text between the <audio> and </audio> tags will only be displayed in browsers that do
not support the <audio> element.

The controls attribute adds audio controls, like play, pause, and volume.
The <source> element allows you to specify alternative audio files which the browser may
choose from. The browser will use the first recognized format.

1.3 Introduction Scalable Vector Graphics(SVG):


SVG is used to define graphics for the Web. SVG has several methods
for drawing paths, boxes, circles, text, and graphic images.

SVG Circle:
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-
width="4" fill="yellow" />
</svg>

SVG Rectangle:
<svg width="400" height="100">
<rect width="400" height="100" style="fill:rgb(0,0,255);stroke-
width:10;stroke:rgb(0,0,0)" />
</svg>

Comparison of Canvas and SVG

The table below shows some important differences between Canvas and SVG:

Canvas SVG
Resolution dependent Resolution independent
No support for event handlers Support for event handlers
Poor text rendering capabilities Best suited for applications with large rendering
You can save the resulting image as .png or .jpg areas (Google Maps)
Slow rendering if complex (anything that uses
Well suited for graphic-intensive games the DOM a lot will be slow)
Not suited for game applications

1.1, 1.2, 1.3 Check Your Progress:

1. HTML is stand for Hyper Text ______ Protocol.


2. HTML5 is a standard for ________ and presenting content on the World Wide Web.

1.4 Form Input Type:


HTML5 introduces no less than a baker’s dozen (yes, that’s 13!) new input types for forms.
These new input types have dual benefits: using them means less development time and an
improved user experience.
Following is the simple example of using labels, radio buttons, and submit buttons −
...
<form action="http://example.com/cgiscript.pl" method="post">

<p>

<label for="firstname">first name:</label>


<input type="text" id="firstname"><br/>

<label for="lastname">last name:</label>


<input type="text" id="lastname"><br/>

<label for="email">email:</label>
<input type="text" id="email"><br>

<input type="radio" name="sex" value="male">Male<br>


<input type="radio" name="sex" value="female">Female<br>
<input type="submit" value="send"><input type="reset">

</p>
</form>
...
The <input> element in HTML5
HTML5 input elements introduced several new values for the type attribute. These are listed below.
S.No. Type & Description

1 datetime
A date and time (year, month, day, hour, minute, second, fractions of a second) encoded
according to ISO 8601 with the time zone set to UTC.

2 datetime-local
A date and time (year, month, day, hour, minute, second, fractions of a second) encoded
according to ISO 8601, with no time zone information.

3 date
A date (year, month, day) encoded according to ISO 8601.

4 month
A date consisting of a year and a month encoded according to ISO 8601.

5 week
A date consisting of a year and a week number encoded according to ISO 8601.

6 time
A time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601.

7 number
This accepts only numerical value. The step attribute specifies the precision, defaulting to 1.

8 range
The range type is used for input fields that should contain a value from a range of numbers.

9 email
This accepts only email value. This type is used for input fields that should contain an e-mail
address. If you try to submit a simple text, it forces to enter only email address in
[email protected] format.

10 url
This accepts only URL value. This type is used for input fields that should contain a URL
address. If you try to submit a simple text, it forces to enter only URL address either in
http://www.example.com format or in http://example.com format.

1.5 HTML5 web storage:

With web storage, web applications can store data locally within the user's browser.
HTML5 introduces two mechanisms, similar to HTTP session cookies, for storing structured data on
the client side and to overcome following drawbacks.
Cookies are included with every HTTP request, thereby slowing down your web application by
transmitting the same data.
Cookies are included with every HTTP request, thereby sending data unencrypted over the internet.
Cookies are limited to about 4 KB of data . Not enough to store required data.
The two storage's are session storage and local storage and they would be used to handle different
situations.
Session Storage
The Session Storage is designed for scenarios where the user is carrying out a single transaction, but
could be carrying out multiple transactions in different windows at the same time.

Local Storage
The Local Storage is designed for storage that spans multiple windows, and lasts beyond the current
session. In particular, Web applications may wish to store megabytes of user data, such as entire
user-authored documents or a user's mailbox, on the client side for performance reasons.

1.6 Web worker:


A web worker is a JavaScript running in the background, without affecting the performance
of the page. When executing scripts in an HTML page, the page becomes unresponsive until
the script is finished. A web worker is a JavaScript that runs in the background,
independently of other scripts, without affecting the performance of the page. You can
continue to do whatever you want: clicking, selecting things, etc., while the web worker
runs in the background.

Check Web Worker Support

Before creating a web worker, check whether the user's browser supports it:
if (typeof(Worker) !== "undefined") {
// Yes! Web worker support!
// some code.....
} else {
// Sorry! No Web Worker support...
}

Create a Web Worker File

Now, let's create our web worker in an external JavaScript.


Here, we create a script that counts. The script is stored in the "demo_workers.js" file:
var i = 0;

function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}

timedCount();
The important part of the code above is the postMessage() method - which is used to post a
message back to the HTML page.
Note: Normally web workers are not used for such simple scripts, but for more CPU
intensive tasks.

Create a Web Worker Object

Now that we have the web worker file, we need to call it from an HTML page.
The following lines checks if the worker already exists, if not - it creates a new web worker
object and runs the code in "demo_workers.js":
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
Then we can send and receive messages from the web worker.
Add an "onmessage" event listener to the web worker.
w.onmessage = function(event){
document.getElementById("result").innerHTML = event.data;
};
When the web worker posts a message, the code within the event listener is executed. The
data from the web worker is stored in event.data.

Terminate a Web Worker

When a web worker object is created, it will continue to listen for messages (even after the
external script is finished) until it is terminated.
To terminate a web worker, and free browser/computer resources, use the terminate()
method:
w.terminate();

Reuse the Web Worker


If you set the worker variable to undefined, after it has been terminated, you can reuse the
code:
w = undefined;

1.4, 1.5, 1.6Check Your Progress:


1. The Session Storage is designed for scenarios where the user is carrying out a ______
transaction, but could be carrying out multiple transactions in different windows at the same
time.
2. The Local Storage is designed for storage that spans ______ windows, and lasts beyond the
current session.
3. A ______ worker is a JavaScript running in the background, without affecting the
performance of the page.

1.7 CSS
1.7.1 Introduction to style sheet:
CSS is a language that describes the style of an HTML document.CSS describes how HTML
elements should be displayed. CSS handles the look and feel part of a web page. Using CSS,
you can control the color of the text, the style of fonts, the spacing between paragraphs,
how columns are sized and laid out, what background images or colors are used, layout
designs,variations in display for different devices and screen sizes as well as a variety of
other effects.
CSS is easy to learn and understand but it provides powerful control over the presentation
of an HTML document. Most commonly, CSS is combined with the markup languages HTML
or XHTML.

Advantages of CSS
 CSS saves time − You can write CSS once and then reuse same sheet in multiple
HTML pages. You can define a style for each HTML element and apply it to as many
Web pages as you want.
 Pages load faster − If you are using CSS, you do not need to write HTML tag
attributes every time. Just write one CSS rule of a tag and apply it to all the
occurrences of that tag. So less code means faster download times.
 Easy maintenance − To make a global change, simply change the style, and all
elements in all the web pages will be updated automatically.
 Superior styles to HTML − CSS has a much wider array of attributes than HTML, so
you can give a far better look to your HTML page in comparison to HTML attributes.
 Multiple Device Compatibility − Style sheets allow content to be optimized for more
than one type of device. By using the same HTML document, different versions of a
website can be presented for handheld devices such as PDAs and cell phones or for
printing.
 Global web standards − Now HTML attributes are being deprecated and it is being
recommended to use CSS. So its a good idea to start using CSS in all the HTML pages
to make them compatible to future browsers.
 Offline Browsing − CSS can store web applications locally with the help of an offline
catche.Using of this, we can view offline websites.The cache also ensures faster
loading and better overall performance of the website.
 Platform Independence − The Script offer consistent platform independence and
can support latest browsers as well.

CSS Versions
Cascading Style Sheets, level 1 (CSS1) was came out of W3C as a recommendation in
December 1996. This version describes the CSS language as well as a simple visual
formatting model for all the HTML tags.
CSS2 was became a W3C recommendation in May 1998 and builds on CSS1. This version
adds support for media-specific style sheets e.g. printers and aural devices, downloadable
fonts, element positioning and tables.
CSS3 was became a W3C recommendation in June 1999 and builds on older versions CSS. it
has divided into documentations is called as Modules and here each module having new
extension features defined in CSS2.
1.7.2 Types of Style sheets:
CSS comes in three types:

 In a separate file (external)


 At the top of a web page document (internal)
 Right next to the text it decorates (inline)
External style sheets are separate files full of CSS instructions (with the file extension .css).
When any web page includes an external stylesheet, its look and feel will be controlled by
this CSS file (unless you decide to override a style using one of these next two types). This is
how you change a whole website at once. And that's perfect if you want to keep up with the
latest fashion in web pages without rewriting every page!
Internal styles are placed at the top of each web page document, before any of the content
is listed. This is the next best thing to external, because they're easy to find, yet allow you to
'override' an external style sheet -- for that special page that wants to be a nonconformist!
Inline styles are placed right where you need them, next to the text or graphic you wish to
decorate. You can insert inline styles anywhere in the middle of your HTML code, giving you
real freedom to specify each web page element. On the other hand, this can make
maintaining web pages a real chore!

Embedded Style Sheet:


Embedded style sheets refer to when you embed style sheet information into an HTML
document using the <style> element. You do this by embedding the style sheet information
within <style></style> tags in the head of your document.

Text formatting properties:


CSS TEXT properties are various type like text color, text-align, text-decoration, letter-spacing
and many more properties.

Using these properties you can change the text formatting style.

Following are some CSS text properties listed. Using these properties you can play with text
formatting style.

CSS Color
CSS color property use to set the Text color. The color value can be specified following three
types:

1. Color Name: Orange


2. Color Hexadecimal Code: #FFA500
3. Color RGB: rgb(255, 165, 0)

Example:
<body>
<p style="color:orange;">CSS TEXT color name orange</p>
<p style="color:#FFA500;">CSS TEXT color hexadecimal code #FFA500</p>
<p style="color:rgb(255,156,0);">CSS TEXT RGB color code
rgb(255,156,0)</p>
</body>

Output:
CSS TEXT color name orange

CSS TEXT color hexadecimal code #FFA500

CSS TEXT RGB color code rgb(255,156,0)


CSS text-align:
CSS text-align property use to set the horizontal alignment of text.
text-align posible value center, left, right, or justify.
When you set text-align property value justify than the effect is both width (left or right)
equal like newspaper or books type.

Example:
<body>
<p style="text-align:right;">CSS TEXT align right</p>
<p style="text-align:center;">CSS TEXT align center</p>
<p style="text-align:left;">CSS TEXT align left</p>
<p style="text-align:justify;">Hello reader, this ia example of CSS text-align justify type. Both
side left and right are equal. Its like newspaper or book type. Hello reader, this ia example of CSS
text-align justify type. Both side left and right are equal. Its like newspaper or book type. Hello
reader, this ia example of CSS text-align justify type. Both side left and right are equal. Its like
newspaper or book type.</p>
</body>

Output:
CSS TEXT align right

CSS TEXT align center

CSS TEXT align left

Hello reader, this ia example of CSS text-align justify type. Both side left and right are equal. Its like newspaper or book
type. Hello reader, this ia example of CSS text-align justify type. Both side left and right are equal. Its like newspaper or
book type. Hello reader, this ia example of CSS text-align justify type. Both side left and right are equal. Its like newspaper
or book type.

CSS text-indent
CSS text-indent property is used to set the paragraph first line leftside leave the blank space.

Example
<body>
<p style="text-indent:35px;">This paragraph is example of CSS text-indent property and
value set 35px (pixel).
So it means paragraph first line leftside leave blank space end of blank space start a first line
paragraph text.</p>
</body>

Output:
This paragraph is example of CSS text-indent property and value set 35px (pixel). So it means paragraph first line left
side leave blank space end of blank space start a first line paragraph text.

CSS text - decoration


CSS text-decoration property use to decorate the text.

CSS text-decoration posible value underline, overline, blink, through etc.

Example
<body>
<p style="text-decoration:underline;">Text is underline decorate</p>
<p style="text-decoration:overline;">Text is overline decorate</p>
<p style="text-decoration:blink;">Text is blink decorate</p>
<p style="text-decoration:line-through;">Text is line delete decorate</p>
<p style="text-decoration:none;">Text is Nothing any decorate value</p>
</body>

Output:
Text is underline decorate

Text is overline decorate

Text is blink decorate

Text is line delete decorate

Text is nothing any decorate value

CSS text-transformation
CSS text-transformation property use to text transform.

CSS text-transformation posible value capitalize, lowercase and uppercase in a text.

CSS text-transformation property value capitalize, it means first letter capital for all word.
Example:
<body>
<p style="text-transform:capitalize;">this line transform capital</p>
<p style="text-transform:lowercase;">this line transform Lowercase</p>
<p style="text-transform:uppercase;">this line transform Uppercase</p>
</body>

Output:
This Line Transform Capital.
this line transform lowercase.
THIS LINE TRANSFORM UPPERCASE.

CSS letter-spacing
CSS letter-spacing property set blank space between each two letter.
Example:
<body>
<p style="letter-spacing:5px">This text is letter spacing</p>
</body>
Output:
This text is letter spacing

CSS word-spacing
CSS word-spacing property set blank space between each two word.
Example:
<body>
<p style="word-spacing:25px">This text is Word Spacing</p>
</body>

Output:
This text is Word Spacing
CSS white-space
CSS white-space property use to set a predefine task. CSS white-space possible value is
normal, pre.

Example:
<body>
<p style="white-space:pre">This text is Predefined Area

Predefined area second line</p>


</body>

Output:
This text is Predefined Area

Predefined area second line

CSS text-shadow
CSS text-shadow property is use to decorate text and apply shadow effect style.
Example:
<body>
<p style="text-shadow:4px 4px 8px orange;">This text is Text Shadow Effect</p>
</body>

Output:
This text is Text Shadow Effect

CSS Class:
CSS class is a selector to assign class name either one or group of element and apply specific
styles.

Using class selector you can easily modify element styles.

CSS class selector define using class attribute with value (user define class name).
CSS class selector identify using (".") dot sign concat with user define class name.

CSS Class use for when you using JavaScript its identify of element
using getElementByIClass() function.

1.7.3 CSS class advantages


One or more CSS class assign to a every single element seprate by single space.
Another advantages is assign same class one or more element with same styles.

Syntax
If you assign same class name multiple element syntax is like,
.class_name{ property:value; }

Example:
<html>
<head>
<style type="text/css">
.line {
color:purple;
font-size:20px;
background-color:#FF6633;
}
</style>
</head>
<body>
<p class="line">This is a paragraph line.</p>
<div class="line">This is a paragraph Second line.</div>
</body>
</html>

Output:
This is a paragraph line.
This is a paragraph Second line.
Syntax
CSS Class allows you to set a particular style for any HTML elements using CSS class.
If you assign same class multiple element with assign unique style each element, syntax
is like,
element.class_name{ property:value; }

Example
<html>
<head>
<style type="text/css">
p.line {
color:purple;
margin-left:20px;
}
div.line {
color:purple;
font-size:20px;
background-color:#FF6633;
}
</style>
</head>
<body>
<p class="line">This is a paragraph line.</p>
<div class="line">This is a paragraph Second line.</div>
</body>
</html>

Output:
This is a paragraph line.

This is a paragraph Second line.

Colour properties:
Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA values.
CSS Syntax
color: color|initial|inherit;

Property Values

Value Description Play it

Color Specifies the text color. Look at CSS Color Values for a complete list of possible Play it
color values. »

Initial Sets this property to its default value. Play it


»

Inherit Inherits this property from its parent element.

Div
Div (short for division) divides the content into individual sections. Each section can then have its
own formatting, as specified by the CSS. Div is a block-level container, meaning that there is a line
feed after the </div> tag.
For example, if we have the following CSS declaration:

.large {
color: #00FF00;
font-family:arial;
font-size: 4pt;
}

Span
Span is similar to div in that they both divide the content into individual sections. The difference is
that span goes into a finer level, so we can span to format a single character if needed. There is no
line feed after the </span> tag.
For example

.largefont {
color: #0066FF;
font-family:arial;
font-size: 6px;
}

1.7 Check Your Progress:


1. ______ is a language that describes the style of an HTML document.
2. ______ style sheets are separate files full of CSS.

3. ______ styles are placed at the top of each web page document, before any of the content is
listed.

4. ______ (short for division) divides the content into individual sections.

1.8 Summary:
HTML5 is the latest and most enhanced version of HTML. HTML5 is a response to the observation
that the HTML and XHTML in common use on the World Wide Web is a mixture of features
introduced by various specifications. SVG is used to define graphics for the Web using methods for
drawing paths, boxes, circles, text, and graphic images. A web worker is a JavaScript that runs in the
background, independently of other scripts, without affecting the performance of the page. CSS
describes how HTML elements should be displayed. Using CSS, you can control the color of the text,
the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what
background images or colors are used, layout designs and variations in display for different devices
and screen sizes as well as a variety of other effects.

1.9 Check Your Progress answers:

1.1, 1.2, 1.3 Check Your Progress:


1. transfer
2. structuring

1.4, 1.5, 1.6 Check Your Progress:


1. single
2. multiple
3. web

1.7 Check Your Progress:


1. Internal
2. External
3. CSS
4. Div

1.10 QUESTIONS FOR SELF-STUDY

1. What are different ways to integrate a CSS into a Web page?


2. What are the advantages and disadvantages of External Style Sheets?
3. What are different features of HTML5.
Chapter II
Introduction to Android

2.0 Objective
2.1 Introduction to Android
2.2 Android SDK
2.3 Android versions and features.
2.4 Summary
2.5 Check Your Progress Answers

2.0 Objective
After studying this chapter you will be able to understand,
 A little Background about mobile technologies
 Android Open platform
 Android SDK Features
 And different android version and their features.

2.1 Introduction to Android:


Android is a Linux based operating system it is designed primarily for touch screen mobile
devices such as smart phones and tablet computers. The operating system have developed
a lot in last 15 years starting from black and white phones to recent smart phones or mini
computers. One of the most widely used mobile OS these days is android. The android is
software that was founded in Palo Alto of California in 2003.
The android is a powerful operating system and it supports large number of applications in
Smartphones. These applications are more comfortable and advanced for the users. The
hardware that supports android software is based on ARM architecture platform. The
android is an open source operating system means that it’s free and any one can use it. The
android has got millions of apps available that can help you managing your life one or other
way and it is available low cost in market at that reasons android is very popular.
The android development supports with the full java programming language. Even other
packages that are API and JSE are not supported. The first version 1.0 of android
development kit (SDK) was released in 2008 and latest updated version is oreo.
Android -A little Background about mobile technologies and Operating
Systems
It seems like everyone has an opinion in the great 'who-makes-the-best-smartphone'
debate. At the heart of this humorous argument, however, isn't the phone itself, but rather
the operating systems that power everything else?The interesting part is that operating
system is mostly invisible; they're just the platform upon which everything else runs. Think
about the computer you're using to access this lesson. Something has to hold all of your
programs and features together, right? That's your computer's operating system. Let's take
a closer look at what its mobile counterpart entails .

What is a Mobile Operating System?


Most people don't go to their local wireless store and ask for a particular operating system.
They ask for an iPhone, an Android, a Windows phone or a handful of other options. But
secretly, it's the operating system that most people prefer. They like how one type handles
versus another.
A mobile operating system, sometimes called a mobile OS for short, is an operating system
that runs only on mobile devices. Consider it the backbone of all of your favorite
applications and programs. It's basically the system on top of which everything else sits. It
also is the basis for all of your settings, such as how you connect to the internet, the way
you text and how you keep your calendar appointments.
In case it's not already clear, mobile operating systems vary from device to device. Apple has
their own system that they call iOS. Samsung phones, for example, use the Android
operating system and even Windows gets into the action with their own phones and
Windows OS. You can find a mobile operating system on any of your handheld devices such
as smartphones and tablets.
Let's examine the most popular operating systems out there right now.

Types of Mobile Operating Systems


iOS
Apple's very own operating system,iOS runs the company's iPod, iPad, iPhone and Apple
Watch devices. It is only available on Apple products and responds to commands from the
user's fingertips. iOS features iTunes for music and the App Store for everything else. One of
the benefits of the Apple operating system is its built-in video chatting and Apple Music
capabilities.
Android
Android's OS is owned by Google and is considered open-source to Apple's closed system.
With an open-source system, software developers can build applications and programs until
their heart's content and users reap the benefits of tons of free software.Most Android lovers
cite the operating system's openness, which leads to more personalization options, as the
reason they're hardcore devotees.
Windows
Microsoft is no stranger to computer operating systems, but is a relative newcomer to mobile
OS. Its latest version uses the tiled layout common to its most recent computer OS. These
tiles can be rearranged and moved to the user's preferences.
BlackBerry OS
A lesser known, but still used OS is the one designed for BlackBerry devices, common among
business users. The BlackBerry operating system is well-liked for its enhanced security and
safety measures. It was the phone of choice for former President Barack Obama! BlackBerry
has been far more successful with an operating system that requires a trackball (like a
computer mouse) and a physical keyboard than a touch screen device like the iPhone.

2.1 Check Your Progress:


1. Android is a _______ based operating system

2. The hardware that supports android software is based on _______ architecture platform.

2.2 Android SDK


The Android software development kit (SDK) includes a comprehensive set of development tools. These
include a debugger, libraries, a handset emulator based on QEMU, documentation, sample code, and
tutorials. Currently supported development platforms include computers running Linux (any modern
desktop Linux distribution), Mac OS X 10.5.8 or later, and Windows 7 or later. As of March 2015, the SDK
is not available on Android itself, but software development is possible by using specialized Android
applications.

Android SDK Features:


The Android SDK can be broken down into several components. These include:

 Platform-tools

 Build-tools

 SDK-tools

 The Android Debug Bridge (ADB)

 Android Emulator

Build tools:
The Build tools were once categorized under the same heading as the Platform tools but have since
been decoupled so that they can be updated separately. As the name suggests, these are also needed
to build your Android apps. This includes the zipalign tool for instance, which optimizes the app to use
minimal memory when running prior to generating the final APK, and the apksigner which signs the APK
(surprise!) for subsequent verification.

Platform tools:
The Platform tools are more specifically suited to the version of Android that you want to target.
Generally, it is best to install the latest Platform tools, which will be installed by default. After first
installation though, you need to keep your Platform-tools constantly updated. The tools should be
backwards compatible, meaning that you will still be able to support older versions of Android.

Android Debug Bridge :


The Android Debug Bridge (ADB) is a program that allows you to communicate with any Android
device. It relies on Platform-tools in order to understand the Android version that is being used on said
device and hence it is included in the Platform-tools package. You can use ADB to access shell tools such
as logcat, to query your device ID or even to install apps.

The Android emulator:


The Android emulator is what lets you test and monitor apps on a PC, without necessarily needing to
have a device available. To use this, you also get an Android system image designed to run on PC
hardware. You’ll use the Android Virtual Device manager in order to choose which version of Android
you want to emulate, along with the device specifications (screen size, performance etc.).

Android Open Source Platform:


Android has open source roots. The project began under Android, Inc. in 2005, which
Google bought two years later. That same year, Google and several other companies formed
the Open Handset Alliance, with Android being the primary piece of software this
consortium is built on.
Android is based on the Linux kernel, and like that complex piece of code, most parts are open
source with a few binary blobs included to make things work with certain hardware. The core
Android platform, known as the Android Open Source Project (AOSP), is available for anyone to do
with what they wish.

2.3Android versions and features:


Version Features
Version Name
No
Android 8.1 Oreo Show battery level in "Quick Settings" for devices connected via
Bluetooth
Navigation buttons dim when not in use
UI updates to 'Power Off' and 'Restart'
Text messages are now white in color with same existing
transparency
Automatic light and dark themes
Emoji updates (i.e: Hamburger move the cheese slice position)
Android 8.0 Oreo PIP: Picture-in-Picture with resizable windows
Android Instant apps
Improved notifications system
Improved system settings
Lock screen redesign
Android Nougat Battery usage alerts
7.1.2 Nexus and Pixel specific improvements
Android Nougat Long press on the app icon enable new launch actions
7.1.1 The default keyboard allows now to send GIFs directly
New set of emojis
Android 7.1 Nougat Daydream Virtual Reality mode
Night Light
Storage manager improvements
Performance improvements for Touch and Display managements
Option to enable fingerprint swipe down gesture
Seamless system updates
Android 7.0 Nougat Unicode 9.0 emoji
Better multitasking
Multi-window mode (PIP, Freeform window)
Seamless system updates (with dual system partition)
Better performance and code size thanks to new JIT Compiler
Android Marshmallow New emojis
6.0.1
Android 6 Marshmallow USB Type-C support
Fingerprint Authentication support
Better battery life with "deep sleep"
Permissions dashboard
Android Pay
MIDI support
Google Now improvements
Android Lollipop Speed improvement
5.1.1 Bug fixes
Android 5.1 Lollipop Multiple SIM cards support
Quick settings shortcuts to join Wi-Fi networks or control
Bluetooth devices
Lock protection if lost or stolen
High Definition voice call
Stability and performance enhancements
Android Lollipop Performance improvements
5.0.2
Android Lollipop bug fixes, fix issues with video playback and password failures
5.0.1
Android 5.0 Lollipop New design (Material design)
Speed improvement
Battery consumption improvement
Android KitKat Fix Heartbleed / OpenSSL vulnerability
4.4.4
Android KitKat Enable Sprint Spark band 26 and band 41
4.4.3
Android KitKat Security enhancements
4.4.2
Android KitKat Enhance the camera on the Nexus 5
4.4.1
Android 4.4 KitKat Screen recording
New Translucent system UI
Enhanced notification access
System-wide settings for closed captioning
Performance improvements
Android 4.3 Jelly Bean Dial pad auto-complete
Photo Sphere enhancements
Camera app UI updated
4K resolution support
Ability to create restricted profiles for tablets
Hebrew and Arabic right-to-left (RTL) support
Bluetooth Low Energy (BLE) support
Bluetooth Audio/Video Remote Control Profile (AVRCP) 1.3
support
Security and performance enhancements
Android Jelly Bean Allow toggling Wi-Fi and Bluetooth state in Quick Settings using
4.2.2 long-press
Shows the percentage and estimated time remaining in the
active download notifications
Wireless charging and low battery sounds changed
Gallery app updated for faster loading with new image transition
Performance enhancements and bug fixes (Bluetooth A2DP
audio streaming fix...)
Android Jelly Bean Add support for Bluetooth gamepads and joysticks HID devices
4.2.1
Android 4.2 Jelly Bean Lockscreen widgets
360 degree images with Photo Sphere
Gesture Typing, for faster typing
Wireless display with Miracast
Daydream to display information when idle or docked
Multi-user for tablets
Android Jelly Bean Enable Home screen rotation
4.1.2 Fix bugs and enhance performances
Android Jelly Bean Fix a bug on screen orientation
4.1.1
Android 4.1 Jelly Bean Voice Search
Speed enhancements
Camera app improvements
Accessibility: gesture mode, enable braille external keyboards...
Android Ice Cream stability improvements
4.0.4 Sandwich better camera performance
smoother screen rotation
Android Ice Cream Social stream API in Contacts provider to show updates
4.0.3 Sandwich associated to your contacts
Video stabilization and QVGA video resolution API access
Accessibility API refinements for screen readers
Calendar provider updates
Android Ice Cream
4.0.2 Sandwich
Android Ice Cream Facial recognition (Face Unlock)
4.0.1 Sandwich UI use Hardware acceleration
Better voice recognition (dictating/Voice typing)
Web browser, allows up to 16 tabs
Updated launcher (customizable)
Android Beam app to exchange data through NFC
Android 4.0 Ice Cream New lock screen actions
Sandwich Improved text input and spell-checking
Control over network data
Email app supports EAS v14
WI-FI direct
BlueTooth Health Device Profile
Android Honeycomb
3.2.6
Android Honeycomb Added "Pay as you go" for tablets
3.2.4
Android Honeycomb
3.2.2
Android Honeycomb Android Market updates including easier automatic updates
3.2.1 Google Books updates
Wi-Fi improvements
Chinese handwriting prediction improved
Android 3.2 Honeycomb Optimizations for a wider range of tablets
Compatibility display mode (zoom for fixed-sized apps)
Media sync from SD card
Android 3.1 Honeycomb UI improvements
Open Accessory API
USB host API
Mice, joysticks, gamepads... support
Resizable Home screen widgets
MTP notifications
RTP API for audio
Android 3.0 Honeycomb Multi core support
Better tablet support
Updated 3D UI

customizable homescreens
recent applications viewing
redone keyboard layout
Media/Picture transport protocol
Google Talk video chat
Google eBooks
"Private browsing"
System-wide Clipboard
HTTP Live streaming
Android Gingerbread Google Wallet support for the Nexus S 4G
2.3.7
Android Gingerbread Voice search issue fixed
2.3.6
Android Gingerbread Improved network performance for the Nexus S 4G
2.3.5 Fixed Bluetooth issues on the Samsung Galaxy S
Gmail app. improvements
Android Gingerbread Voice or video chat using Google Talk
2.3.4
Android Gingerbread
2.3.3
Android 2.3 Gingerbread Updated UI
Improved keyboard ease of use
Improved copy/paste
Improved power management
Social networking features
Near Field Communication support
Native VoIP/SIP support
Video call support
Android 2.2 Froyo Speed improvements
JIT implementation
USB Tethering
Applications installation to the expandable memory
Upload file support in the browser
Animated GIFs
Android 2.1 Éclair Updated UI
Android Éclair
2.0.1
Android 2.0 Éclair HTML
Digital zoom
Microsoft Exchange support
Bluetooth 2.1
Live Wallpapers
Updated UI
Android 1.6 Donut Gesture framework
Turn-by-turn navigation
Android 1.5 Cupcake Bluetooth A2DP, AVRCP support
Soft-keyboard with text-prediction
Record/watch videos
Android 1.1 Banana bread "Show" & "Hide" numeric keyboard, in caller application
Ability to save MMS attachments
Android 1.0 Apple pie Download and updates via Android Market
Web Browser
Camera support
Gmail, Contacts and Google Agenda synchronization
Google Maps
YouTube application
2.2, 2.3 Check Your Progress:
Fill in the blanks

1. _____ is stand for software development kit.


2. _____ is stand for Android Debug Bridge.
True or False
1. The Platform tools are more specifically suited to the version of Android that you want to
target.
2. The Android emulator is what lets you test and monitor apps on a PC, without necessarily
needing to have a device available.

2.4Summary
A mobile operating system, sometimes called a mobile OS for short, is an operating system that runs only
on mobile devices. The Android software development kit (SDK) includes a comprehensive set of
development tools. These include a debugger, libraries, a handset emulator based on QEMU,
documentation, sample code, and tutorials. Android is based on the Linux kernel, and like that complex
piece of code, most parts are open source with a few binary blobs included to make things work with
certain hardware.

2.5Check Your Progress answers:


2.1 Check Your Progress:
1. Linux
2. ARM

2.2, 2.3 Check Your Progress:


1. development
2. Debug
True or False
1. True
2. True

2.6QUESTIONS FOR SELF-STUDY


Write a short note on Google Android SDK?
State the importance of emulator.
Chapter III
Tools for Development

3.0 Objective
3.1 Installing Android
3.2 First Android application
3.3 Running on Emulator
3.4 Android development Tools, Android Studio, IDEs and Tools
3.5 Summary
3.6 Check Your Progress answers

3.0 Objective:
After studying this chapter you will be able to understand,
 How to install Android Studio
 Write your first android application
 Testing your application in virtual environment

3.1Installing Android:
Google provides Android Studio for the Windows, Mac OS X, and Linux platforms. Before
downloading Android Studio, make sure your platform meets one of the following
requirements:
Windows OS

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


 2 GB RAM minimum, 8 GB RAM recommended
 2 GB of available disk space minimum, 4 GB Recommended (500 MB for IDE + 1.5 GB for
Android SDK and emulator system image)
 1280 x 800 minimum screen resolution
 JDK 8
 For accelerated emulator: 64-bit operating system and Intel processor with support for Intel
VT-x, Intel EM64T (Intel 64), and Execute Disable (XD) Bit functionality
Mac OS

 Mac OS X 10.8.5 or higher, up to 10.11.4 (El Capitan)


 2 GB RAM minimum, 8 GB RAM recommended
 2 GB of available disk space minimum, 4 GB Recommended (500 MB for IDE + 1.5 GB for
Android SDK and emulator system image)
 1280 x 800 minimum screen resolution
 JDK 6
Linux OS
 GNOME or KDE desktop: Tested on Ubuntu 12.04, Precise Pangolin (64-bit distribution
capable of running 32-bit applications)
 64-bit distribution capable of running 32-bit applications
 GNU C Library (glibc) 2.11 or later
 2 GB RAM minimum, 8 GB RAM recommended
 2 GB of available disk space minimum, 4 GB Recommended (500 MB for IDE + 1.5 GB for
Android SDK and emulator system image)
 1280 x 800 minimum screen resolution
 JDK 8
 For accelerated emulator: Intel processor with support for Intel VT-x, Intel EM64T (Intel 64),
and Execute Disable (XD) Bit functionality, or AMD processor with support for AMD
Virtualization (AMD-V)
After launched android-studio-bundle-143.2821654-windows.exe to start the installation
process. The installer responded by presenting the Android Studio Setup dialog box shown
in Figure 1.

Figure 1. Set up Android Studio

Clicking Next took me to the following dialog box, which gives you the option to decline
installing the Android SDK (included with the installer) and an Android Virtual Device (AVD).
Figure 2. Do you want to install the Android SDK and AVD?

I chose to keep the default settings. After clicking Next, you'll be taken to the license
agreement dialog box. Accept the license to continue the installation.

Figure 3. Accept the license agreement to continue installation

The next dialog box invites you to change the installation locations for Android Studio and
the Android SDK.
Figure 4. Set the Android Studio and Android SDK installation locations

Change the location or accept the default locations and click Next.
The installer defaults to creating a shortcut for launching this program, or you can choose to
decline. I recommend that you create the shortcut, then click the Install button to begin
installation.

Figure 5. Create a new shortcut for Android Studio

The resulting dialog box shows the progress of installing Android Studio and the Android
SDK. Clicking the Show Details button will let you view detailed information about the
installation progress.
The dialog box will inform you when installation has finished. When you click Next, you
should see the following:
Figure 6. Leave the Start Android Studio check box checked to run this software

To complete your installation, leave the Start Android Studio box checked and click Finish.
Running Android Studio
Android Studio presents a splash screen when it starts running:

Figure 7. Android Studio's start screen

On your first run, you'll be asked to respond to several configuration-oriented dialog boxes.
The first dialog box focuses on importing settings from any previously installed version of
Android Studio.
Figure 8. Import settings

If you're like me, and don't have a previously installed version, you can just keep the default
setting and click OK. Android Studio will respond with a slightly enhanced version of the
splash screen, followed by the Android Studio Setup Wizard dialog box:

Figure 9. Validate your Android SDK and development environment setup

When you click Next, the setup wizard invites you to select an installation type for your SDK
components. For now I recommend you keep the default standard setting.
Figure 10. Choose an installation type

Click Next and verify your settings, then click Finish to continue.
Figure 11. Review settings

The wizard will download and unzip various components. Click Show Details if you want to
see more information about the archives being downloaded and their contents.
Figure 12. The wizard downloads and unzips Android Studio components

If your computer isn't Intel based, you might get an unpleasant surprise after the
components have completely downloaded and unzipped:

Figure 13. Intel-based hardware acceleration is unavailable


Your options are to either put up with the slow emulator or use an Android device to speed
up development. I'll discuss the latter option later in the tutorial.
Finally, click Finish to complete the wizard. You should see the Welcome to Android Studio
dialog box:

Figure 14. Welcome to Android Studio

You'll use this dialog to start up a new Android Studio project, work with an existing project,
and more. You can access it anytime by double-clicking the Android Studio shortcut on your
desktop.
3.2 First Android Application

The quickest way to get to know Android Studio is to use it to develop an app. We'll start
with a variation on the "Hello, World" application: a little mobile app that displays a
"Welcome to Android" message.
In the steps that follow, you'll start a new Android Studio project and get to know the
project workspace, including the project editor that you'll use to code the app in Part 2.
Starting a new project
From our setup so far, you should still have Android Studio running with the Welcome to
Android Studio dialog box. From here, click Start a new Android Studio project. Android
Studio will respond with the Create New Project dialog box shown in Figure 15.
Figure 15. Create a new project

Enter W2A (Welcome to Android) as the application name and tmv.com.project as the
company domain name. You should then see E:\Project\MyApplication as the project
location. Click Next to select your target devices.
Figure 16. Select your target device categories

Android Studio lets you select form factors, or categories of target devices, for every app
you create. I would have preferred to keep the default API 15: Android 4.0.3
(IceCreamSandwich) minimum SDK setting (under Phone and Tablet), which is supported by
my Amazon Kindle Fire HD tablet. Because Android Studio doesn't currently support this API
level (even when you add the 4.0.3 system image via the SDK Manager), I changed this
setting to API 14: Android 4.0 (IceCreamSandwich), which is also supported by my tablet.
Click Next, and you will be given the opportunity to choose a template for your app's main
activity. For now we'll stick with Empty Activity. Select this template and click Next.
Figure 17. Specify an activity template

Next you'll customize the activity:


Figure 18. Customize your activity

Enter W2A as the activity name and main as the layout name, and click Finish to complete
this step. Android Studio will respond that it is creating the project, then take you to the
project workspace.

Figure 19. Android Studio workspace


The project workspace is organized around a menu bar, a tool bar, a work area, additional
components that lead to more windows (such as a Gradle Console window), and a status
bar. Also note the Tip of the Day dialog box, which you can disable if you like.
Accessing AVD Manager or SDK Manager from menu and tool bar
To access the traditional AVD Manager or SDK Manager, select Android from the Tools
menu followed by AVD Manager or SDK Manager from the resulting pop-up menu (or click
their tool bar icons).
The project and editor windows
When you enter the project workspace, W2A is identified as the current project, but you
won't immediately see the project details. After a few moments, these details will appear in
two new windows.

Figure 20. The project and editor windows

The project window is organized into a tree whose main branches are App and Gradle
Scripts. The App branch is further organized into manifests, java, and res subbranches:

 manifests stores AndroidManifest.xml, which is an XML file that describes the structure of
an Android app. This file also records permission settings (where applicable) and other
details about the app.
 java stores an app's Java source files according to a package hierarchy, which
is ca.javajeff.w2a in this example.
 res stores an app's resource files, which are organized into drawable, layout, mipmap, and
values subbranches:
o drawable: an initially empty location in which to store an app's artwork
o layout: a location containing an app's layout files; initially, main.xml(the main activity's
layout file) is stored here
o mipmap: a location containing various ic_launcher.png files that store launcher screen icons
of different resolutions
o values: a location containing colors.xml, dimens.xml, strings.xml, and styles.xml
The Gradle Scripts branch identifies various .gradle (such as build.gradle)
and .properties (such as local.properties) files that are used by the Gradle-based build
system.

3.3Run Android App in AVD / Emulator:

Below are the steps to run an Android App in AVD of Emulator:


Step 1: Firstly, open the AVD Manager directly by the AVD icon in the Toolbar.

Step 2: Your Virtual Devices list will be opened on your Computer screen. After that you
select that AVD on which you want to run your App.
If you don’t see any AVD (Android Virtual Device) that means you haven’t created not even
one. Read this, How to Create New AVD In Emulator.
Step 3: After that your AVD / Emulator will open up. It will take time to start depending on
your system configuration and pixel resolution of AVD. Choose less pixel resolution for
faster loading of AVD.

Step 4: After that you can run app directly as shown in figure below. Click on run icon.
Step 5: You can also run app go to the Menu bar and Click on Run > Run app. (Shift+F10)
shortcut key to run app in AVD of Emulator in android studio.
Step 6: After that Device chooser will be opened on your computer screen. Choose a
running device and Click OK.
Step 7: Your Android app run in AVD / Emulator in android studio.

3.1, 3.2, 3.3 Check Your Progresss:


1. _______ provides Android Studio for the Windows, Mac OS X, and Linux platforms.
2. _______stand for Android Virtual Device.

3.4 Android developer tools

Android Studio
No list of Android development tools would be complete without Android Studio. This
is the official IDE (Integrated Development Environment) for Android, making it the number
one choice for the majority of developers looking to make basic apps in-keeping with
Google’s Material Design and with access to all the advanced features of the platform.

The IDE is where any developer will spend most of their time: it acts as an editor for the
chosen programming language (Android Studio supports Java, C++ and now Kotlin, though
Java is the official language of Android), a compiler that can create APK files and a file
system for arranging your project. It also includes an XML editor and ‘design view’ for
arranging elements on the screen. Android Studio offers an entire suite of additional tools
too – some of which we’ll examine in this post – and thankfully most of this will now come
bundled together as a single download. In fact, it also comes bundled with the Android SDK
itself, though you will still need to download and install the Java JDK separately. You should
also check out our full Android Studio tutorial for beginners.
Developing with Java and the Android SDK does have a somewhat steep learning curve, but in terms
of integration, support and features Android Studio can’t be beaten.

AVD Manager
The AVD Manager tool is bundled with Android Studio. AVD stands for ‘Android Virtual
Device’, so essentially this is an emulator for running Android applications on your PC. This is
useful because it means that you can test your apps quickly without having to constantly
install them on physical devices. More importantly, the AVD Manager allows you to create
lots of different emulators with different screen sizes, specifications and versions of
Android. This means you can see what your creation will look like on any given device and
thereby ensure support across the most popular gadgets. Performance is getting better all
the time, especially with the fast virt mode, which runs an Intel version of Android on your PC
and removes the need for instruction level emulation.

Android Device Monitor


Another built-in Android development tool, the Android Device Monitor allows you to monitor
your device or virtual device during runtime and get access to information such as how
many processes are running on what thread, network stats, the LogCat and more. It’s great
for testing the performance of your apps and seeing what’s going on under the.

Android Debug Bridge


The ADB shell is a useful little command-line tool that you can use to communicate with or run commands on a
connected Android device (virtual or physical). It comes with Android Studio and for the most part you won’t need
to worry about it. Every now and then though, you’ll be following a tutorial and find you need to open it up. To do
so, navigate to the platform-tools folder of your Android SDK installation or whichever folder adb.exe is located
and open up a command line (Shift + RMB > Open Command Window Here).

3.4 Check Your Progress:


1. _______stand for Integrated Development Environment.
2. The _______shell is a useful little command-line tool that you can use to communicate with or run commands
on a connected Android device.
3. _______Device Monitor allows you to monitor your device or virtual device during runtime and get
access to information such as how many processes are running on what thread, network stats,
the LogCat and more.
4. Android Studio supports Java, C++ and now _______, though Java is the official language of
Android
3.5Summary:
Google provides Android Studio for the Windows, Mac OS X, and Linux platforms. The quickest way
to get to know Android Studio is to use it to develop an app. Android Studio is the official IDE
(Integrated Development Environment) for Android, making it the number one choice for the
majority of developers looking to make basic apps in-keeping with Google’s Material Design and
with access to all the advanced features of the platform. AVD stands for ‘Android Virtual Device’, so
essentially this is an emulator for running Android applications on your PC.

3.6Check Your Progress answers:

3.1, 3.2, 3.3 Check Your Progresss:


Google
AVD

3.4 Check Your Progresss:


IDE
ADB
Monitor
Kotlin

3.7QUESTIONS FOR SELF-STUDY


Write a short note on;
1) Android Studio
2) AVD Manager
Chapter IV
Android Architecture and OOPS
4.0 Objective
4.1 Building Blocks of Android
4.2 Java Classes and Objects, Class Methods and Instances, Inheritance and
Polymorphism in Java and Interface and Abstract class.
4.3 Summary
4.4 Check Your Progress answers

4.0 Objective
After studying this chapter you will be able to understand
 Different building Blocks of Android
 Java Classes and Objects
 Class Methods and Instances
 Inheritance and Polymorphism in Java & Interface and Abstract class.

4.1 Building Blocks of Android

There are different types of building blocks of android are there, which are;

 Activities
 Services
 Broadcast Receivers
 Content Providers
 Intent

Activities
Activity processes have application components the user is interact .Its represents the
presentation layer of an Android application. Its presents screen in your application.

Services
Android offers the Service class to create application components that handle long-lived
operation and include functionality that doesn't require a user interface.
Services are started, stopped and controlled from other application components, including
Activities, Broadcast Receivers, and other Services.

Intent
Intent are used as a message-passing mechanism that both within your application and
between application

 Starts a particular Service or Activity using a class name.


 Start an Activity or Service to perform an action with a particular piece of data.
 Broadcast that an event has occurred

Broadcast Receiver
Broadcast Intents are used to notify application of system or application events, extending
the event-driven programming model between applications.
Within your application, construct the intent you want to broadcast and call send Broadcast
to send it .

Content Providers
Content Providers provide a interface for publishing and the content schema. Content
Providers can be shared between applications, queried for results, have their existing record
deleted or updated, and record added.

4.1 Check Your Progress:


1. _______processes have application components the user is interacting with.
2. _______ are used as a message-passing mechanism that both within your application and
between application
3. _______ is component which is run in background and includes functionality that doesn't
require a user interface.

4.2Object Oriented Programming:

Object-Oriented Programming is a methodology or paradigm to design a program using


classes and objects. It simplifies the software development and maintenance by providing
some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.

Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example:
to convince the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

There are two types of polymorphism in java:


1) Static Polymorphism also known as compiles time polymorphism:
Polymorphism that is resolved during compiler time is known as static polymorphism.
Method overloading is an example of compile time polymorphism.
Method Overloading: This allows us to have more than one method having the same name,
if the parameters of methods are different in number, sequence and data types of
parameters.

2) Dynamic Polymorphism also known as runtime polymorphism:


It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a
process in which a call to an overridden method is resolved at runtime, thats why it is called
runtime polymorphism.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.

Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java
1. Abstract class
2. Interface

Abstract class in Java


A class that is declared as abstract is known as abstract class. It needs to be extended and
its method implemented. It cannot be instantiated.
Example :
abstract class A{}

abstract method

A method that is declared as abstract and does not have implementation is known as
abstract method.

Example
abstract void printStatus();//no body and abstract
Program:
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Output:
running safely..

Interface in Java
The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and
multiple inheritance in Java.It cannot be instantiated just like abstract class.
Why use Java interface?

There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
Program:
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Output:
Hello

Difference between abstract class and interface


Abstract class Interface
1) Abstract class can have abstract Interface can have only abstract methods. Since
and non-abstract methods. Java 8, it can have default and static
methods also.
2) Abstract class doesn't support Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, Interface has only static and final variables.
non-final, static and non-static
variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to The interface keyword is used to declare interface.
declare abstract class.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

4.2 Check Your Progress:


1. Any entity that has state and behaviour is known as an________.
2. Collection of objects is called ________..
3. When one task is performed by different ways known as ________.
4. ________ class can have abstract and non-abstract methods.

4.3Summary:
There are different types of building blocks of android are there, which are; Activities,
Services, Broadcast, Receivers, Content Providers, Intent. Content Providers can be shared
between applications, queried for results, have their existing record deleted or updated, and
record added. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.
4.4Check Your Progress answers:
4.1 Check Your Progress:
1. Activity
2. Intent
3. Service
4.2 Check Your Progress:
1. object
2. class
3. polymorphism
4. Abstract

4.5QUESTIONS FOR SELF-STUDY


1. What is difference between Abstract class and polymorphism?
2. What is BroadcastReceiver? Explain with Example
3. Explain AVD,Android Device monitor and ADB
Chapter V
Android User Interface

5.0 Objective
5.1 Fundamental Android UI Design, Introducing Views, In Creating new Views
5.2 Introducing Layouts, Using resources, Complex UI components.
5.3 Building UI for performance using themes.
5.4 Debugging Android Code.
5.5 Summary
5.6 Check Your Progress answers

5.0 Objective:
After studying this chapter you will be able to understand
 How to design Android application user interface.
 Using layouts for designing,
 Handling complex UI components
 Using themes and debugging android code.

5.1 Fundamental Android UI Design


The basic unit of android application is the activity. A UI is defined in an xml file. During
compilation, each element in the XML is compiled into equivalent Android GUI class with
attributes represented by methods.

View and ViewGroups


The Android View class and ViewGroup class are two very central classes in Android apps.
An Android app contains one or more activities. An Android activity is a screen, similar to
windows in a desktop application. Inside an activity you can have GUI components. The GUI
components are instances of Viewer ViewGroup subclasses. It may sound a bit abstract at
this point, but I will explain both in more detail below.

View
The View class is a superclass for all GUI components in Android. For instance,
the TextView class which is used to display text labels in Android apps is a subclass of View.
Android contains the following commonly used View subclasses:

 TextView
 EditText
 ImageView
 ProgressBar
 Button
 ImageButton
 CheckBox
 DatePicker

These are only some of the many, many subclasses of the View class.

ViewGroup
The ViewGroup class is a subclass of the View class. ViewGroup instances work as containers
for Viewinstances to group View instances together. Android contains the following
commonly used ViewGroup subclasses:

 LinearLayout
 RelativeLayout
 ListView
 GridView

These are not the only ViewGroup subclasses Android contains. There are others but which
are less used.

The ViewGroup subclasses listed above group View instances together and takes care of
their layout. For instance, the LinearLayout will render the components after each other
either horizontally or vertically.

5.1 Check Your Progress:


1. The ________ class is a superclass for all GUI components in Android.
2. The ________ class is a subclass of the View class.

5.2 Introducing Layouts


There are many types of layout. Some of which are listed below −

 Linear Layout
 Absolute Layout
 Table Layout
 Frame Layout
 Relative Layout
Linear Layout
Linear layout is further divided into horizontal and vertical layout. It means it can arrange
views in a single column or in a single row. Here is the code of linear layout(vertical) that
includes a text view.
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >

<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>

AbsoluteLayout
The AbsoluteLayout enables you to specify the exact location of its children. It can be
declared like this.
<AbsoluteLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >

<Button
android:layout_width=”188dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”126px”
android:layout_y=”361px” />
</AbsoluteLayout>

TableLayout
The TableLayout groups views into rows and columns. It can be declared like this.
<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent” >
<TableRow>
<TextView
android:text=”User Name:”
anroid:width =”120dp” />
<EditText
android:id=”@+id/txtUserName”
android:width=”200dp” />
</TableRow>
</TableLayout>
RelativeLayout
The RelativeLayout enables you to specify how child views are positioned relative to each
other.It can be declared like this.
<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
</RelativeLayout>

FrameLayout
The FrameLayout is a placeholder on screen that you can use to display a single view. It can
be declared like this.
<?xml version=”1.0” encoding=”utf-8”?>
<FrameLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true” >

<ImageView
android:src = “@drawable/droid”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</FrameLayout>

5.3 Building UI for performance using themes:

We have only been applying styles to views that are inside an activity. Android
allows you to apply styles to entire activities and applications too. When a style is applied to
an activity or application, it becomes a theme.
By default, all apps created using the latest version of Android Studio use a theme
called AppTheme . AppTheme is a descendant of the well-known AppCompat theme, a
large and very comprehensive theme that can affect the looks of almost all the commonly
used views.
You can find the definition of AppTheme in styles.xml:

<!-- Base application theme. -->


<stylename="AppTheme"parent="Theme.AppCompat.Light.DarkActionBar">
<itemname="colorPrimary">@color/colorPrimary</item>
<itemname="colorPrimaryDark">@color/colorPrimaryDark</item>
<itemname="colorAccent">@color/colorAccent</item>
</style>

5.4 Debugging the Code:


Debugging is one of the essential parts of a developer’s everyday life. We always strive to
write bulletproof code and bug-free applications but to do this, we have to fix every bug,
which are sometimes hard to spot in the code. Debugging allows you to go through each
line of code, evaluating your app’s variables, methods and how well your code is working.
It’s easier to find small mistake in large pieces of code. In this article we will go through
basic tips and tricks on debugging an Android app.
Start debug mode
When you want to start the debugging mode, first make sure your device is setup for
debugging and connected to USB, and open your project in Android Studio (AS) and just
click the Debug icon . Then select your device in the Choose Device window, and Android
Studio will launch your application in the debug mode. Android Studio will also
automatically open the Debug tool. You can turn it on manually by clicking Debug! at the
bottom of Android Studio. Another way to start debugging without having to restart your
app is by clicking on “Attach debugger to Android process” . You also have to select the
device and the app (process) you want to attach the debugger to. This option is also very
useful if you want to debug a specific feature, and you have to go through a couple of
other screens in the meantime. Because some operations run slower in the debug mode
going through the app without the debug mode on is much faster. When you are one
click away from the thing you want to debug, attach a debugger to your app and start
debugging right there.
Debug using Logs
The easiest way to debug your code is to use Log. This is a utility that allows you to send
log outputs, which you can then view in Logcat in AS. You don’t even need to run your
app in the debug mode to do this. Simply use android.util.Log in combination with one of
the following methods: Log.v(), Log.d(), Log.i(), Log.w(), Log.e() or Log.wtf(). All of them
use 2 string parameters: TAG and your message. You can also pass Throwable as a third
parameter, which will log your TAG, message and exception log. By using different
methods — levels of verbosity (VERBOSE, DEBUG, INFO, WARNING, ERROR) — you can
later filter the logs out or even set up AS and customize the Logcat text colors and text
background for each level.

Logcat
At STRV we use the Logcat utility, which handles if-statement among other things. Check
it out here. In build.gradle we have buildconfig property LOGS, which can be set to true in
the debug build type and to false in the release type. Logcat always check the LOGS
property before logging any message. Then you don’t have to worry about wrapping it in
any if-statement.
Simply call the method:
Logcat.d(“Your message here”);
You can also set other parameters in this class. The message can include “Code location”.
This means that it displays the name of the method, the line of code and also the thread
where Logcat is called. Another cool thing about Logcat is that you can log formatted
messages. So instead of:
Logcat.d(“Message with index: ” + someInteger)
we use:
Logcat.d(“Message with index: %d”, someInteger)
This method allows you to have as many parameters as you want.

Debug with breakpoints


Android Studio will highlight whatever line of code the app stops at when a breakpoint is
hit. The hard part starts in the Debug window — examining every variable that is
currently allocated and going line by line or jumping to another breakpoint.

5.2, 5.3 &5.4 Check Your Progress:


1. _______layout is further divided into horizontal and vertical layout.
2. The _______ groups views into rows and columns.
3. The _______ enables you to specify how child views are positioned relative to each other.
4. The _______ is a placeholder on screen that you can use to display a single view.
5. When a _______ is applied to an activity or application, it becomes a theme.

5.5 Summary
A UI is defined in an xml file. During compilation, each element in the XML is compiled into
equivalent Android GUI class with attributes represented by methods. The Android View class and
ViewGroup class are two very central classes in Android apps. Debugging allows you to go through
each line of code, evaluating your app’s variables, methods and how well your code is working.
5.6 Check Your Progress answers:
5.1 Check Your Progress:

1. View
2. ViewGroup

5.2, 5.3 & 5.4 Check Your Progress:

1. Linear
2. TableLayout
3. RelativeLayout
4. FrameLayout
5. style

5.7 QUESTIONS FOR SELF-STUDY


1. What are different types of layout?

2. Write a short note on Views


Chapter VI
Activity, Intent & Fragment

6.0 Objective
6.1 Introduction to Activity
6.2 Lifecycle of Activity
6.3 Introduction to Intent
6.4 Intent Filter
6.5 Fragment
6.6 Lifecycle of Fragment
6.7 Summary
6.8 Check Your Progress answers

6.0 Objective:
After studying this chapter you will be able to understand
 Lifecycle of the activity
 Different types of intent
 How to use filters to pinpoint the set of Activities, Services, and Broadcast receivers
that can handle the Intent
 How to use a multi-pane UI and reuse a fragment in multiple activities.

6.1Introduction to Activity:
An activity represents a single screen with a user interface just like window or frame of
Java.Android activity is the subclass of ContextThemeWrapper class. The Activity class
defines the following call backs i.e. events.
6.2Lifecycle of Activity
onCreate():
Called when the activity is first created. This is where you should do all of your normal static
set up: create views, bind data to lists, etc. This method also provides you with a Bundle
containing the activity's previously frozen state, if there was one.
Always followed by onStart().

onStart():
Called when the activity is becoming visible to the user.Followed by onResume() if the
activity comes to the foreground, or onStop() if it becomes hidden.
onResume():
Called when the activity will start interacting with the user. At this point your activity is at
the top of the activity stack, with user input going to it. Always followed by onPause().
onPause():
Called when the system is about to start resuming a previous activity. This is
typically used to commit unsaved changes to persistent data, stop animations and other
things that may be consuming CPU, etc. Implementations of this method must be very quick
because the next activity will not be resumed until this method returns.
Followed by either onResume() if the activity returns back to the front, or onStop() if it
becomes invisible to the user.
onRestart()
Called after your activity has been stopped, prior to it being started again. Always
followed by onStart()

onStop()
Called when the activity is no longer visible to the user, because another activity has been
resumed and is covering this one. This may happen either because a new activity is being
started, an existing one is being brought in front of this one, or this one is being destroyed.
Followed by either onRestart() if this activity is coming back to interact with the user, or
onDestroy() if this activity is going away.
onDestroy()
The final call you receive before your activity is destroyed. This can happen either
because the activity is finishing (someone called finish() on it, or because the system is
temporarily destroying this instance of the activity to save space. You can distinguish
between these two scenarios with the isfinishing() method.

6.3Introduction to Intent:
Intents are asynchronous messages which allow application components to request
functionality from other Android components. Intents allow you to interact with components
from the same applications as well as with components contributed by other applications.
For example, an activity can start an external activity for taking a picture.
There are 2 types of intent:
1)Implicit Intent
2)Explicit Intent

1)Implicit Intent:

Implicit intents specify the action which should be performed and optionally data
which provides content for the action. If an implicit intent is sent to the Android system, it
searches for all components which are registered for the specific action and the fitting data
type. If only one component is found, Android starts this component directly. If several
components are identified by the Android system, the user will get a selection dialog and can
decide which component should be used for the intent.

For example, the following tells the Android system to view a webpage. All installed web
browsers should be registered to the corresponding intent data via an intent filter.

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));

startActivity(i);

2)Explicit Intent:

Explicit intents explicitly define the component which should be called by the Android
system, by using the Java class as identifier. Explicit intents are typically used within an
application as the classes in an application are controlled by the application developer. The
following shows how to create an explicit intent and send it to the Android system to start an
activity.
Intent i = new Intent(this, ActivityTwo.class);
Startactivity(i);
6.4Intent Filter:
Android OS uses filters to pinpoint the set of Activities, Services, and Broadcast receivers
that can handle the Intent with help of specified set of action, categories, data scheme
associated with Intent. You will use <intent-filter> element in the manifest file to list down
actions, categories and data types associated with any activity, service, or broadcast
receiver.
Following is an example of a part of AndroidManifest.xml file to specify an
activity com.example.MyApplication.CustomActivity which can be invoked by either of the
two mentioned actions, one category, and one data −
<activity android:name=".CustomActivity"
android:label="@string/app_name">

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.example.MyApplication.LAUNCH" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>

6.1, 6.2, 6.3 & 6.4 Check Your Progress:


1. Android _______ is the subclass of ContextThemeWrapper class.
2. _______ Called when the activity is first created.
3. _______ Called when the system is about to start resuming a previous activity.
4. _______ intents specify the action which should be performed and optionally data which
provides content for the action.
5. _______ intents explicitly define the component which should be called by the Android
system, by using the Java class as identifier.

6.5Fragment:
A Fragment represents a behavior or a portion of user interface in an Activity. You can
combine multiple fragments in a single activity to build a multi-pane UI and reuse a
fragment in multiple activities. You can think of a fragment as a modular section of an
activity, which has its own lifecycle, receives its own input events, and which you can add or
remove while the activity is running

How to use Fragments?


This involves number of simple steps to create Fragments.
 First of all decide how many fragments you want to use in an activity. For example
let's we want to use two fragments to handle landscape and portrait modes of the
device.
 Next based on number of fragments, create classes which will extend
the Fragment class. The Fragment class has above mentioned callback functions.
You can override any of the functions based on your requirements.
 Corresponding to each fragment, you will need to create layout files in XML file.
These files will have layout for the defined fragments.
 Finally modify activity file to define the actual logic of replacing fragments based on
your requirement.

6.6Fragment Life Cycle:


Below are the methods of fragment lifecycle.

1. onAttach() :This method will be called first, even before onCreate(), letting us know
that your fragment has been attached to an activity. You are passed the Activity that
will host your fragment

2. onCreateView() : The system calls this callback when it’s time for the fragment to
draw its UI for the first time. To draw a UI for the fragment, a View component must
be returned from this method which is the root of the fragment’s layout. We can
return null if the fragment does not provide a UI

3. onViewCreated() : This will be called after onCreateView(). This is particularly useful


when inheriting the onCreateView() implementation but we need to configure the
resulting views, such as with a ListFragment and when to set up an adapter

4. onActivityCreated() :This will be called after onCreate() and onCreateView(), to


indicate that the activity’s onCreate() has completed. If there is something that’s
needed to be initialised in the fragment that depends upon the activity’s onCreate()
having completed its work then onActivityCreated() can be used for that initialisation
work

5. onStart() : The onStart() method is called once the fragment gets visible

6. onPause() : The system calls this method as the first indication that the user is leaving
the fragment. This is usually where you should commit any changes that should be
persisted beyond the current user session

7. onStop() : Fragment going to be stopped by calling onStop()

8. onDestroyView() : It’s called before onDestroy(). This is the counterpart to


onCreateView() where we set up the UI. If there are things that are needed to be
cleaned up specific to the UI, then that logic can be put up in onDestroyView()

9. onDestroy() : onDestroy() called to do final clean up of the fragment’s state but Not
guaranteed to be called by the Android platform.

10. onDetach() : It’s called after onDestroy(), to notify that the fragment has been
disassociated from its hosting activity

6.5 & 6.6 Check Your Progress:


1. A _______ represents a behavior or a portion of user interface in an Activity.
2. You can combine multiple fragments in a single activity to build a _______ UI and reuse a
fragment in multiple activities.

6.7Summary:
Android activity is the subclass of ontextThemeWrapper class. Intents allow you to interact with
components from the same applications as well as with components contributed by other
applications. You can combine multiple fragments in a single activity to build a multi-pane UI and
reuse a fragment in multiple activities.

6.8Check Your Progress answers:

6.1, 6.2, 6.3 & 6.4 Check Your Progress:


1. activity
2. onCreate
3. onPause
4. Implicit
5. Explicit

6.5 & 6.6 Check Your Progress:


1. Fragment
2. multi-pane

6.9QUESTIONS FOR SELF-STUDY


1. What is Intent? Different types of Intent
2. Explain Lifecycle of Fragment
3. Explain Activity Lifecyle?
Chapter VII
Database and Content Providers

7.0 Objective
7.1 Introducing Android Databases
7.2 Introducing SQLite
7.3 SQLiteOpenHelper and creating a database, Opening and closing a database, Working
with cursors Inserts, updates, and deletes,
7.4 Creating new content Provider, Using Content providers, Native Android Content
provider.
7.5 Summary
7.6 Check Your Progress answers

7.0 Objective:
After studying this chapter you will be able to understand
 Different types of database used in android programming
 How to use SQLlite Database in android.
 Create, modify & delete and data in SQLlite database.
 Creating and using content provider.

7.1Introducing Android Databases


Every mobile applications need data to work, and databases have for quite a while been the
most common way of storing and managing data. There are two way to access the
database; 1) Access from cloud or 2) Embedded database, which is stored on mobile device.
Embeddeddatabase allow your application to be fully functional even when no network
connection is available and to sync with the remote database periodically or when going
back on-line. Embeddable databases are lightweight, self-contained libraries with no server
component, no need for administration, a small code footprint, and limited resource
requirements. There are several embeddable databases out there which can be used for
mobile application, some them are listed below;

Database Type of data stored License Supported platforms


BerkeleyDB relational, objects, key-value AGPL 3.0 Android, iOS
pairs, documents
CouchbaseLite documents Apache Android, iOS
2.0
LevelDB key-value pairs New BSD Android, iOS
SQLite relational Public Android, iOS, Windows
Domain Phone, Blackberry
UnQLite key-value pairs, documents BSD 2- Android, iOS, Windows
Clause Phone

7.2Introduction to Sqlite:
SQLite is an opensource SQL database that stores data to a text file on a device. Android
comes in with built in SQLite database implementation.SQLite supports all the relational
database features.
7.3Database - Helper class
For managing all the operations related to the database, an helper class has been given and
is called SQLiteOpenHelper. It automatically manages the creation and update of the
database. Its syntax is given below

public class DBHelper extends SQLiteOpenHelper {

publicDBHelper(){

super(context,DATABASE_NAME,null,1);

public void onCreate(SQLiteDatabasedb) {}

public void onUpgrade(SQLiteDatabase database, intoldVersion, intnewVersion) {}


}

getReadableDatabase:

SQLiteDatabasegetReadableDatabase ()
Create and/or open a database. This will be the same object returned
by getWritableDatabase() unless some problem, such as a full disk, requires the database to
be opened read-only. In that case, a read-only database object will be returned. If the
problem is fixed, a future call to getWritableDatabase() may succeed, in which case the
read-only database object will be closed and the read/write object will be returned in the
future.

getWritableDatabase:
SQLiteDatabasegetWritableDatabase ()

Create and/or open a database that will be used for reading and writing. The first time this is
called, the database will be opened and onCreate(SQLiteDatabase),
onUpgrade(SQLiteDatabase, int, int) and/or onOpen(SQLiteDatabase) will be called.
Once opened successfully, the database is cached, so you can call this method every time
you need to write to the database. (Make sure to call close()when you no longer need the
database.) Errors such as bad permissions or a full disk may cause this method to fail, but
future attempts may succeed if the problem is fixed.
7.1, 7.2 & 7.3 Check Your Progress:
1. ________is aopensource SQL database that stores data to a text file on a device.
2. For managing all the operations related to the database , an helper class has been given and
is called ________

7.4Cursor :
Query in android will return as a “Cursor” objects. Cursors are pointers to the result set
within the underlying data.
Following are some of functions in “Cursor” class, which helps navigation within result set.
 moveToFirst Moves the cursor to the first row in the query result
 moveToNext Moves the cursor to the next row
 moveToPrevious Moves the cursor to the previous row
 getCount Returns the number of rows in the result set
 getColumnName Returns the name of the specified column index
 getColumnNames Returns a string array of all the column names in the current
Cursor
 moveToPosition Moves the Cursor to the specified row
 getPosition Returns the current Cursor position

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

SQLiteDatabasemydatabase = openOrCreateDatabase("your database


name",MODE_PRIVATE,null);

e.g.
private static final String DATABASE_NAME = “myTestDatabase.db”;
private static final String DATABASE_TABLE = “mainTestTable”;
private static final String DATABASE_CREATE =
“create table ” + DATABASE_TABLE + ” ( _id integer primary key autoincrement,” +
“column_one text not null)”;
SQLiteDatabasemyDatabase;
private void createDatabase() {
myDatabase = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
myDatabase.execSQL(DATABASE_CREATE);
}

Database - Insertion
we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class. Its syntax is given below

mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username


VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");

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

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


resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);

Database – Deleting
we can delete data into table using execSQL method defined in SQLiteDatabase class. Its
syntax is given below
Synatx:
delete from mytable where id = 10

7.5Content Provider:

Store and retrieve data and make it available to all applications


– Only way to share data across applications
• Standard content providers part of Android:
– Common data types (audio, video, images, personal contact information)
• Applications can create their own content providers to make their data public
– Alternatively add the data to an exis4ng provider
• Implement a common interface for querying the provider, adding, altering and dele4ng
data
• Actual storage of data is up to the designer
• Provides a clean separation between the application layer and data layer

Accessing Content
• Applications access the content through a ContentResolver instance
– ContentResolver allows querying, inserting, deleting and updating data from the content
provider
ContentResolvercr = getContentResolver();
cr.query(People.CONTENT_URI, null, null, null, null); //querying contacts
ContentValuesnewvalues = new ContentValues();
cr.insert(People.CONTENT_URI, newvalues);
cr.delete(People.CONTENT_URI, null, null); //delete all contacts
• Content providers expose their data as a simple table on a database model
– Each row is a record and each column is data of a particular type and meaning
• Queries return cursor objects
• Each content provider exposes a public URI that uniquely identifies its data set
– Separate URI for each data set under the control of the provider
– URIs start with content://… – Typical format: Content://.provider./

Creating Content Providers


• To create a content provider, you must:
– Set up a system for storing the data. Most content providers store their data using
Android's file storage methods or SQLite databases, but you can store your data any way
you want.
– Extend the ContentProvider class to provide access to your data
– Declare the content provider in the manifest file for your applica4on
(AndroidManifest.xml)
• Extending the ContentProvider class will require:
– Implementing the following methods: query(), insert(), update(), delete(), getType(),
onCreate()
– Make sure that these implementations are thread-safe as they may be called from several
ContentResolver objects in several different processes and threads
• In addition, you need to:
– Declare a public static final URI named CONTENT_URI
– Define the column names that the content provider will return to clients
– Carefully document the data type of each column
• You need to declare the content provider in the Manifest file:
Example:
<providerandroid:name="com.example.tmv"
android:authorities="com. example.tmv ">
</provider>

7.4 & 7.5 Check Your Progress:


1. ________ are pointers to the result set within the underlying data.
2. ________()is used for Create and/or open a database that will be used for reading and
writing.

7.6Summary
There are two way to access the database; 1) Access from cloud or 2) Embedded database,
which is stored on mobile device. Embedded database allow your application to be fully
functional even when no network connection is available and to sync with the remote
database periodically or when going back on-line. For managing all the operations related to
the database, an helper class has been given and is called SQLiteOpenHelper. Cursors are
pointers to the result set within the underlying data.

7.7Check Your Progress answers:


7.1, 7.2 & 7.3 Check Your Progress:
1. SQLite
2. SQLiteOpenHelper

7.4 & 7.5 Check Your Progress:


1. Cursors
2. getWritableDatabase

7.8QUESTIONS FOR SELF-STUDY


1. What is Intent? Different types of Intent
2. Explain Lifecycle of Fragment
3. Explain Activity Lifecyle?
Questions Banks:
1. Explain external Style Sheet? How would you link to it?
2. What are the advantages and disadvantages of Embedded Style Sheets?
3. How embedded style can be linked with HTML documents?
2. Difference between canvas and SVG.
3. Explain HTML5 web storage?
4. What are the most commonly used List tags?
5. What are Advantages of CSS?
6. What is Android?
7. What Is the Google Android SDK?
8. What is the importance of having an emulator within the Android environment?
9. Describe Activities.
10. Describe Service.
11. Differentiate Activities from Services.
12. What items are important in every Android project?
13. Explain Activity Lifecycle?
14. What is Fragment?Advantages of Fragment
15. Explain Lifecycle of Fragment
16. Difference between Activity and Fragment
17. What are different types of layout?
18. Explain AVD,Android Device monitor and ADB
19. What is Intent?Different types of Intent
20. What is BroadcastReceiver? Explain with Example
21. Explain Object Oriented Programming Concept?
22. What is difference between Abstract class and polymorphism?
23. What is polymorphism? What are different types?
24. What is SQLite Database?
25. Explain Different types of Android Version with its features?
26. How to perform the operation of insertion,deletion and update in SQLite?
27. What is Content Provider?
28. What do you think are some disadvantages of Android?
29. When is the onStop() method invoked in Activity?
30. What is the AndroidManifest.xml?
31. What are different methods which get called when any call comes on the current activity?
32. Is it possible to use or add a fragment without using a user interface?
33. What are the different storage methods in Android?
34. What is DDMS and what can it do?
35. How to install application on Phone?

You might also like