Mobile Application and Web Programming Module
Mobile Application and Web Programming Module
Prepared By:
Reviewed by:
ii
Contents
PHASE I: ..................................................................................................................................................... 1
INTERNET PROGRAMMING- I and II ................................................................................................. 1
Chapter 1 ....................................................................................................................................................... 2
Internet Technologies and Protocols ............................................................................................................. 2
1.1 What is Internet? ................................................................................................................................. 2
Web development tools............................................................................................................................. 4
1.2 Client-server architecture .................................................................................................................... 5
1.3 How the Web works? .......................................................................................................................... 5
1.4 Web Protocols ..................................................................................................................................... 6
1.5. Static and dynamic web pages ........................................................................................................... 7
What are Static Web Pages? ..................................................................................................................... 8
What are Dynamic Web Pages? ................................................................................................................ 8
1.6 Review Questions ............................................................................................................................... 9
Chapter 2 ....................................................................................................................................................... 11
HTML (Hyper Text Markup Language) ..................................................................................................... 11
2.1 What is Markup language? ...................................................................................................................... 11
2.2 HTML Links ....................................................................................................................................... 15
2.3 HTML image ....................................................................................................................................... 15
2.4 HTML Lists ........................................................................................................................................ 16
2.5 HTML Comments................................................................................................................................ 16
2.6 HTML Frames ..................................................................................................................................... 18
2.7 HTML Tables ...................................................................................................................................... 19
2.8 HTML Buttons ................................................................................................................................... 22
2.9 HTML Forms ....................................................................................................................................... 23
2.10 HTML Form Controls .......................................................................................................................... 24
2.11 REVIEW QUESTIONS ...................................................................................................................... 32
Chapter 3 ..................................................................................................................................................... 35
Styling HTML with CSS ............................................................................................................................ 35
What is CSS? ............................................................................................................................................ 35
Why Use CSS?........................................................................................................................................... 35
Inline Styles .............................................................................................................................................. 39
iii
Internal Style Sheet .................................................................................................................................... 39
External Style Sheet ................................................................................................................................... 40
Review Questions ...................................................................................................................................... 41
Chapter 4 ..................................................................................................................................................... 43
JavaScript .................................................................................................................................................... 43
4.1 Features of JavaScript ............................................................................................................................ 43
4.2 JavaScript Rules ................................................................................................................................... 43
4.3 JavaScript variables .............................................................................................................................. 45
4.4 Functions in JavaScript ............................................................................................................................ 47
4.5 Objects in JavaScript ............................................................................................................................ 48
4.6 Cookies in JavaScript ............................................................................................................................ 48
4.7 What is the DOM? ............................................................................................................................... 50
JavaScript HTML DOM Elements ............................................................................................................... 52
4.8 Review Questions ................................................................................................................................ 53
Chapter 5 ........................................................................................................................................................ 54
Server-side programming .................................................................................................................................... 54
5.1 Introduction to server-side scripting .................................................................................................... 54
5.2 What is PHP? ...................................................................................................................................... 55
5.3 Comments in PHP ...................................................................................................................................... 58
5.4 Variables in PHP.............................................................................................................................. 59
5.5 PHP Variables Scope ............................................................................................................................. 60
5.6 Manipulate Strings ................................................................................................................................ 62
5.7 Operators in PHP ........................................................................................................................ 64
5.8 What are constants? ............................................................................................................................... 67
5.9 Array in PHP ................................................................................................................................... 68
5.10 PHP Database connectivity .......................................................................................................... 70
5.11 JSP and Servlets .............................................................................................................................. 72
What is Java Servlet? .............................................................................................................................. 72
What is Java Server page? ...................................................................................................................... 72
5.12 Review Questions ............................................................................................................................... 74
PHASE II: .................................................................................................................................................. 76
MOBILE APPLICATION ....................................................................................................................... 76
iv
CHAPTER ONE ......................................................................................................................................... 77
INTRODUCTION ANDROID ................................................................................................................... 77
1.0 The Android Platform ....................................................................................................................... 77
1.2 Native Android Applications ............................................................................................................ 79
1.3 Android Sdk Features........................................................................................................................ 80
1.5 Factors that affect Mobile Application development ........................................................................ 84
Chapter Two................................................................................................................................................ 87
Android Software Development Android Studio for .................................................................................. 87
CHAPTER THREE .................................................................................................................................. 103
ANDROID - APPLICATION COMPONENTS ....................................................................................... 103
CHAPTER FOUR:.................................................................................................................................... 114
ANDROID INTENTS .............................................................................................................................. 114
CHAPTER FIVE: ..................................................................................................................................... 119
ANDROID GUI ........................................................................................................................................ 119
v
Specific objectives / learning outcomes
vi
PHASE I:
INTERNET PROGRAMMING- I
and II
1
Chapter 1
Internet Technologies and Protocols
1.1 What is Internet?
It is a world-wide global system of interconnected computer networks. A computer
network is the interconnection of many individual computers to exchange message.
Network is a group of two or more computer connected together.
It uses the standard Internet Protocol TCP/IP. Every computer in internet is identified by
a unique IP address. IP Address is a unique set of numbers which identifies a computer
location. Domain Name server (DNS) is used to give name to the IP Address so that user
can locate a computer by a name.
o For example, a DNS server will resolve a name http://www.google.com to a
particular IP address to uniquely identify the computer on which this website is
hosted.
Internet is accessible to every user all over the world. So, Internet is a network of networks.
2
It allows a user to move from one web page to another by using a mouse to click
on special hypertext links. For example, a user viewing web pages that describe
airplanes might encounter a link to jet engines from one of those pages. By
clicking on that link, the user automatically jumps to a page that describes jet
engines.
d. Webpage
Webpage is a single document that may contain text, graphics, and icon.
They are created using HTML.
e. Web site
It is a group of well-structured and interlinked webpages.
f. Uniform Resource Locator (URL)
To visit a Web site, users type the URL, which is the site's address, into the web
browser. An example of a URL is www.yahoo.com.
A complete URL is generally made up of three components: the protocol, the site
name, and the absolute path to the document or resource as shown in the figure
below:
g. Web server
A web server is a computer that stores a web site, and is responsible for checking
requests for viewing that web site.
Client computers send requests for particular URLs to the web server, which then
finds the appropriate web page, and sends it back to the client computer.
A web server on the Internet must have a permanent Internet connection, so that
whenever a client computer requests a URL, the web server can respond straight
away.
3
h. Internet Service Provider (ISP)
A company that provides Internet connections to customers.
i. Protocol
It is a set of rules that govern the communication.
j. Hypertext Transfer Protocol (HTTP/HTTPS)
It is a communications protocol.
It defines mechanism for communication between browser and the web server. It
is also called request and response protocol because the communication between
browser and server takes place in request and response pairs. Simply, it is the
means by which computers on the WWW communicate.
HTTPS is the secure version of HTTP. It is used on web sites where sensitive
information such as bank details is exchanged.
k. Hypertext Markup Language (HTML)
It is the language used to write web pages on the WWW.
l. Extensible Markup Language (XML)
It is an alternative language for writing web pages. Whereas HTML pages
describe the format of the data’s presentation, pages written in XML describe
only how the data is structured
XML provides a standard format for the movement of data in and between
applications.
The data in an XML file usually requires some other application to interpret the
data and display it in a useful format.
m. World Wide Web Consortium (W3C)
It is a group of experts who meet regularly to develop common protocols for the
evolution of the WWW.
The W3C agrees on standards for HTML, XML and other web technologies, and
for how web browsers should interpret them.
4
HTML/XML: HTML and XML are the two main languages used for writing web pages.
Web authors can use a simple text editor such as Notepad to enter the HTML/XML
commands. The final page can then be viewed using a web browser.
5
The Web server locates the request page either on its hard drive or cached in memory.
The Web server sends its contents back to the requested browser.
Web protocols are standardized rules and conventions that govern how data is transmitted,
received, and displayed over the internet. These protocols ensure seamless communication
between devices, servers, and applications. There are different types of web protocols. Such as:
6
Commonly used for applications like web browsing and file transfer..
7
webpages create content instantly in response to user input and present customized or updated
information.
8
1.6 Review Questions
Choose the best answer for the following questions
1. What is the correct syntax of web address?
A. port://domain.filenmae:path/scheme/prefix
B. prefix://scheme.port:domain/filename/path
C. path://prefix.port:domain/filename/scheme
D. scheme://prefix.domain:port/path/filename
2. Which protocol is commonly used for secure communication over the web?
A. HTTP B. FTP C. SMTP D. HTTPS
3. Which protocol is primarily used for transferring emails between servers?
A. HTTP B. SMTP C. FTP D. IMAP
4. Which of the following is used to read an HTML page and render it?
A. Web server C. Web network
B. Web browser D. Web matrix
5. Which protocol is used to resolve domain names to IP addresses?
A. FTP B. DHCP C. DNS D. SNMP
6. Which protocol is used for secure data transmission over the internet?
A. HTTP B. FTP C. HTTPS D. SNMP
9
7. What is the main function of the DHCP protocol?
A. To translate domain names into IP addresses
B. To assign dynamic IP addresses to devices
C. To monitor network devices
D. To establish a virtual private network
8. Which protocol is used to securely log into a remote computer?
A. Telnet B. FTP C. SSH D. SNMP
9. What is the port number for HTTPS?
A. 443 B. 80 C. 25, D 40
10. What does the 404 error code indicate in HTTP?
A. Unauthorized access C. Forbidden access
B. Page not found D Internal server error
10
Chapter 2
HTML (Hyper Text Markup Language)
2.1 What is Markup language?
A markup language is a programming language that is used to make text more
interactive and dynamic. It can turn a text into images, tables, links etc.
What is Hyper Text Markup Language (HTML)?
It is the standard markup language for creating Web pages.
It is a language for describing web pages.
HTML documents contain HTML tags and plain text
HTML documents are also called web pages
It consists of a series of elements
HTML elements tell the browser how to display the content
HTML elements are represented by tags
HTML tags label pieces of content such as heading, paragraph, table, and so on
Browsers do not display the HTML tags, but use them to render the content of the
page
What is HTML Tag?
HTML tags are element names surrounded by angle brackets:
11
The structure of an HTML element
12
<head> <title>Heading Example</title> </head>
<body>
<h1>this is heading 1</h1>
<h2>this is heading 2</h2>
<h3>this is heading 3</h3>
<h4>this is heading 4</h4>
<h5>this is heading 5</h5>
<h6>this is heading 6</h6>
</body>
</html>
Paragraph Tag
The <p> tag offers a way to structure your text into different paragraphs. Each paragraph of
text should go in between an opening <p> and a closing </p> tag as shown below in the
example:
<!DOCTYPE html>
<html>
<head> <title>Paragraph Example</title> </head>
<body>
<p>Here is a first paragraph of text.</p>
<p>Here is a second paragraph of text.</p>
<p>Here is a third paragraph of text.</p>
</body>
</html>
Line Break Tag
Whenever you use the <br /> element, anything following it starts from the next line.
This tag is an example of an empty element, where you do not need opening and closing
tags, as there is nothing to go in between them. The <br /> tag has a space between the
characters br and the forward slash. If you omit this space, older browsers will have
trouble rendering the line break.
Example <!DOCTYPE html>
13
<html>
<head> <title>Line Break Example</title> </head>
<body>
<p>Hello<br />
You delivered your assignment
on time. <br /> Thanks<br />
Mahnaz</p>
</body>
</html>
Centering Content
You can use <center> tag to put any content in the center of the page or any table cell.
<!DOCTYPE html>
<html>
<head>
<title>Centring Content Example</title> </head>
<body> <p>This text is not in the center.</p>
<center> <p>This text is in the center.</p> </center>
</body>
</html>
Horizontal Lines
Horizontal lines are used to visually break-up sections of a document.
The <hr> tag creates a line from the current position in the document to the right marginand
breaks the line accordingly. For example, you may want to give a line between two
paragraphs as in the given example below:
<!DOCTYPE html>
<html>
<head> <title>Horizontal Line Example</title> </head>
<body>
<p>This is paragraph one and should be on top</p>
<hr />
14
<p>This is paragraph two and should be at bottom</p>
</body></html>
Again <hr /> tag is an example of the empty element, where you do not need opening and
closing tags, as there is nothing to go in between them. The <hr /> element has a space
between the characters hr and the forward slash. If you omit this space, older browsers
will have trouble rendering the horizontal line.
Nonbreaking Spaces
In cases, where you do not want the client browser to break text, you should use a
nonbreaking space entity instead of a normal space.
For example, when coding the "12 Angry Men" in a paragraph, you should use something
similar to the following code:
<!DOCTYPE html>
<html>
<head> <title>Nonbreaking Spaces Example</title> </head>
<body>
<p>An example of this technique appears in the movie
"12 Angry Men."</p>
</body>
</html>
2.2 HTML Links
HTML links are defined with the <a> tag: <a href="url">link text</a>. The link's
destination is specified in the href attribute. Attributes are used to provide additional
information about HTML elements.
Example: -<a href="https://www.w3schools.com/html/">Visit our HTML tutorial</a>
2.3 HTML image
HTML images are defined with the <img> tag.
The source file (src), alternative text (alt), width, and height are provided as attributes.
15
2.4 HTML Lists
In HTML, lists are used to group related items together. HTML provides three main types
of lists: ordered lists, unordered lists, and definition lists.:
HTML Lists are defined with the <ul> (unordered/bulletlist) or the <ol> (ordered/numbered
list) tag, followed by <li> tags (list items):
o An unordered list uses bullet points to display items. It is created using the <ul>
tag.
o An ordered list uses numbers or letters to display items in a sequence. It is created
using the <ol> tag.
o A definition list is used to display terms and their descriptions. It is created using
the <dl> tag, with <dt> for the term and <dd> for its description.
</html>
2. Multiline Comments
So far we have seen single line comments, but HTML supports multi-line comments as
16
well. You can comment multiple lines by the special beginning tag <!-- and ending tag --
> placed before the first line and end of the last line as shown in the given example
below. Example
<!DOCTYPE html>
<html>
<head> <title>Multiline Comments</title> </head>
<body>
<!--
This is a multiline comment and
it can span through as many as
lines you like.
-->
<p>Document content goes here </p>
</body> </html>
3. Conditional Comments
Conditional comments only work in Internet Explorer (IE) on Windows but they are
ignored by other browsers. They are supported from Explorer 5 onwards, and you can use
them to give conditional instructions to different versions of IE. Example
<!DOCTYPE html>
<html>
<head> <title>Conditional Comments</title>
<!--[if IE 6]>
Special instructions for IE 6 here
<![endif]-->
</head>
<body>
<p>Document content goes here ............... </p>
</body>
</html>
17
2.6 HTML Frames
HTML frames are used to divide your browser window into multiple sections where each
section can load a separate HTML document. A collection of frames in the browser window
is known as a frameset. The window is divided into frames in a similar way the tables are
organized: into rows and columns.
Disadvantages of Frames
a. There are few drawbacks with using frames, so it's never recommended to use
frames ni your webpages. Some smaller devices cannot cope with frames often
because their screen is not big enough to be divided up. Sometimes your page will
be displayed differently on different computers due to different screen resolution.
b. The browser's back button might not work as the user hopes. There are still few
browsers that do not support frame technology.
Creating Frames
To use frames on a page we use <frameset> tag instead of <body> tag.
The <frameset> tag defines how to divide the window into frames.
The rows attribute of <frameset> tag defines horizontal frames and cols attribute defines
vertical frames.
Each frame is indicated by <frame> tag and it defines which HTML document shall open
into the frame.
Following is the example to create three horizontal frames:
<!DOCTYPE html>
<html>
<head> <title>HTML Frames</title> </head>
<frameset rows = "10%,80%,10%">
<frame name = "top" src = "/html/top_frame.htm" />
<frame name = "main" src = "/html/main_frame.htm" />
<frame name = "bottom" src = "/html/bottom_frame.htm" />
<noframes>
<body>Your browser does not support frames.</body>
18
</noframes>
</frameset>
</html>
Let's put the above example as follows, here we replaced rows attribute by cols and
changed their width. This will create all the three frames vertically:
<!DOCTYPE html>
<html>
<head> <title>HTML Frames</title> </head>
<frameset cols = "25%, 50%, 25 %">
<frame name = "left" src = "/html/top_frame.htm" />
<frame name = "center" src = "/html/main_frame.htm" />
<frame name = "right" src = "/html/bottom_frame.htm" />
<noframes>
<body>Your browser does not support frames.</body>
</noframes>
</frameset>
</html>
2.7 HTML Tables
HTML Tables is used to preset data in rows and columns format. A Table is the
collection of rows and rows is the collection of columns. <tr> stands for table rows.
To add a row in a table <table row> tags are used. <td> or <th> is used to put the
column inside the row. Whereas <td> means table data and <th> means table head.
Syntax: <table>
<tr>
<td>row1col1</td>
<td>row1col2</td>
</tr>
</table>
19
Example
<table border="1">
<tr>
<th>Name</th>
<th>Email</th></tr>
<tr>
<td>phptpoint</td>
<td>phptpoint@gmail.com</td>
</tr>
<tr>
<td>phptpoint blog</td>
<td>blog@gmail.com</td>
</tr>
</table>
In the above example a table is created have 3 rows and 6 columns where each row
c o n t a i n s 2 column. <tr> tag is used to create a row while <td> or <th> is used to
create column. <tr> comes in between <table> tag while <td> or <th> comes in between
<tr>.
How to merge table column
When you want to merge 2 or more than 2 column (cell), use colspan property of <td
colspan="2″> or <th colspan=”2″>.
Example
<table border="1">
<tr>
<th colspan="2"> User Details</th>
</tr>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
20
<tr>
<td>phptpoint</td>
<td>phptpoint@gmail.com</td>
</tr>
<tr>
<td>phptpoint blog</td>
<td>blog@gmail.com</td>
</tr> </table>
How to merge table rows
when you want to merge 2 or more than 2 rows in a single row, use rowspan property of
<td rowspan=”2″> or <th rowspan=”2″>
Example
<table border="1">
<tr>
<td rowspan="2"> </td>
<td> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>
Nested Table
Nested table means how to use table inside a table. Multiple times you need to use tableinside
a table. When you want to use a table inside a table write the syntax of table in between
your cell i.e either <td> or <th>.
Example<html>
<body>
<table border="1" bgcolor="gray" width="200" height="200">
<tr>
<th>
21
<table align="center" border="1" bgcolor="#F8F8F8" width="
100" height="100">
<tr>
<th>Inner Table</th>
</tr>
</table>
</th>
</tr>
</table>
</body>
</html>
Definition and Usage
The <table> tag defines an HTML table. An HTML table consists of the <table> element and
one or more <tr>, <th>, and <td> elements.
The <tr> element defines a table row, the <th> element defines a table header, and the
<td> element defines a table cell. A more complex HTML table may also include
<caption>, <col>, <colgroup>, <thead>, <tfoot>, and <tbody> elements.
22
2.9 HTML Forms
HTML Forms are required, when you want to collect some data from the site visitor.
o For example, during user registration you would like to collect information such as
name,email address, credit card, etc.
A form will take input from the site visitor and then will post it to a back-end application such
as CGI, ASP Script or PHP script etc.
The back-end application will perform required processing on the passed data
based on defined business logic inside the application.There are various form
elements available like text fields, text-area fields, drop-down menus, radio
buttons, checkboxes, etc.
The HTML <form> tag is used to create an HTML form and it has following
syntax:
Form Attributes
Apart from common attributes, following is a list of the most frequently
used formattributes
S.No Attribute Description
1 Action Backend script ready to process your passed data.
2 Method Method to be used to upload data. The most frequently used are
GET and POST methods.
3 Target Specify the target window or frame where the result of the script
will be displayed. It takes values like _blank, _self, _parent etc.
23
4 Enctype You can use the enctype attribute to specify how the browser encodes
the data before it sends it to the server. Possible values are:
application/x-www-form-urlencoded − This is the standard
method most forms use in simple scenarios.
mutlipart/form-data − This is used when you want ot
upload binary data in the form of files like image, word file etc.
A. Single-line text input controls: is used for items that require only one line of user
input, such as search boxes or names. They are created using HTML <input> tag. Here
is a basic example of a single-line text input used to take first name and last name
<!DOCTYPE html>
<html>
<head> <title>Text Input Control</title> </head>
<body>
<form >
First name: <input type = "text" name = "first_name" />
<br> Last name:
<input type = "text" name = "last_name" /
</form>
</body>
</html>
24
Attributes: -Following is the list of attributes for <input> tag for creating text field.
S.No Attribute Description
1 Type Indicates the type of input control and for text input control it will
be set to text.
2 Name Used to give a name to the control which is sent to the server to be
recognized and get the value.
3 Value This can be used to provide an initial value inside the control.
4 Size Allows specifying the width of the text-input control in terms of
characters.
5 maxlength Allows specifying the maximum number of characters a user can
enter into the text box.
B. Password input controls: This is also a single-line text input but it masks the character
as soon as a user enters it. They are also created using HTML <input> tag. Here is a
basic example of a single-line password input used to take user password:
<!DOCTYPE html>
<html>
<head> <title>Password Input Control</title> </head>
<body>
<form >
User ID : <input type = "text" name = "user_id" /> <br> Password:
<input type = "password" name = "password"
/></form>
</body>
</html>
25
Attributes: -Following is the list of attributes for <input> tag for creating password
field.
S.No Attribute Description
1 Type Indicates the type of input control and for password input
control it will be set to password.
2 Name Used to give a name to the control which is sent to the server
to be recognized and get the value.
3 Value This can be used to provide an initial value inside the
control.
4 Size Allows specifying the width of the text-input control in terms
of characters.
5 maxlength Allows specifying the maximum number of characters a user
can enter into the text box.
C. Multi-line text input controls: This is used when the user is required to give details
that may be longer than a single sentence. They are created using HTML <textarea>
tag. Here is a basic example of a multi-line text input used to take item description:
<!DOCTYPE html>
<html>
<head> <title>Multiple-Line Input Control</title> </head>
<body>
<form>
Description : <br />
<textarea rows = "5" cols = "50" name = "description">
Enter description here...
</textarea>
</form>
</body></html>
26
Attributes: -Following is the list of attributes for <textarea> tag.
S.No Attribute Description
1 Name Used to give a name to the control which is sent to the server
to be recognized and get the value.
2 Rows Indicates the number of rows of text area box.
3 Cols Indicates the number of columns of text area box
2. Checkbox Control
Checkboxes are used when more than one option is required to be selected. They
are also created using HTML <input> tag but type attribute is set to checkbox.Here
is an example HTML code for a form with two checkboxes:
<!DOCTYPE html>
<html>
<head> <title>Checkbox Control</title> </head>
<body>
<form>
<input type = "checkbox" name = "maths" value = "on"> Maths
<input type = "checkbox" name = "physics" value = "on"> Physics
</form>
</body>
</html>
27
3. Radio Button Control
Radio buttons are used when out of many options; just one option is required to be
selected. They are also created using HTML <input> tag but type attribute is set to
radio. Here is example HTML code for a form with two radio buttons
<!DOCTYPE html>
<html>
<head> <title>Radio Box Control</title> </head>
<body>
<form>
<input type = "radio" name = "subject" value = "maths"> Maths
<input type = "radio" name = "subject" value = "physics"> Physics
</form>
</body>
</html>
Attributes: -Following is the list of attributes for radio button.
S.No Attribute Description
1 Type Indicates the type of input control and for checkbox input
control it will be set to radio.
2 Name Used to give a name to the control which is sent to the server
to be recognized and get the value.
3 Value The value that will be used if the radio box is selected.
4 Checked Set to checked if you want to select it by default.
<!DOCTYPE html>
<html>
28
<head> <title>Select Box Control</title> </head>
<body>
<form>
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
</form>
</body>
</html>
Attributes: -Following is the list of important attributes of <select> tag
S.No Attribute Description
1 Name Used to give a name to the control which is sent to the server
to be recognized and get the value.
2 Size This can be used to present a scrolling list box.
3 Multiple If set to "multiple" then allows a user to select multiple items
from the menu.
Following is the list of important attributes of <option> tag
S.No Attribute Description
1 Value The value that will be used if an option in the select box box
is selected.
2 Selected Specifies that this option should be the initially selected value
when the page loads.
3 Label An alternative way of labeling options
29
<html>
<head><title>File Upload Box</title></head>
<body>
<form>
<input type = "file" name = "file upload" accept = "image/*" />
</form>
</body>
</html>
Attributes: -Following is the list of important attributes of file upload box
S.No Attribute Description
1 Name Used to give a name to the control which is sent to the server
to be recognized and get the value.
2 Accept Specifies the types of files that the server accepts.
6. Button Controls
There are various ways in HTML to create clickable buttons. You can also create a
clickable button using <input>tag by setting its type attribute to button. The type
attribute can take the following values
S.No Attribute Description
1 Submit This creates a button that automatically submits a form.
2 Reset This creates a button that automatically resets form
controls to their initial values.
3 Button This creates a button that is used to trigger a client-side
script when the user clicks that button.
4 Image This creates a clickable button but we can use an image as
background of the button.
Here is example HTML code for a form with three types of buttons
<!DOCTYPE html>
<html>
<head> <title>File Upload Box</title> </head>
30
<body>
<form>
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
<input type = "button" name = "ok" value = "OK" />
<input type = "image" name = "imagebutton" src = "/html/images/logo.png" />
</form>
</body>
</html>
7. Hidden Form Controls
Hidden form controls are used to hide data inside the page which later on can be pused to the
server. This control hides inside the code and does not appear on the actual page. For
example, following hidden form is being used to keep current page number. When a user
will click next page then the value of hidden control will be sent to the web server and there
it will decide which page will be displayed next based on the passed current page. Here is
example HTML code to show the usage of hidden control
<!DOCTYPE html>
<html>
<head> <title>File Upload Box</title> </head>
<body>
<form>
<p>This is page 10</p>
<input type = "hidden" name = "pagename" value = "10" />
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset” value = "Reset" />
</form>
</body>
</html>
31
2.11 REVIEW QUESTIONS
Choose the best answer for the following questions
1. What is the correct syntax of doctype in HTML5?
A. </doctype html> C. <doctype html>
B. <doctype html!> D. <!doctype html>
2. Which of the following statements is true about HTML?a
A. Tags are case sensitive
B. Tags normally come in pairs
C. Tags are usually sounded by double quotation
D. It is platform-dependent.
3. What is the function of the <body> element in HTML?
A. It defines the visible content of the document.
B. It specifies the document's metadata.
C. It contains the document's title.
D. It links external resources to the document.
4. What is the correct HTML for adding a background color?
A. <bg> C. <backgroung>
B. <bgcolor0 = color> D. <body bgcolor=”color”>
5. Which tag is used to define a table row in HTML?
A. <tr> B. <td> C. <table> D. <th>
6. What is the correct HTML element for inserting line break?
A. <bl> B. <br> C. <break> D. < lb>
7. Which HTML element is used to define the metadata of a document, such as its title,
character set, and links to external resources?
A. <title> B. <head> C. <meta> D. <link>
8. What is the use of <hr/> tag in HTML?
A. For making content appearance italics C. To create vertical rule between
sections
B. To create a line break D. To create horizontal line between
sections
32
9. Which tag is used to include an external JavaScript file in an HTML document?
A. <script> B. <link> C. <js> D. <include>
10. What is the purpose of the <title> element in HTML?
A. To specify the content of the webpage.
B. To define the header of the webpage.
C. To set the title displayed in the browser's title bar or tab.
D. To create a hyperlink within the webpage.
11. Which one is used to insert Hyperlink in HTML Page?
A. <a href="https://www.hypeerlink.com/">HTML</a>
B. <a target="https://www. hypeerlink.com/" HTML />
C. <a src="https://www. hypeerlink.com">HTML</a>
D. <a>https://www. hypeerlink.com/</a>
12. What is the purpose of the <link> element in the <head> section of an HTML document?
A. To insert images into the document.
B. To define a relationship between the current document and an external resource.
C. To create hyperlinks within the document.
D. To embed multimedia content.
13. Which tag is used to create an HTML links
A. <link> B. <href> C.. <src>
D. <a>
14. What does the action attribute of a html form specify?
A. The name of the form
B. The script or URL that processes the form data
C. The method used to submit the form
D. The form's target window or frame
15. Which of the following HTML tag is used to create an unordered list?
A. <ol> B. <ul> C. <li> D. <ll>
16. Which tag is used to create a dropdown in HTML Form?
A. <input> B. <select> C. <text> D. <textarea>
17. Where Client-side JavaScript code is embedded within HTML documents?
33
A. A URL that uses the special javascript:code
B. A URL that uses the special javascript:protocol
C. A URL that uses the special javascript:encoding
D. A URL that uses the special javascript:stack
18. Which of the following HTML tag is used to insert an image?
A. <img url=”htmllogo.jpg” /> C. <img alt=”htmllogo.jpg” />
B. <img src=”htmllogo.jpg” /> D. <img link=”htmllogo.jpg” />
19. In HTML, which attribute is used to create a link that opens in a new window tab?
A. src=”_blank” C. alt=”_blank”
B. target=”_self” D. target=”_blank”
34
Chapter 3
Styling HTML with CSS
Cascading Style Sheets (CSS) is used to format the layout of a webpage.
With CSS, you can control the color, font, and the size of text, the spacing between elements, how
elements are positioned and laid out, what background images or background colors are to be used,
different displays for different devices and screen sizes, and much more!
What is CSS?
CSS stands for Cascading Style Sheets
CSS is a language that describes the style of an HTML document.
CSS describes how HTML elements should be displayed.
CSS is used to control the style of a web document in a simple and easy way.
Why Use CSS?
CSS is used to define styles for your web pages, including the design,
layout and variations in display for different devices and screen sizes.
CSS Syntax and Selectors
CSS Syntax
A CSS rule-set consists of a selector and a declaration block:
35
Example
In this example all <p> elements will be center-aligned, with a red text color:
p{
color: red;//declaration
text-align: center;
}
CSS Selectors
CSS selectors are used to "find" (or select) HTML elements based on their element
name, id, class, attribute, and more.
The element Selector
The element selector selects elements based on the element name.
Example
You can select all <p> elements on a page like this (here, all <p> elements
will be center- aligned, with a red text color):
p{
text-align: center;
color: red;
}
The id Selector
The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element should be unique within a page, so the id selector is
used to select one unique element!
To select an element with a specific id, write a hash (#) character, followed by the id
of the element.
Example
The style rule below will be applied to the HTML element with id="para1":
#para1 {
text-align: center;
color: red;
36
}
Note: An id name cannot start with a number
37
}
h2 {
text-align: center;
color: red;
}
p{
text-align: center;
color: red;
}
It will be better to group the selectors, to minimize the code.
38
CSS can be added to HTML in the following ways:
Inline - using the style attribute in HTML elements
Internal - using the <style> element in the <head> section
External - using an external CSS file
The preferred way to add CSS to HTML is to put CSS syntax in separate CSS files.
Inline Styles
An inline style can be used if a unique style is to be applied to one single
occurrence of an element.
To use inline styles, use the style attribute in the relevant tag. The style
attribute can contain any CSS property.
The example below shows how to change the text color and the left margin
of a paragraph:
<p style="color:blue;margin-left:20px;">This is a paragraph.</p>
39
body {background-color:yellow;}
p {color:blue;}
</style>
</head>
External Style Sheet
An external style sheet is ideal when the style is applied to many pages.
External Style Sheets can save a lot of work
External Style Sheets are stored in CSS files
With an external style sheet, you can change the look of an entire Web site
by changing one file.
Each page must link to the style sheet using the <link> tag. The <link> tag
goes inside the <head> section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
Example mystle.css
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
The external style sheet can be written in any text editor. The file must not contain any
HTML code, and must be saved with a .css extension.
Here is what the "styles.css" file looks like:
40
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
Generally,
Review Questions
Choose the best answer for the following questions
1. Which of the following is the correct syntax to link an external style sheet in the HTML file?
A. <link rel=”stylesheet” href=”style.css” />
B. <link rel=”stylesheet” src=”style.css” />
C. <style rel=”stylesheet” src=”style.css” />
D. <style rel=”stylesheet” link=”style.css” />
2. Where in an HTML document is the correct place to refer to an external style sheet (style.css)?
A. At the end of the document C. In the <head> section
B. At the beginning of the document D. In the <body> section
3. Where in an HTML document is the correct place to refer to an external style sheet (style.css)?
A. At the end of the document C. In the <head> section
B. At the beginning of the document D. In the <body> section
4. Which of the following tag is used to embed css in html page?
41
A. <css> C. <!DOCTYPE html>
B. <script> D. <style>
5. Which of the following CSS property is used to make the text bold?
A. text-decoration: bold C. font-weight: bold
B. font-style: bold D. text-align: bold
6. Which of the following CSS property can be used to set the image as a border instead
of the border style?
A. background-image-source C. background-image
B. border-image-source D. border-image
42
Chapter 4
JavaScript
JavaScript is a popular web-page scripting language, and is supported by almost
browser.
It adds interactivity to web technology pages.
JavaScript is usually embedded directly into HTML pages.
43
Variables are declared using the keyword var.
Script does not require main function and exit condition.
Language Format
JavaScript can be implemented using JavaScript statements that are placed within
the
<script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere
within you w
ebpage, but it is normally recommended that you should keep it
within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text
between thesetags as a script.
So, syntax will look as follows:
<script language="javascript" type="text/javascript"> JavaScript code
</script>
The script tag takes two important attributes
1. Language: This attribute specifies what scripting language you are using. Typically,
its value will be JavaScript. Although recent versions of HTML have phased out the
use of this attribute.
2. Type: This attribute is what is now recommended to indicate the scripting language in
use and its value should be set to "text/javascript".
Take a look at the following code.
<html>
<body>
<script language="javascript" type="text/javascript">
document.write ("Hello World!")
</script>
</body>
</html>
This code will produce the following result: Hello World!
44
Description:
o The <script type="text/javascript"> tag tells the browser that whatever comes between
that tag and the coming </script> tag is script.
o The type="text/javascript" tells it that it is JavaScript.
o The document.write() is the JavaScript standard for writing text to the browser window.
o The 'document' clause refers to the HTML webpage (termed a document) as a whole;
what follows ('.write()') is a command for the document object to carry out.
4.3 JavaScript variables
JavaScript is used for the manipulation of data. The pieces of data can be stored either ni
variables or arrays.
JavaScript Variables are declared using the “var” keyword. Syntax: var num;
JavaScript variables can be declared with initial value. Syntax: var num=1;
Multiple JavaScript variables can even be declared at the same time.
45
but before a value has been assigned to it
JavaScript Popup Boxes
JavaScript has three kinds of popup boxes:
1. Alert Box: - is used if you want to make sure information comes through to the user.
Syntax: alert("sometext");
2. Confirm Box: - is used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
Syntax:
confirm("sometext"); if
(confirm("Press a
button!")) { txt =
"You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
3. Prompt Box: - is used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value. If the user clicks "OK" the box returns the input
value. If the user clicks "Cancel" the box returns null.
Syntax: prompt("sometext","defaultvalue");
var person = prompt("Please enter your name", "Nahil"); if
(person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you today?";
}
46
4.4 Functions in JavaScript
A function consists of the “function” keyword followed by the name of the
function, a set of open and close parentheses enclosing an optional parameter
list and a body enclosed in a set of curly braces.
Syntax:
function functionName(parameterList) {
// body
}
Function parameters are separated by commas in the function declaration.
A function uses the return keyword to return a value from a function.
JavaScript code found in a function is not executed until the function is called.
Assigns function to event: - many elements of DOM support events. These events
Example:
<html>
<body>
<script type="text/javascript">
function addition(){
47
var x=7; var y=10;
var sum=x+y;
alert(sum);}
</script><form>
<input type="button" onclick="addition()" value="show">
</form> </body></html>
48
JavaScript can create, read, and delete cookies with the document.cookie property.
With JavaScript, a cookie can be created like: document.cookie = "username=Ayantu";
We can also add an expiry date (in UTC time). By default, the cookie is deleted when the
browser is closed. document.cookie = "username=Ayantu; expires=Thu, 18 Dec 2019
12:00:00 UTC";
With JavaScript, we can read cookies like:
<script>
{
document.write(document.cookie);
}
</script>
Deleting a cookie is very simple. Just set the “expires” parameter to a passed date.
document.cookie = "username=Ayantu; expires=Thu, 01 Jan 1970 00:00:00 UTC;
path=/;" ;
Session: - A session uniquely identifies and provides continuity for a user’s website usage
to a better degree than an IP address or cookie could (essentially, by using both together)
Session Cookie: - A cookie that is deleted when the web browser is closed.
Using JavaScript on HTML forms
49
false, to prevent the form from being submitted:
function validateForm() {
var x = document.forms["myForm"]["fieldname"].value; if (x == "") {
alert("Name must be filled out"); return false;
}
}
The function can be called when the form is submitted.
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()"
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
4.7 What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface
that allows programs and scripts to dynamically access and update the content,
structure, and style of a document."
What is the HTML DOM?
The HTML DOM is a standard object model and programming interface for HTML. It defines:
The HTML elements as objects
The properties of all HTML elements
The methods to access all HTML elements
The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.
1. JavaScript HTML DOM Window Object
The window object represents an open window in a browser.
If a document contain frames (<iframe> tags), the browser creates one window object for
50
the HTML document, and one additional window object for each frame.
Note: There is no public standard that applies to the Window object, but all major
browsers support it.
Window object properties and methods:
1. self :- it returns the current window
2. status:- it sets or returns the text in the status bar of a window
3. top:- it returns the topmost browser window
2. JavaScript HTML DOM Document:
The HTML DOM document object is the owner of all other objects in our web page.
The document object represents our web page. When we want to access any element ni
an HTML page, we always start with accessing the document object.
Below are some examples of how we can use the document object to access and
manipulate HTML.
DOM Document methods for finding HTML elements
o document.getElementById(id):- Find an element by element id.
o document.getElementsByTagName(name):- Find elements by tag name
o document.getElementsByClassName(name):- Find elements by class name
DOM Document methods for changing HTML elements
o element.innerHTML = new html content:- Change the inner HTML of an
element
o element.attribute = new value: - Change the attribute value of an HTML
element.
o element.setAttribute(attribute, value):- Change the attribute value of an
HTML element
o element.style.property = new style:- Change the style of an HTML element
DOM Document methods for Adding and Deleting Elements
o document.createElement(element):- Create an HTML element
o document.removeChild(element):- Remove an HTML element
o document.appendChild(element):- Add an HTML element
o document.replaceChild(element):- Replace an HTML element
51
o document.write(text):- Write into the HTML output stream
52
4.8 Review Questions
Choose the best answer for the following questions
1. Where Client-side JavaScript code is embedded within HTML documents?
A. A URL that uses the special javascript:code
B. A URL that uses the special javascript:protocol
C. A URL that uses the special javascript:encoding
D. A URL that uses the special javascript:stack
2. Which of the following is not an error in JavaScript?
A. Missing of Bracket C. Division by zero
B. Syntax error D. Missing of semicolons
3. What is the correct way to declare a variable in JavaScript?
C. var myVariable; C. let myVariable;
D. const myVariable = 10; D. All of the above
4. What does the Array.prototype.map() method return?
A. A modified version of the original array C. A new array with transformed
elements
B. A single value D. The length of the array
5. What is the output of the following code?
let x = "9";
let y = 3;
console.log(x + y);
A. 93 B. 12 C. 5 3 D. Error
6. Which of the following methods is used to merge two or more arrays?
A. splice () B. push() C. concat() D. merge()
7. Which of these is NOT a looping structure in JavaScript?
A. Foreach B. repeat C. while D. for
53
Chapter 5
Server-side programming
All of the code is executed on the server before the data is passed to the user'sbrowser. In the
case of PHP this means that no PHP code ever reaches the user, it is instead executed and only
the information it outputs is sent to the web browser.
Server-side processing is used to interact with permanent storage like databases orfiles.
Server-side processing happens when a page is first requested and when pages areposted back
to the server.
Examples of server-side processing are:
o User validation,
o Saving and retrieving data, and
o Navigating to other pages.
Differences between Client-side and Server-side Scripting
The client refers to a web browser running on the user’s local machine.
The server is the web server software (e.g. Apache) that runs on server hardware.
Client-Side Scripting
It is used to run scripts which are usually a browser.
The processing takes place on the end users computer.
The source code is transferred from the web server to the user’s computer overthe
54
internet and run directly in the browser.
The scripting language needs to be enabled on the client computer.
Server-Side Scripting
It is used to runs a scripting language in a web server.
A user's request is fulfilled by running a script directly on the web server ot generate
dynamic HTML pages. This HTML is then sent to the client browser.
It is usually used to provide interactive web sites that interface to databases or other data stores
on the server.
Its advantage is the ability to highly customize the response based on the user's
requirements, access rights, or queries into data stores.
5.2 What is PHP?
It is an acronym for "PHP Hypertext Preprocessor"
It is used for creating dynamic and interactive websites.
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain
HTML
PHP files have extension ".php"
It can create, open, read, write, delete, and close files on the server
It can collect data from form, and it can send and receive cookies
It can add, delete, modify data in your database and supports a wide range of databases
It can restrict users to access some pages on your website and it can encrypt data
It runs on various platforms (Windows, Linux, UNIX, Mac OS X, etc.)
It is compatible with almost all servers used today (Apache, IIS, etc.)
It is free. Download it from the official PHP resource: www.php.net
It is easy to learn and runs efficiently on the server side
55
Use Basic Syntax
There are three main differences between a standard HTML document and a PHP
document.
First, PHP scripts should be saved with the .php file extension (for example, index.php).
Just as a file’s extension on your computer tells the operating system in what application to
open the file, a Web page’s extension tells the server how to process the file.
Second, you place PHP code within <?php and ?> tags, normally within thecontext of
some HTML.
Example <html><body><h1>This is HTML.</h1>
<?php PHP code! ?>
<p>More HTML</p>
</body></html>
PHP tags indicate the parts of the page to be run through the PHP processor on the server.
Third, PHP scripts must be run on a PHP-enabled Web server (whereas HTML
pages can be viewed on any computer, directly in a browser). This means that
PHP scripts must always be run through a URL.
Note
A PHP script can be placed anywhere in the document.
PHP statements are terminated by semicolon (;).
The closing tag of a block of PHP code also automatically implies a semicolon (soyou
do not have to have a semicolon terminating the last line of a PHP block).
Example <!DOCTYPE html>
<html><body><h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body></html>
Sending Data to the Web Browser
1. You’ll use PHP most frequently to send information to the browser in the form of
plain text and HTML tags. To do so, there are two basic ways to get output: echo
56
and print.
There are some differences between echo and print:
1. Echo: - can output one or more strings
It is a language construct, and used with or without parentheses: echo orecho().
It is faster compared to print as echo does not return any value.
2. Print: - can only output one string, and returns always 1
It is can be used with or without parentheses: print or print().
Just type the word print, followed by what you want to display: a simplemessage,
the value of a variable, the result of a calculation, and so forth.
To be clear, print doesn’t actually print anything; it just outputs data. Whena
PHP script is run through a Web browser, that PHP output is received by the
browser itself.
Example using Echo
<?php
echo "<h2>PHP is
fun!</h2>"; echo "Hello
world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This", " string", " was", " made", " with multiple parameters.";
?>
Example using Print
<?php
print "<h2>PHP is
fun!</h2>"; print "Hello
world!<br>";
print "I'm about to learn PHP!";
?>
57
5.3 Comments in PHP
Comments are integral to programming, not because they do anything but becausethey help
you remember why you did something.
The computer ignores these comments when it processes the script. Furthermore, PHP
comments are never sent to the Web browser and therefore remain your secret.
Comments are useful for:
To let others understand what you are doing - Comments let other programmers
understand what you were doing in each step.
To remind yourself what you did - Most programmers have experienced comingback
to their own work a year or two later and having to re-figure out what they did.
Comments can remind you of what you were thinking when you wrote the code.
PHP supports three ways of commenting:
1. // This is a single line comment
2. # This is also a single line comment
3. /* This is a multiple lines comment block that spans over more than one line */
PHP Case Sensitivity
In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo,etc.)
are NOT case-sensitive.
However; in PHP, all variables are case-sensitive.
In the example below, only the first statement will display the value of the $colorvariable
(this is because $color, $COLOR, and $coLOR are treated as three different variables):
Example <!DOCTYPE html>
<html><body>
<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>"; echo "My boat is " . $coLOR
. "<br>";
?>
</body></html>
58
5.4 Variables in PHP
A variable is a container for data.
Once data has been stored in a variable that data can be altered, printed to the W
ebbrowser,
saved to a database, emailed, and so forth.
Variables in PHP are, by their nature, flexible: You can put data into a variable, retrieve
that data from it (without affecting the value of the variable), put new data in, and
continue this cycle as long as necessary.
Variables in PHP are largely temporary: - they only have a value for the duration of the
script’s execution on the server. Once the execution passes the final closing PHP tag,
those variables cease to exist.
Example <?php
$x=5; $y=6;$z=$x+$y; echo $z;
?>
Note
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, _ )
Variable names are case sensitive ($y and $Y are two different variables)
PHP has no command for declaring a variable.
59
After the execution of the statements above, the variable txt will hold the value Hello world!,
the variable x will hold the value 5, and the variable y will hold the value 10.5.
Note
When you assign a text value to a variable, put quotes around the value.
PHP is a Loosely Typed Language
PHP automatically converts the variable to the correct data type, depending on itsvalue.
In other languages such as C, C++, and Java, the programmer must declare the nameand type
of the variable before using it.
5.5 PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/ used.
PHP has three different variable scopes:
1. local
2. global
3. static
Local and Global Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function.
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function.
The following example tests variables with local and global scope:
Example <?php
$x=5; // global scope function myTest() {
$y=10; // local scope
echo "<p>Test variables inside the function:</p>"; echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y"; } myTest();
echo "<p>Test variables outside the function:</p>"; echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>
60
In the example above there are two variables $x and $y and a function myTest().
$x is a global variable since it is declared outside the function and $y is a localvariable since
it is created inside the function.
When we output the values of the two variables inside the myTest() function, it prints the
value of $y as it is the locally declared, but cannot print the value of $x since it is created
outside the function.
Then, when we output the values of the two variables outside the myTest() function, it prints the
value of $x, but cannot print the value of $y since it is a local variable and it is created inside
the myTest() function.
You can have local variables with the same name in different functions, because localvariables
are only recognized by the function in which they are declared.
PHP the global Keyword
The global keyword is used to access a global variable from within a function. To dothis, use
the global keyword before the variables (inside the function):
Example <?php
$x=5;$y=10; function myTest() { global $x,$y;
$y=$x+$y; } myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index].
The index holds the name of the variable. This array is also accessible from withinfunctions
and can be used to update global variables directly.
The example above can be rewritten like this:
Example <?php
$x=5; $y=10; function myTest() {
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y']; }
myTest();
echo $y; // outputs 15
?>
PHP the static Keyword
Normally, when a function is completed or executed, all of its variables are deleted. However,
61
sometimes we want a local variable NOT to be deleted. We need it for a further job. To
do this, use the static keyword when you first declare the variable:
Example <?php
function myTest() { static $x=0;
echo $x;
$x++; } myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information ticontained
from the last time the function was called. The variable is still local to the function.
5.6 Manipulate Strings
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example <?php
$x = "Hello world!"; echo $x;
echo "<br>";
$x = 'Hello world!'; echo $x;
?>
Concatenating Strings
It refers to the appending of one item onto another.
The period (.) is the operator for performing this action, and it’s used like so:
$s1 = 'Hello, ';
$s2 = 'world!';
62
Adjusting String Case
A handful of PHP functions are used to change the case of a string’s letters:
. ucfirst() capitalizes the first letter of the string.
. ucwords() capitalizes the first letter of words in a string.
. strtoupper() makes an entire string uppercase.
. strtolower() makes an entire string lowercase.
Manipulate Numbers
An integer is a number without decimals.
Rules for integers:
An integer must have at least one digit (0-9)
An integer cannot contain comma or blanks
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based –
prefixed with 0x) or octal (8-based - prefixed with 0)
In the following example we will test different numbers. The PHP var_dump() function returns
the data type and value of variables:
Example <?php
$x = 5985;
var_dump($x); echo "<br>";
$x = -345; // negative number var_dump($x);
echo "<br>";
63
function returns the data type and value of variables:
Example <?php
$x = 10.365;
var_dump($x); echo "<br>";
$x = 2.4e3; var_dump($x); echo "<br>";
$x = 8E-5;
var_dump($x);
?>
PHP Booleans
Booleans can be either TRUE or FALSE. Booleans are often used in conditional
testing.
$x=true;
$y=false;
5.7 Operators in PHP
1. Arithmetic Operators
There are following arithmetic operators supported by PHP language.
Addition (+), Subtraction (-), Multiplication (*), Division (/)
Assume variable A holds 10 and variable B holds 20 then:
64
Operator Description Example
== Checks if the value of two operands is equal or not, if yes (A == B) is not true.
then condition becomes true.
!= Checks if the value of two operands is equal or not, if (A! = B) is true.
values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value (A > B) is not true.
of right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal (A >= B) is not true.
to the value of right operand, if yes then condition becomes
true.
<= Checks if the value of left operand is less than or equal to the(A <= B) is true.
value of right operand, if yes then condition becomes true.
3. Logical Operators
There are following logical operators supported by PHP language. Assume variable A holds 10 and
variable B holds 20 then
65
4. Assignment Operators
There are following assignment operators supported by PHP language:
operand
operand
5. Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for a true or false value
and then execute one of the two given statements depending upon the result of the evaluation. The conditional
operator has this syntax:
All the operators we have discussed above can be categorized into following categories
2. Binary operators: - which take two operands and perform a variety of arithmetic and
logical operations.
3. The conditional operator (a ternary operator): - which takes three operands and
66
evaluates either the second or third expression, depending on the evaluation of the first
expression.
4. Assignment operators: - which assign a value to a variable.
Constants are like variables except that once they are defined they cannot bechanged or
undefined.
A constant is an identifier (name) for a simple value. The value cannot be changed during
the script.
A valid constant name starts with a letter or underscore, followed by any number of letters,
numbers, or underscores. A constant is case-sensitive by default. By convention,
constant identifiers are always uppercase.
Note: Unlike variables, constants are automatically global across the entire script.
Set a PHP Constant
To set a constant, use the define() function - it takes three parameters:
The first parameter defines the name of the constant,
The second parameter defines the value of the constant, and
The optional third parameter specifies whether the constant name should becase-
insensitive. Default is false.
The example below creates a case-sensitive constant, with the value of "Welcome to Ambo
University!":
Example <?php
define("GREETING", "Welcome to Ambo University!"); echo GREETING;
?>
The example below creates a case-insensitive constant, with the value of "Welcome to Ambo
University!":
Example <?php
define("GREETING", "Welcome to Ambo University!", true); echo greeting;
?>
To define a constant you have to use define() function and to retrieve the value ofaconstant,
you have to simply specifying its name.
67
You can also use the function constant() to read a constant's value if you wish ot obtain
the constant's name dynamically.
constant() function
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not know sti name,
i.e. it is stored in a variable or returned by a function. constant()
Example <?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in constants.
Differences between constants and variables are
There is no need to write a dollar sign ($) before a constant, where as in Variable onehas to
write a dollar sign.
Constants cannot be defined by simple assignment, they may only be defined usingthe define()
function.
Constants may be defined and accessed anywhere without regard to variable scopingrules.
Once the Constants have been set, may not be redefined or undefined.
68
o Associative arrays - Arrays with named keys
o Multidimensional arrays - Arrays containing one or more arrays
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
A two-dimensional array is an array of arrays (a three-dimensional array is an array of
arrays of arrays).
o Example
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
To get access to the elements of the $cars array we must point to the two indices (row and
column):
69
PHP provides many built-in functions to work with arrays. Some of the commonly used
ones are:
o count($array): Returns the number of elements in the array.
o array_merge($array1, $array2): Merges two or more arrays.
o array_push($array, $value): Adds one or more elements to the end of the array.
o array_pop($array): Removes the last element of the array.
o array_keys($array): Returns all the keys of the array.
o array_values($array): Returns all the values of the array.
o in_array($value, $array): Checks if a value exists in the array.
o sort($array): Sorts an array in ascending order.
o rsort($array): Sorts an array in descending order
Database Queries
70
o Define password of the user.
o efine database name.
To define the constant, we can use as follows:
<?php
?>
b. Opening Database Connection
After defining constants using php, opening or creating connection is very important. To
open or create database connection, we use mysql_connect function.
This function takes three parameters. Those are:
o db_server,db_user,db_pass.
o Db_server:-The host name running database server
o Db_user:-The username accessing the database
o Db_pass:-The password of the user accessing the database.
From the above the host name running database server is ―localhost‖, the username
accessing the database is ―user‖, and the password of the user accessing the database is
empty. Connection can opened or created as follows:
$connection=mysql_connect(db_server,db_user,db_pass);
c. Select database
Once you establish a connection with a database server then it is required to select a
particular database where your all the tables are associated.
This is required because there may be multiple databases residing on a single server and
you can do work with a single database at a time.
To select database, we use mysql_select_db as follows:-
$db_select=mysql_select_db(db_name,$connection);
71
d. Closing database connection
Its simplest function mysql_close PHP provides to close a database connection. This
function takes connection resource returned by mysql_connect function. For example, to
close the connection that you use in the above; you use mysql_close function as follows:-
mysql_close($connection);
72
The difference between Servlet and JSP is as follows:
Servlet JSP
Servlet is a java code. JSP is a HTML-based compilation code.
Writing code for servlet is harder than JSP as it JSP is easy to code as it is java in HTML.
is HTML in java.
Servlet plays a controller role in the ,MVC JSP is the view in the MVC approach for
approach. showing output.
Servlet is faster than JSP. JSP is slower than Servlet because the first
step in the JSP lifecycle is the translation of
JSP to java code and then compile.
Servlet can accept all protocol requests. JSP only accepts HTTP requests.
In Servlet, we can override the service() In JSP, we cannot override its service()
method. method.
In Servlet by default session management is In JSP session management is automatically
not enabled, user have to enable it explicitly. enabled.
In Servlet we have to implement everything In JSP business logic is separated from
like business logic and presentation logic in presentation logic by using JavaBeansclient-
just one servlet file. side.
Modification in Servlet is a time-consuming JSP modification is fast, just need to click
compiling task because it includes reloading, the refresh button.
recompiling, JavaBeans and restarting the
server.
It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.
There is no method for running JavaScript on While running the JavaScript at the client
the client side in Servlet. side in JSP, client-side validation is used.
Packages are to be imported on the top of the Packages can be imported into the JSP
program. program (i.e, bottom , middleclient-side, or
top )
It can handle extensive data processing. It cannot handle extensive data processing
very efficiently.
The facility of writing custom tags is not The facility of writing custom tags is
present. present.
Servlets are hosted and executed on Web Before the execution, JSP is compiled in
Servers. Java Servlets and then it has a similar
lifecycle as Servlets.
73
5.12 Review Questions
Choice the best answer for the following Questions
1. Which one of the following is not an array in PHP programming?
A. Multidimensional array C. Indexed array
B. Singledimensional array D. Associative array
2. Which is the correct syntax that used to write PHP server scripts?
A. <?php> ------ <?p> C. <script>--------</script>
B. <?php ------- ?> D. <html>…-.</html>
3. All PHP variables are start with which symbol?
A. ? B. & C. # D. $
4. What is the correct way to create a function in PHP?
A. function myFuction() C. Myfunction function()
B. create myFunction() D. new_function function()
5. Which of the following is a correct way to add a comment in PHP?
A. /* ……. */ B. \* ……..*\ C. <? ………> D. <>……..</>
6. Which one is invalid variables name in php?
A. $myVar B. $my_Var C. $my-Var D. $_017
7. One is the correct php statements to display “Hello World” on a browser.
A. echo Hello World C. echo @Hello World@;
B. echo “Hello World”; D. All are correct
8. A PHP loop execute a code once, and then repeats the loop as long as a special condition is
true. is:
A. while B. do…. while C. for D. foreach
9. One is the correct PHP syntax that used to returns the length of a string.
A. substr(string,start,length) C. strrev(string)
B. substr_count(string,substring,start,length) D. strlen(string)
10. PHP uses __________ function to create a MySQL database.
A. mysqli_creatte() C. mysqli_connect ()
B... mysqli_query () D. mysqli_database ()
11. What is the correct way to create a function in PHP?
A. function myFuction() C. Myfunction function()
B. create myFunction() D. new_function function()
12. Which of the following is a correct function to close a database connection in PHP?
A. mysqli_close(); B. mysqli_delete(); C. mysqlclose(); D mysqli-
-close();
13. _________function is used to read a single line from a file.
A fgetc() B. fwrite() C. fgets() D. fopen()
14. Which superglobal variable holds information about headers, paths, and script locations?
A. $_SESSION B. $GLOBALS C. $_SERVER D. $_GET
74
15. To open or create database connection, mysql_connect function..
C. mysqlconnect C. . mysqli--connect()
D. mysqli_connect() D. All are correct
16. What is the correct way to open the file "time.txt" as readable?
A. fopen("time.txt","r"); C. open("time.txt");
B. open("time.txt","read"); D. fopen("time.txt","r+");
17. Data can be fetched from MySQL tables by executing _________statement through PHP
function mysql_query
A. SQL INSERT C. SQL UPDATE
B. SQL DELETE D. SQL SELECT
75
PHASE II:
MOBILE APPLICATION
76
CHAPTER ONE
INTRODUCTION ANDROID
Android is an operating system that powers mobile devices and is one of the most popular
mobile platforms today. Android platform runs on hundreds of millions of mobile devices
throughout the world. It's the largest installed operating system of anymobile operating system
and growing rapidly day by day.
You can develop apps and games using Android and it gives you an open marketplace for
distributing your apps and games instantly.
Android is the operating system for powering screens of all sizes. Android version is named
after a dessert. The latest version of android is Android 9.0 – Pie. Following table shows how
the android platform evolves.
1.0 The Android Platform
Andy Rubin has been credited as the father of the Android platform. His company, Android
Inc., was acquired by Google in 2005.Working together, OHA members, including Google,
began developing a non-proprietary open standard platform based upon technology developed
at Android Inc. that would aim to solve the problems hindering the mobile community. The
result is the Android project. Most Android platform development is completed by Rubin’s
team at Google, where he acts as VP of Engineering and manages the Android platform
roadmap. Google hosts the Android open-source project and provides online Android
documentation, tools, forums, and the Software Development Kit (SDK) for developers. All
major Android news originates at Google.
What is android?
Android is called as “the first complete, open, and free mobile platform”:
Free: Android applications are free to develop. Android applications can bedistributed
and commercialized in a variety of ways.
77
Features of Android
What it is not?
Android is not:
A Java ME implementation: Android applications are written in the Java language, but
they are not run within a Java ME virtual machine, and Java- compiled classes and
executable will not run natively in Android.
Part of the Linux Phone Standards Forum or the Open Mobile Alliance: Android runs on
an open-source Linux kernel, but, while their goals are similar, Android’s complete
software stack approach goes further than the focus of these standards-defining
organizations.
Simply an application layer (like UIQ or S60): While Android does include an application
layer, ‘‘Android’’ also describes the entire software stack encompassing the underlying
operating system, the API libraries, and the applications themselves.
A mobile phone handset Android includes a reference design for mobile handset
manufacturers, but there is no single ‘‘Android phone.’’ Instead, Android has beendesigned
to support many alternative hardware devices.
78
Google’s answer to the iPhone: The iPhone is a fully proprietary hardware and software
platform released by a single company (Apple), while Android is an open-source software
Android phones will normally come with a suite of generic preinstalled applications that are
part of the Android Open-Source Project (AOSP), including, but not necessarily limited to:
An e-mail client
A calculator
An alarm clock
In many cases Android devices will also ship with the following proprietary Google
mobile applications:
79
The Gmail mail client
GSM, EDGE, and 3G networks for telephony or data transfer, enabling you to make or
receive calls or SMS messages, or to send and retrieve data across mobile networks
Comprehensive APIs for location-based services such as GPS
Full multimedia hardware control, including playback and recording with thecamera and
microphone
APIs for using sensor hardware, including accelerometers and the compass
The ability to integrate application search results into the system search
Full support for applications that integrate map controls as part of their user
interface
Mobile-optimized hardware-accelerated graphics, including a path-based 2Dgraphics
libraryand support for 3D graphics using OpenGL ES 2.0
80
Media libraries for playing and recording a variety of audio/video or still image
formats
Localization through a dynamic resource framework
An application framework that encourages reuse of application components andthe
replacement of native application
Android is an open source, Linux-based software stack created for a wide array of devices and
form factors. The following diagram shows the major components of the Android platform.
The Linux Kernel
The foundation of the Android platform is the Linux kernel. For example, the Android Runtime
(ART) relies on the Linux kernel for underlying functionalities such asthreading and low-level
memory management.Using a Linux kernel allows Android totake advantage of key security
features and allows device manufacturers to develop hardware drivers for a well-known kernel.
Hardware Abstraction Layer (HAL)
The hardware abstraction layer (HAL) provides standard interfaces that exposedevice hardware
capabilities to the higher-level Java API framework. The HAL consists of multiple library
modules, each of which implements an interface for a
specific type of hardware component, such as the camera or Bluetooth module. When a
framework API makes a call to access device hardware, the Android system loads the library
module for that hardware component.
Android Runtime
For devices running Android version 5.0 (API level 21) or higher, each app runs in its own
process and with its own instance of the Android Runtime (ART). ART is written to run
multiple virtual machines on low-memory devices by executing DEX files, a byte code format
designed especially for Android that's optimized for minimal memory footprint. Build tool
chains, such as Jack, compile Java sources into DEX byte code, which can run on the Android
platform.
81
Some of the major features of ART include the following:
The entire feature-set of the Android OS is available to you through APIs written inthe
Java language. These APIs form the building blocks you need to create Android
apps by simplifying the reuse of core, modular system components and services,which
include the following:
A rich and extensible View System you can use to build an app’s UI, includinglists,
grids, text boxes, buttons, and even an embeddable web browser
A Resource Manager, providing access to non-code resources such aslocalized
strings, graphics, and layout files
82
A Notification Manager that enables all apps to display custom alerts in thestatus
bar
An Activity Manager that manages the lifecycle of apps and provides acommon
navigation back stack
Content Providers that enable apps to access data from other apps, such asthe
Contacts app, or to share their own data
Developers have full access to the same framework APIs that Android system appsuse.
System Apps
Android comes with a set of core apps for email, SMS messaging, calendars,internet browsing,
contacts, and more. Apps included with the platform have no special status among the apps the
user chooses to install. So, a third-party app can become the user's default web browser, SMS
messenger, or even the default keyboard (some exceptions apply, such as the system's Settings
app).
The system app’s function both as apps for users and to provide key capabilities that developers can
access from their own app. For example, if your app would like to deliver an SMS message, you don't
need to build that functionality you—you can instead invoke whichever SMS app is already installed to
deliver a message to the recipient you specify
83
Figure-1: Android Software Stack
1.5 Factors that affect Mobile Application development
You should keep in mind the following factors while developing mobile application:
• Low processing power
• Limited RAM
• Limited permanent storage capacity
• Small screens with low resolution
• High costs associated with data transfer
• Slow data transfer rates with high latency
• Unreliable data connections
84
• Limited battery life
Following are some of the factors that affect app development time:
Assignments
a. What is android? Explain history of android version with API level
b. Explain android architecture and features of android SDK
85
A. Apple B. Google C. Android Inc. D. Nokia
5. Android supports which features.
A. Multitasking B. Bluetooth C. Video calling D. All of the above
6. Android is -
A. an operating system B. a web browser C. a web server D. None of the above
86
Chapter Two
Android Software Development Android Studio for
Introduction
Android Studio is the official Integrated Development Environment (IDE) for Android app
development. Android Studio offers many features that enhance your productivity when
building Android apps. In this unit we will explore in great details about Android Studio.
Features of Android Studio
Android Studio has following salient features for android application development:
Intelligent code editor: Android Studio provides an intelligent code editor capable of
advanced code completion, refactoring, and code analysis. The powerful code editor helps you
be a more productive Android app developer.
Project Wizard: New project wizards make it easier than ever to start a new project. Start
projects using template code for patterns such as navigation drawer and view pagers, and even
import Google code samples from GitHub.
Multi-screen app development: Build apps for Android phones, tablets, Android Wear,
Android TV, Android Auto and Google Glass. With the new Android Project View and
module support in Android Studio, it's easier to manage app projects and resources.
Virtual devices for all shapes and sizes: Android Studio comes pre-configuredwith an
optimized emulator image. The updated and streamlined Virtual Device Manager provides pre-
defined device profiles for common Android devices.
Android builds evolved, with Gradle: Create multiple APKs for your Android app with
different features using the same project.
To develop apps for Android, you use a set of tools that are included in Android Studio. In
addition to using the tools from Android Studio, you can also access most of the SDK tools
from the command line.
App Workflow
The basic steps for developing applications encompass four development phases,which
include:
Environment Setup: During this phase you install and set up your development
environment. You also create Android Virtual Devices (AVDs) and connect hardware
devices on which you can install your applications.
87
Project Setup and Development: During this phase you set up and developyour
Android Studio project and application modules, which contain all of the source code and
resource files for your application.
Building, Debugging and Testing: During this phase you build your project into a
debuggable .apk package(s) that you can install and run on the emulator or an Android-
powered device. Android Studio uses a build system based on Gradle that provides
flexibility, customized build variants, dependency resolution, and much more. If you're
using another IDE, you can build your project using Gradle and install it on a device using
adb. Next, with Android Studio you debug your application using the Android Debug
Monitor and device log messages along with the IntelliJ IDEA intelligent coding features.
You can also use a JDWP-compliant debugger along with the debugging and logging tools
that are provided with the Android SDK. Last, you test your application using various
Android SDK testing tools.
Publishing: During this phase you configure and build your application forrelease and
distribute your application to users.
Android Virtual Devices (AVD)
An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual
device by defining hardware and software options to be emulated by the Android Emulator. An
AVD consists of:
A hardware profile: Defines the hardware features of the virtual device. For example, you
can define whether the device has a camera, whether it uses aphysical QWERTY keyboard or
a dialing pad, how much memory it has, and so on.
A mapping to a system image: You can define what version of the Androidplatform will run
on the virtual device. You can choose a version of the standard Android platform or the system
image packaged with an SDK add-on.
Other options: You can specify the emulator skin you want to use with the AVD, which lets
you control the screen dimensions, appearance, and so on. You can also specify the emulated
SD card to use with the AVD.
A dedicated storage area on your development machine: the device's user data (installed
applications, settings, and so on) and emulated SD card are stored in this area.
88
The easiest way to create an AVD is to use the graphical AVD Manager. You can also start the
AVD Manager from the command line by calling the android tool with the avd options, from
the <sdk>/tools/ directory.
You can also create AVDs on the command line by passing the android tool options.
You can create as many AVDs as you need, based on the types of device you want to model.
To thoroughly test your application, you should create an AVD for each general device
configuration (for example, different screen sizes and platform versions) with which your
application is compatible and test your application on each one.Keep these points in mind
when you are selecting a system image target foryour AVD:
The API Level of the target is important, because your application will not be able to run
on a system image whose API Level is less than that required by your application, as
specified in the minSdkVersion attribute of the application's manifest file.
You should create at least one AVD that uses a target whose API Level is greaterthan that
required by your application, because it allows you to test the forward- compatibility of
your application. Forward-compatibility testing ensures that, when users who have
downloaded your application receive a system update, your application will continue to
function normally.
If your application declares a uses-library element in its manifest file, the application can
only run on a system image in which that external library is present. If you want to run your
application on an emulator, create an AVD that includes the required library. Usually, you
must create such an AVD using an Add-on component for the AVD's platform.
89
Using Hardware Device to test Application
When building a mobile application, it's important that you always test your application on a
real device before releasing it to users.
You can use any Android-powered device as an environment for running, debugging, and
testing your applications. The tools included in the SDK make it easy to install and run your
application on the device each time you compile. You can install your application on the device
directly from Android Studio or from the command line with ADB.
Android ProjectStructure and Basics
Introduction
The Android build system is organized around a specific directory tree structure for the Android
project, similar to the any Java project. The project prepares the actual application that will run
on the device or emulator. When you create a new Android project, you get several items in
the project’s root directory which is discussed in sub sequent sections.
Android Project Structure
An Android project contains everything that defines your Android app. The SDK tools require
that your projects follow a specific structure so it can compile and package your application
correctly. Android Studio takes care of all this for you.
A module is the first level of control within a project that encapsulates specific types of source
code files and resources. There are several types of modules with a project
Module Description
Android It contains source code, resource files, and application- l e v e l settings,
Application such as the module-level build file, resource files, and
Modules Android Manifest file.
Test Modules It contains code to test your application projects and is built into
test applications that run on a device.
Library It contains shareable Android source code and resources that youcan
Modules reference in Android projects. This is useful when you have
common code that you want to reuse.
90
App Engine They are App Engine java Servlet Module for backend development, App
Modules Engine java Endpoints Module to convert server-side Java code
annotations into RESTful backend APIs, and App Engine Backend with
Google Cloud Messaging to send
push notifications from your server to your Android devices.
91
Check your progress-1
a) contains shareable Android source code and resources that you canreference
in Android projects.
c) When you compile the project for first time, in the “main” activity’s namespace
directory, the Android build chain will create
main/assets/ This is empty. You can use it to store raw asset files. For example,this is
a good location for textures and game data. Files that you save here are
compiled into an .apk file as-is, and the original filename is preserved.
You can navigate this directory and read
files as a stream of bytes using the AssetManager.
92
main/res/ Contains application resources, such as drawable files, layout files,
and string values in the following directories.
anim/ For XML files that are compiled into animation objects.
color/ For XML files that describe colors.
drawable/ For bitmap files (PNG, JPEG, or GIF), 9-Patch image files, and
XML files that describe Drawable shapes or Drawable objects that
contain multiple states (normal, pressed, or focused).
mipmap/ For app launcher icons. The Android system retains the resources in this
folder (and density-specific folders such as mipmap- xxxhdpi) regardless
of the screen resolution of the device where your app is installed. This
behavior allows launcher apps to pickthe best resolution icon for your
app to display on the home
screen.
layout/ XML files that are compiled into screen layouts (or part of a
screen).
93
app.iml/ IntelliJ IDEA module
build.gradle Customizable properties for the build system. You can edit this file to
override default build settings used by the manifest file and also set the
location of your keystore and key alias so that the build tools can sign
your application when building in release mode. This file is integral to
the project, so maintain it in a source revision
control system.
Types of Modules
94
Java Library: This type of library can contain only Java source files. The buildresult
is a Java Archive or JAR file that can be added as a dependency for your Android app
modules or other Java projects.
Google Cloud module: it provides a container for your Google Cloud backendcode. It has the
required code and dependencies for a Java App Engine backendthat uses HTTP, Cloud Endpoints, and
Cloud Messaging to connect to your app. Youcan develop your backend to provide cloud services need
by your appBasic Android API Packages
Application program interface (API) is a set of routines, protocols, and tools for building
software applications. An API specifies how software components should interact and APIs
are used when programming graphical user interface (GUI) components. Android offers a
number of APIs for developing your applications. The following list of core APIs should
provide an insight into what’s available.
API Package Use
android.util Provides common utility methods such as date/time
manipulation, base64 encoders and decoders, string andnumber
conversion methods, and XML utilities.
android.os Provides basic operating system services, message passing,
and inter-process communication on the device.
android.graphics Provides low level graphics tools such as canvases, color filters,points,
and rectangles that let you handle drawing to the screen
directly.
android.text Provides classes used to render or track text and text spans on
the screen.
android.database Contains classes to explore data returned through a content
provider.
android.content Contains classes for accessing and publishing data on a device.
android.view Provides classes that expose basic user interface classes that
handle screen layout and interaction with the user.
android.widget The widget package contains (mostly visual) UI elements to use
on your Application screen.
95
android.app Contains high-level classes encapsulating the overall Android
application model.
android.provider Provides convenience classes to access the content providers
supplied by Android.
android.webkit Provides tools for browsing the web.
Assignment
Explain Android Project Structure
Write detailed note on basic and advanced API packages
96
Check your progress-2
d) Application Program Interface is a set of routines, protocols, and tools for building
software applications (True/False)
Android Studio generally builds the manifest file for you when you create a project. For a
simple application with a single activity and nothing else, the auto-generated manifest will
work fine with little or no modifications.
97
Component of Manifest file
Android manifest file is global application description file which defines your application’s
capabilities and permissions and how it runs. This topic describes some of the most important
characteristics of your app which is stored in the manifest file.
Package name and application ID
The manifest file's root element requires an attribute for your app's package name.
App Components
For each app component that you create in your app, you must declare acorresponding XML
element in the manifest file so that the system can start it.
Foreach subclass of Activity, we have <activity>
Foreach subclass of Service, we have <service>
Foreach subclass of BroadcastReceiver we have <receiver>.For
each subclass of ContentProvider, we have <provider>
The name of your subclass must be specified with the name attribute, using the fullpackage designation,
App activities, services, and broadcast receivers are activated by intents. It is an asynchronous messaging
mechanism to match task requests with the appropriate Activity.
Permissions
Android apps must request permission to access personnel user data such ascontacts,
SMS, camera, files, internet etc. Each permission is identified by a unique label. For
example, an app that needs to send and receive SMS messages must have the following
line in the manifest:
<manifest ... >
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
...
</manifest>
Device Compatibility
In manifest file is you can declare what types of hardware or software features your app requires and
types of devices with which your app is compatible. It can’t be installed on devices that don't provide
the features or system version that your app requires. The following table shows the most common tags
for specifying device compatibility
98
Tag Description
<uses-feature> It allows you to declare hardware and software features your appneeds
Example
<manifest ... >
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
...
</manifest>
<uses-sdk> It indicates the minimum version with which your app is compatibleelement
are overridden by corresponding properties in the build.gradle file.
<manifest>
<uses-sdkandroid:minSdkVersion="5" />
...
</manifest>
File conventions
Following are the conventions and rules that generally apply to all elements and
attributes in the manifest file.
Only the <manifest> and <application> elements are required. They each mustoccur
only once, other elements can occur zero or more times.
Elements at the same level are generally not ordered hence elements can beplaced in
any order
All attributes are optional but attributes must be specified so that an element canserve its
purpose. If attributes are not provided then it indicates the default value
Except for some attributes of the root <manifest> element, all attribute namesbegin with an
android: prefix
99
Manifest elements reference
The following table provides links to reference documents for all valid elements inthe
AndroidManifest.xml file.
Element Description
<action> It is used to add an action to an intent filter.
<activity> It is used to declare an activity component.
<activity-alias> It is used to declare an alias for an activity.
<application> It is used to declare the application.
<category> It is used to add category name to an intent filter.
<compatible-screens> It is used to specifies each screen configuration with whichthe
application is compatible.
<data> Adds a data specification to an intent filter.
<grant-uri-permission> Specifies the subsets of app data that the parent contentprovider
has permission to access.
<instrumentation> Declares an Instrumentation class that enables you tomonitor an
application's interaction with the system.
<intent-filter> Specifies the types of intents that an activity, service, or
broadcast receiver can respond to.
<manifest> The root element of the AndroidManifest.xml file.
<meta-data> A name-value pair for an item of additional, arbitrary datathat
can be supplied to the parent component.
<path-permission> Defines the path and required permissions for a specificsubset
of data within a content provider.
<permission> Declares a security permission that can be used to limit access to
specific components or features of this or other applications.
100
<receiver> Declares a broadcast receiver component.
<supports-screens> Declares the screen sizes your app supports and enables screen
compatibility mode for screens larger than what your app supports.
<uses-permission> Specifies a system permission that the user must grant in order for
the app to operate correctly.
101
Multiple Choice Question for Chapter two.
1. We require an AVD to create an emulator. What does AVD stand for?
A. Android Virtual device B. Android Virtual Display C. Active Virtual Display D. Active
Virtual device
2. What is contained in manifest.xml?
A. Source code B. List of strings used in the app C. Permission that the application requires D.
None of the above
3. Which of these files specifies our screen’s layout?
A. Manifest file B. Layout file C. R file D. Strings XML
4. Which of the following holds Java source code for the application?
A. res/ B. assets/ C. src/ D. bin/
5. Of these files contains text values that you can use in your application?
A. AndroidManifest.xml B. res/Text.xml C. res/layout/Main.xml D. res/values/strings.xml
6. What file format does Android Studio generate as the final output for apps?
A. APK B. JAR C. EXE D. WAR
7. Where do you configure the minimum SDK version in Android Studio?
A. build.gradle file B. AndroidManifest.xml C. app.properties D. proguard-rules.pro
8. What is the role of the Android Virtual Device (AVD) Manager in Android Studio?
A. To manage app resources C. To test Android apps on virtual devices
B. To deploy apps to real devices D. To publish apps on Google Play
9. How do you declare a service in the AndroidManifest.xml file?
A. <service android:name=".MyService"/> C. <service name="MyService"/>
B. <service android:class="MyService"/> D. <service android:name="MyService.class"/>
10. An app fails to build in Android Studio due to missing dependencies. What is the likely
solution?
A. Restart the IDE C. Check the build.gradle file for missing dependencies
B. Uninstall and reinstall Android Studio D. Update the AndroidManifest file
102
CHAPTER THREE
ANDROID - APPLICATION COMPONENTS
Application components are the essential building blocks of an Android application.
These components are loosely coupled by the application manifest file
AndroidManifest.xml that describes each component of the application and how they
interact.
There are following four main components that can be used within an Android application
1 Activities
They dictate the UI and handle the user interaction to the smart phone screen.
Services
2
They handle background processing associated with an application.
Broadcast Receivers
3
They handle communication between Android OS and applications.
Content Providers
4
They handle data and database management issues.
What is activity?
The Activity class is designed to facilitate this paradigm. When one app invokes
another, the calling app invokes an activity in the other app, rather than the app asan
atomic whole. In this way, the activity serves as the entry point for an app's interaction
with the user. You implement an activity as a subclass of the Activityclass. An
activity provides the window in which the app draws its UI. This window typically fills
the screen, but may be smaller than the screen and float on top of otherwindows.
Generally, one activity implements one screen in an app. For instance, oneof an app’s
activities may implement a Preferences screen, while another activity implements a
Select Photo screen.
103
Life Cycle of an Activity
The Activity class is an important for application's whole lifecycle. Android applications can
be multi-process, and the multiple applications to run concurrently if memory and processing
power is available. Applications can have background processes, and applications can be
interrupted/paused when events such as message or phone calls occur. There can be only one
active application visible to theuser at a time or in other words only a single Activity is in the
foreground at any giventime.
Activities in the Android operating system are managed using an activity stack.When a new
activity is started, it is placed on the top of the stack and becomes the running/foreground
activity the previous activity always remains below it in the stack, and will not come to the
foreground again until the new activity exits.
Activity States
An activity has essentially four states
State Description
Active or running When an activity is in the foreground of the screen (at the top of
the stack).
Paused If an activity has lost focus but is still visible, it is paused. A paused
activity maintains all state and member information and remains attached
to the window manager, but can be killed by the
system in extreme low memory situations.
Stopped If an activity is completely hidden by another activity, it is stopped.
It still retains all state and member information, it will often bekilled
by the system when memory is needed elsewhere.
Destroyed If an activity is paused or stopped, the system can drop theactivity from
memory by either asking it to finish, or simply killing its process. When
it is displayed again to the user, it must be
completely restarted and restored to its previous state.
104
Activity Events
The Activity base class defines a series of events that governs the life cycle of an
activity. The Activity class defines the following events:
Event Description
onCreate() Called when the activity is first created
onStart() Called when the activity becomes visible to the user
onResume() Called when the activity starts interacting with the user
onPause() Called when the current activity is being paused and the previous
activity is being resumed
onStop() Called when the activity is no longer visible to the user
onDestroy() Called before the activity is destroyed by the system
onRestart() Called when the activity has been stopped and is restarting again
By default, the activity created for you contains the onCreate() event. Within this event
handler is the code that helps to display the UI elements of your screen.
105
Understanding Life Cycle of an Activity
The best way to understand the various stages experienced by an activity is to create a new
project, implement the various events, and then subject the activity to various user interactions.
import android.util.Log;
public class MainActivityextends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); Log.d("Event",
"In the onCreate() event");
}
public void onStart()
{
super.onStart();
Log.d("Event", "In the onStart() event");
}
public void onRestart()
{
super.onRestart();
Log.d("Event", "In the onRestart() event");
}
public void onResume()
{
super.onResume();
Log.d("Event", "In the onResume() event");
}
public void onPause()
{
super.onPause();
Log.d("Event", "In the onPause() event");
}
public void onStop()
{
super.onStop();
Log.d("Event", "In the onStop() event");
}
public void onDestroy()
{
super.onDestroy();
Log.d("Event", "In the onDestroy() event");
}
}
import android.util.Log;
Logging is a valuable resource for debugging and learning Android. Android logging features
are in the Log class of the android. util package. Some helpful methods in the android.util. Log
106
class are shown in Table. We have used Log.d() method to print message in LogCat Window
when particular event of activity fired.
Method Purpose
Log.e() Log errors
Log.w() Log warnings
Log.i() Log information messages
Log.d() Log debug messages
Log.v() Log verbose messages
Context
The application Context is the central location for all top-level application functionality. The
Context class can be used to manage application- specific configuration details as well as
application-wide operations and data. Use the application Context to access settings and
resources shared across multiple Activity instances.
Retrieving the Application Context
You can get the context by invoking getApplicationContext(), getContext(),
getBaseContext()or this (when in the activity class). You can retrieve the Contextfor the
current process using the getApplicationContext() method, like this: Context context =
getApplicationContext();
2) Retrieving Application Resources: You can retrieve application resources using the
getResources() method of the application Context. The moststraightforward way to retrieve
a resource is by using its resource identifier, a unique number automatically generated
within the R.java class.The following example retrieves a String instance from the
application resources by its resourceID:
String greeting = getResources().getString(R.string.settings);
3) Retrieving Shared Application Preferences: You can retrieve shared application
107
preferences using the getSharedPreferences() method of the application Context. The
SharedPreferences class can be used to save simple application data, such as configuration
settings.
4) Accessing Other Application Functionality Using Context: The applicationContext
provides access to a number of other top-level application features.
Here are a few more things you can do with the application Context:
Launch Activity instances
Inspect and enforce application permissions
Retrieve assets packaged with the application
Request a system service (for example, location service)
Manage private application files, directories, and databases
b) You can use the to access settings and resources shared across
multiple Activity instances.
108
Services
Introduction
In Android a service is an application that runs in the background without anyinteraction with
the user. For example, while using an application, you may want to download some file at the
same time. In this case, the code that is downloading file has no need to interact with the user,
and hence it can be run as a service. Services are also perfect for circumstances in which there
is no need to present a user interface (UI) to the user. For example, consider an application that
continually logs the geographical coordinates of the device. In this case, you can write a
service todo that in the background. You can create your own services and use them to perform
background tasks asynchronously.
To improve application responsiveness and performance, consider implementing a service to
handle the task outside the main application lifecycle. Any Services exposed by an Android
application must be registered in the Android Manifest file.
Uses Services
You can use services for different purposes. Generally, you use a service when no input is
required from the user. Here are some circumstances in which you might want to implement or
use an Android service:
A weather, email, or social network app might implement a service to routinelycheck
for updates.
A photo or media app that keeps its data in sync online might implement aservice
to package and upload new content in the background when the device isidle.
A video-editing app might offload heavy processing to a queue on its service in order to
avoid affecting overall system performance for non-essential tasks.
A news application might implement a service to “pre-load” content by downloading news
stories in advance of when the user launches the application, to improve performance
Creating a Service
To create service, you must define a class that extends the Service base class.Inside your
service class, you have to implement four methods discussed below:
109
Method Description
onStartCommand() The system calls this method when another component, such as an
activity, requests that the service be started, by calling
startService().
Once this method executes, the service is started and can run in
the background indefinitely.
It is your responsibility to stop the service when its work is done,
by calling stopSelf() or stopService().
If you only want to provide binding, you don't need to
implement this method.
onBind() The system calls this method when another component wants to
bind with the service by calling bindService().
In your implementation of this method, you must providean
interface that clients use to communicate with the service, by
returning an IBinder.
If you don't want to allow binding, then you should return
null.
onCreate() The system calls this method when the service is first
created, to perform one-time setup procedures before it
calls either onStartCommand() or onBind().
If the service is already running, this method is not called.
onDestroy() The system calls this method when the service is no longerused
and is being destroyed.
This method should be implemented to clean up any resources
such as threads, registered listeners, receivers, etc.
This is the last call the service receives.
110
Start and Stop a Service
You can use Intents and Activities to launch services using the startService() and
bindService() methods. A service can essentially take two forms. The difference
between two is as follows:
startService() bindService()
A service is "started" when an application A service is "bound" when an application
component starts it by calling component binds to it by calling
startService() bindService()
Once started, a service can run in the A bound service runs only as long asanother
background indefinitely, even if the application component is bound to it. Multiple
component that started it is destroyed components can bind to the
service.
Usually, a started service performs a single A bound service offers a client-server
operation and does not return a result to the interface that allows components to interact
caller. For example, it might download or with the service, send requests, get results, and
upload a file over the network. When the even do so across processes with inter
operation is done, the process
service should stop itself communication (IPC)
Service Life Cycle
Like an activity, a service has lifecycle callback methods that you can implement to
monitor changes in the service's state and perform work at the appropriate times as
discussed above. that are created by startService() and from those created by bindService
111
Check you progress-1
Services are perfect for circumstances in which there are no need to present auser
interface (UI) to the user. (True/False)
You can use Intents and Activities to launch services using the methods.
c) Once method executes, the service is started and can run in the
background indefinitely.
d) A service is "bound" when an application component binds to it by calling
Assignment
Differentiate between startService() and bindService()
Explain service life cycle
List uses of services
Chapter Three Multiple Choice question
1. What is an Activity in Android?
A. A component that allows background services C. A component to handle database
B. A component that represents a single screen with a user interface D. A background
process handler
2. Which method is used to launch a new Activity in Android?
A. startActivity() B. startApp() C. launchIntent() D. openActivity()
3. What is the purpose of the onCreate() method in an Android Activity?
A. To perform operations when the Activity is first created C. To close the Activity
B. To manage user permissions D. To handle background services
4. Which lifecycle method is called when an Activity becomes visible to the user?
A. onStart() B. onCreate() C. onResume() D. onPause()
5. Which method is used to send data back from an Activity to its parent?
A. setResult() B. sendIntent() C. finishActivity() D. returnResult()
6. What could cause an Activity to not appear when you try to start it?
A. The Activity is not declared in the AndroidManifest.xml C. The layout file is missing
B. The device's battery is low D. The app has no internet access
7. Which of these does NOT refer to a state in a service’s lifecycle?
A. Paused B. Destroyed C. Running D. Starting
8. Which of the following methods is called in an Activity when another activity gets into
the foreground?
A. onDestroy() B. onStop() C. onPause() D. onExit()
112
9. What is the difference between a started Service and a bound Service in Android?
A. Started Service handles user input, Bound Service doesn't C. There is no difference
B. Started Service has a UI, Bound Service does not D. Started Service runs
indefinitely, Bound Service is tied to a component
10. Which type of Service is used to perform tasks in response to explicit user interaction in
Android?
A. Started Service B. Bound Service C. Foreground Service D. Background Service
11. How do you start a Service in Android?
A. startService(new Intent(this, MyService.class)); C. runService();
B. startBackgroundService(); D. bindService();
12. How do you stop a Service in Android?
A. stopService(); B. terminateService(); C. stopForegroundService(); D.killService();
13. Why would an Android Service fail to start?
A. The Service is not declared in AndroidManifest C. The app has no internet
B. The Service is missing a layout file D. The Service uses too much memory
113
CHAPTER FOUR:
ANDROID INTENTS
An Android Intent is an abstract description of an operation to be performed. It can be used with
startActivity to launch an Activity, broadcastIntent to send it to any interested
BroadcastReceiver components, and startService(Intent) or bindService(Intent,
ServiceConnection, int) to communicate with a background Service.
The intent itself, an Intent object, is a passive data structure holding an abstract description
of an operation to be performed.
There are separate mechanisms for delivering intents to each type of component − activities,
services, and broadcast receivers.
1 Context.startActivity(): The Intent object is passed to this method to launch a new activity
or get an existing activity to do something
3 Context.sendBroadcast(): The Intent object is passed to this method to deliver the message
to all interested broadcast receivers.
An Intent object is a bundle of information which is used by the component that receives the
intent as well as information used by the Android system.
An Intent object can contain the following components based on what it is communicating or
going to perform −
Action
This is mandatory part of the Intent object and is a string naming the action to be performed —
or, in the case of broadcast intents, the action that took place and is being reported. The action
114
largely determines how the rest of the intent object is structured. The Intent class defines a
number of action constants corresponding to different intents. Here is a list of Android Intent
Standard Actions
The action in an Intent object can be set by the setAction() method and read by getAction().
Data
Adds a data specification to an intent filter. The specification can be just a data type (the
mimeType attribute), just a URI, or both a data type and a URI. A URI is specified by separate
attributes for each of its parts −
These attributes that specify the URL format are optional, but also mutually dependent −
If a scheme is not specified for the intent filter, all the other URI attributes are
ignored.
If a host is not specified for the filter, the port attribute and all the path attributes
are ignored.
Types of Intents
Explicit Intents
Explicit intent going to be connected internal world of application,suppose if you wants to
connect one activity to another activity, we can do this quote by explicit intent, below image is
connecting first activity to second activity by clicking button.
115
Implicit Intents
These intents do not name a target and the field for the component name is left blank. Implicit
intents are often used to activate components in other applications. For example −
Intent read1=new Intent(); read1.setAction(android.content.Intent.ACTION_VIEW);
read1.setData(ContactsContract.Contacts.CONTENT_URI); startActivity(read1);
Broadcast Receivers simply respond to broadcast messages from other applications or from the
system itself. These messages are sometime called events or intents. For example, applications
can also initiate broadcasts to let other applications know that some data has been downloaded to
the device and is available for them to use, so this is broadcast receiver who will intercept this
communication and will initiate appropriate action.
There are following two important steps to make BroadcastReceiver works for the system
broadcasted94 intents −
Creating the Broadcast Receive
There are following two important steps to make BroadcastReceiver works for the
system broadcasted94 intents −
Creating the Broadcast Receiver.
There are following two important steps to make BroadcastReceiver
works for the system broadcasted94 intents −
Creating the Broadcast Receiver.Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents
then you will have to create and broadcast those intents.
Creating the Broadcast Receiver
116
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and
overriding the onReceive() method where each message is received as a Intent
object parameter.
There are following two important steps to make BroadcastReceiver works for the
system broadcasted94 intents −
Creating the Broadcast Receiver.
Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents
then you will have to create and broadcast those intents.
Creating the Broadcast Receiver
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and
overriding the onReceive() method where each message is received as a Intent
object parameter.
Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents then you
will have to create and broadcast those intents.
Creating the Broadcast Receiver
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding
the onReceive() method where each message is received as a Intent object parameter.
There is one additional steps in case you are going to implement your custom intents then you
will have to create and broadcast those intents.
Creating the Broadcast Receiver
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding
the onReceive() method where each message is received as a Intent object parameter.
117
Chapter Four Multiple Question
1. How to pass the data between activities in android?
A. Intent B. Content Provider C. Broadcast receiver D. None of the Above
2. How do you pass data between two Activities in Android?
A. Using a Service B. Using a Fragment C. Using an Intent D. Using a Content Provider
3. How do you retrieve data from an Intent in the receiving Activity?
A. getIntent().getData() B. getIntent().getExtras() C. startIntent().getData() D. All
4. If you want to configure a link between two Android activities in the same Android
application, you need to use:
A. Intent B. Gradle C. Toast D. Progress bar
5. What is an Intent in Android?
A. messaging object B. type of service C. memory management tool D. debugging
technique
118
CHAPTER FIVE:
ANDROID GUI
Android provides several common UI controls, widgets, and Layout Managers.
For most graphical applications, it’s likely that you’ll need to extend and modify these standard
Views — or create composite or entirely new Views — to provide your own user experience.
The basic building block for user interface is a View object which is created from the View class
and occupies a rectangular area on the screen and is responsible for drawing and event handling.
View is the base class for widgets, which are used to create interactive UI components like
buttons, text fields, etc.
The ViewGroup is a subclass of View and provides invisible container that hold other Views or
other ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical
layout defines the visual structure for an Android user interface and can be created either at run
time using View/ViewGroup objects or you can declare your layout using
simple XML file main_layout.xml which is located in the res/layout folder of your project.
119
Android Layout Types
There are number of Layouts provided by Android which you will use in almost all the Android
applications to provide different view, look and feel.
2 Relative Layout: RelativeLayout is a view group that displays child views in relative
positions.
3 Table Layout: TableLayout is a view that groups views into rows and columns.
6 List View: ListView is a view group that displays a list of scrollable items.
UI Elements
A View is an object that draws something on the screen that the user can interact with
and a ViewGroup is an object that holds other View (and ViewGroup) objects in
order to define the layout of the user interface.
Android UI Controls
There are number of UI controls provided by Android that allow you to build the
graphical user interface for your app.
120
Sr.No UI Control & Description
.
1 TextView: This control is used to display text to the user.
2 EditText:EditText is a predefined subclass of TextView that includes rich editing
capabilities.
3 AutoCompleteTextView:The AutoCompleteTextView is a view that is similar to EditText,
except that it shows a list of completion suggestions automatically while the user is typing.
4 Button: A push-button that can be pressed, or clicked, by the user to perform an action.
5 ImageButton:An ImageButton is an AbsoluteLayout which enables you to specify the exact
location of its children. This shows a button with an image (instead of text) that can be
pressed or clicked by the user.
6 CheckBox: An on/off switch that can be toggled by the user. You should use check box
when presenting users with a group of selectable options that are not mutually exclusive.
7 ToggleButton: An on/off button with a light indicator.
8 RadioButton: The RadioButton has two states: either checked or unchecked.
9 RadioGroup: A RadioGroup is used to group together one or more RadioButtons.
10 ProgressBar: The ProgressBar view provides visual feedback about some ongoing tasks,
such as when you are performing a task in the background.
11 Spinner:A drop-down list that allows users to select one value from a set.
12 TimePicker:The TimePicker view enables users to select a time of the day, in either 24-
hour mode or AM/PM mode.
13 DatePicker:The DatePicker view enables users to select a date of the day.
2-D Graphics and UI Design are two important aspects in User Interface (UI) design. In this
chapter, we will introduce 2-D graphics and some advanced UI design techniques. Main techniques
of 2-D graphics include Color, Paint, Path, Canvas, Drawable, and Button Selector. Three main
aspects in multimedia include Media, Audio, and Video.
Android implements complete 2-D functions in one package, named android.graphics. This
package provides various kinds of graphics tools, such as canvas, color filter, point, line, and
rectangles.
Color
121
Colors are represented as packed integers, made up of 4 bytes: Alpha, Red, Green, and Blue. Alpha
is a measure of transparency, from value 0 to value 255. The value 0 indicates the color is
completely transparent. The value 255 indicates the color is completely opaque. Besides alpha,
each component ranges between 0 and 255, with 0 meaning no contribution for that component,
and 255 meaning 100% contribution. We can create a half-opaque purple color like: int color1 =
Color.argb(127, 255, 0, 255);
in XML resource file, like: #7fff00ff
The colors in Android XML resource files must be formulated as “#” + 6 or 8 bit Hexadecimal
number.
After we define some colors in the XML file, we can reference them by their names, as we did for
strings, or we can use them in Java code like:
int color3 = getResource().getColor(R.color.my_color); or
int color3 = R.color.text_color
The getResources() method returns the ResourceManager class for the current activity, and get
getColor() asks the manager look up a color given a resource ID.
Paint The Paint class holds the style and color information on drawing geometries, text, and
bitmaps. Before we draw something on the screen, we can set color to a Paint via setColor()
method.
Path
The Path class encapsulates multiple contour geometric paths, such as lines, rectangles, circles,
and curves.
Canvas
To draw something, we need to prepare four basic components, including a Bitmap to hold the
pixels, a Canvas to host the draw call, a drawing primitive, and a Paint. The Bitmap is the place
where to draw something, and the Canvasis used to hold the “draw” calls. A drawing primitive can
122
be a Rect, a Circle, a Path, a Text, and a Bitmap. In Android, a display screen istaken up by an
Activity, which hosts a View, which in turn hosts a Canvas. We can draw on the canvas by
overriding the View.onDraw()method. A Canvas object is the only parameter to onDraw()method.
Bitmap: A bitmap graphic file (.png, .jpg, or .gif). Nine-Patch: A PNG file with stretchable regions
to allow image resizing based on content (.9.png).
Layer: A Drawable that manages an array of other Drawables. These are drawn in array order, so
the element with the largest index is be drawn on top.
State: An XML file that references different bitmap graphics for different states (for example, to
use a different image when a button is pressed).
Level: An XML file that defines a drawable that manages a number of alternate Drawables, each
assigned a maximum numerical value. Creates a LevelListDrawable.
Transition: AnXMLfile that defines a drawable that can cross-fade between two drawable
resources.
Inset Drawable: An XML file that defines a drawable that insets another drawable by a specified
distance. This is useful when a View needs a background drawable that is smaller than the View’s
actual bounds.
Clip: An XML file that defines a drawable that clips another Draw- able based on this Drawable’s
current level value. Scale: An XML file that defines a drawable that changes the size of another
Drawable based on its current level value.
Shape: An XML file that defines a geometric shape, including colors and gradients. A drawable
resource is a general concept for a graphic that can be drawn to the screen and that can be retrieved
with Application Programming Interface (API).
123
Chapter Five Multiple Choice Question
1. Which layout is the simplest for arranging UI components in a single row or column in
Android?
A. RelativeLayout B. LinearLayout C. ConstraintLayout D. FrameLayout
2. What is the purpose of the 'wrap_content' attribute in Android layouts?
A. To match the parent's width or height C. To make the view as large as its parent
B. To make the view just large enough to fit its content D. To hide the view
3. Which layout is best suited for creating overlapping UI components?
A. FrameLayout B. LinearLayout C. TableLayout D. GridLayout
4. What does the 'match_parent' value for layout width or height signify?
A. The view will expand to fill the parent C. The view will be hidden
B. The view will wrap around its content D. The view will be centered
5. How do you set the margin of a Button in XML?
A. android:layout_margin="16dp" B. layout_margin="16dp"
B. android:margin="16dp" D. view_margin="16dp"
6. How do you set a background color for a TextView in XML?
A. android:background="@color/colorPrimary" C. android:backgroundColor="blue"
B. android:layout_backgroundColor="@color/colorPrimary" D. all are answer
7. How do you align a Button to the center of its parent in a RelativeLayout?
A. android:layout_centerInParent="true" C. android:layout_alignInCenter="true"
B. android:layout_alignParentCenter="true" D. android:layout_center="true"
8. Which Android widget is used to display a scrollable list of items?
A. TextView B. ListView C. Button D. ImageView
9. What is the function of the Spinner widget in Android?
A. To display a list of selectable options C. To display text
B. To trigger background services D. To display images
10. What does the CheckBox widget allow users to do?
A. Select a single option B. Select multiple options C. Open a new activity D. Submit a
form
11. Which widget is used to create a button that can trigger a user action?
A. TextView B. Button C. ImageButton D. SeekBar
124
12. What is the purpose of the Android ProgressBar widget?
A. To display the progress of an operation C. To display text
B. To show a list of items D. To select multiple options
13. How do you set a click listener for a Button in Android?
A. button.setOnClickListener(this); C. button.addClickListener();
B. button.onClick(this); D. button.clickListener(this);
14. A Button in your app is not responding to clicks. What is the most likely issue?
A. The Button is invisible C. The Button has no click listener
B. The Button is disabled D. The Button is disabled
125