Android Ebook
Android Ebook
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:
Internet YES NO NO
Explorer
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:
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.
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>
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
<p>
<label for="email">email:</label>
<input type="text" id="email"><br>
</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.
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.
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...
}
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.
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.
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();
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:
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:
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
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
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.
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
CSS text-transformation
CSS text-transformation property use to text transform.
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
Output:
This text is Predefined Area
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.
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.
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.
Colour properties:
Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA values.
CSS Syntax
color: color|initial|inherit;
Property Values
Color Specifies the text color. Look at CSS Color Values for a complete list of possible Play it
color values. »
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;
}
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.
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. The hardware that supports android software is based on _______ architecture platform.
Platform-tools
Build-tools
SDK-tools
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.
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
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.
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
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.
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.
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:
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:
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:
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
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.
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.
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.
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.
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.
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
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.
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.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
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.
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");}
Output:
Hello
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
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.
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.
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>
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:
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.
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
1. Linear
2. TableLayout
3. RelativeLayout
4. FrameLayout
5. style
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.
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.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
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
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
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.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.
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.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
publicDBHelper(){
super(context,DATABASE_NAME,null,1);
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
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
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.
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:
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./
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.