Você está na página 1de 17

Androidfp_19.

fm Page 1 Friday, May 18, 2012 10:32 AM

19
HTML5 Favorite Twitter
Searches App
Browser-Based Mobile Apps with HTML5,
CSS3, JavaScript and Web Storage
Objectives
In this chapter youll:

Implement a web-based version of the Favorite Twitter


Searches app from Chapter 5.

Use HTML5 and CSS3 to implement the interface of a web


app.

Use JavaScript to implement the logic of a web app.

Use HTML5s Web Storage APIs to store key-value pairs of


data that persist between executions of a web app.

Use a CSS reset to remove all browser specific HTMLelement formatting before styling an HTML documents
elements.

Save a shortcut for a web app to your devices home screen


so you can easily launch a web app.

DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 2 Friday, May 18, 2012 10:32 AM

Outline

Chapter 19 HTML5 Favorite Twitter Searches App

19.1 Introduction
19.2 Test-Driving the Favorite Twitter
Searches App
19.3 Technologies Overview

19.5 Building the App


19.5.1 HTML5 Document
19.5.2 CSS
19.5.3 JavaScript

19.6 Wrap-Up

19.1 Introduction
The Favorite Twitter Searches app from Chapter 5 allowed users to save their favorite Twitter search strings with easy-to-remember, user-chosen, short tag names. Users could then
conveniently follow tweets on their favorite topics. In this chapter, we reimplement the Favorite Twitter Searches app as a web app, using HTML5, CSS3 and JavaScript. We assume
that youre already familiar with the basics of web-app development, so we focus only on the
key concepts for implementing the Android app as a web app. Even, if youre not familiar
with web-app development, there are still two key takeaways from reading this chapter:

Its possible to develop apps that run on Android devices without using native
Android/Java development.

The app in this chapter runs on most web browsers, so using HTML5, CSS3 and
JavaScript, you can develop apps that run on a broad range of todays popular
smartphones and tablets.

Note that, although HTML5, CSS3 and JavaScript are portable technologies, you often
must tweak your code to get web apps to work correctly across a wide range of devices.
Favorite Twitter Searches web app executes in the devices browser, as shown for an
Android phone and an iPhone in Fig. 19.1 and for an Android tablet and iPad in Fig. 19.2.
a) Running on an Android Phone

b) Running on an iPhone

Fig. 19.1 | Favorite Twitter Searches web app running on an Android phone and an iPhone.
DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 3 Friday, May 18, 2012 10:32 AM

19.1 Introduction

a) Running on an Android tablet


b) Running on an iPad

Fig. 19.2 | Favorite Twitter Searches web app running on an Android tablet and an iPad.
With HTML5, CSS3 and JavaScript, you can write apps that are portable among a
great variety of desktop and mobile platforms, including Android and iOS (iPhone/iPad).
Running an HTML5 app on your smartphone or tablet is as simple as opening it in the
devices HTML5-compliant web browser. The user can even install a shortcut to your app
on the devices home screen. This chapter demonstrates that you can create a web app with
similar functionality to a native Android app.
As with Chapter 5s version of Favorite Twitter Searches, the users favorite searches
are saved on the device, so theyre immediately available each time the app launches. In
this web-based version, we use HTML5s Web Storage APIs to store key-value data pairs.
Figure 19.1(a) shows the app with several saved searchesthe user can save many searches
and scroll through them in alphabetical order.
HTML5 presents an interesting opportunity for developers. The range of devices that
support HTML5 is enormous compared to those that support native Android. Virtually
all smartphones, tablets and desktop computers have browsers that now support HTML5.
Though HTML5 is still under development, its continuously improving, so youll be able
DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 4 Friday, May 18, 2012 10:32 AM

Chapter 19 HTML5 Favorite Twitter Searches App

to use it to create an increasing variety of powerful web apps. Were now writing HTML5
for Programmers: A Mobile App-Driven Approach in which well convert most of the apps
in this book to HTML5 for use in mobile browsers.

19.2 Test-Driving the Favorite Twitter Searches App


Opening and Running the App
Open the web browser on your Android device or your AVD and navigate to
http://test.deitel.com/androidfp/fts/favoritetwittersearches.html

Adding a New Favorite Search


Enter from:Google in the top HTML5 "text" input element specifying your search subject. Enter Google in the bottom HTML5 "text" input element (Fig. 19.3(a)). This will
be the short name displayed in the Previously Tagged Searches section. Touch the Save
Search Button to save the search and hide the keyboarda Google hyperlink appears under the Previously Tagged Searches heading (Fig. 19.3(b)) and the soft keyboard is automatically dismissed.
a) Entering a Twitter search and search tag

b) App after saving the search and search tag

Fig. 19.3 | Entering a Twitter search.


Editing a Search
To the right of each search hyperlink is a pencil icon ( ). Touch this to reload your query
and tag into the "text" input elements at the top of the app for editing. Lets restrict our
search to tweets since February 1, 2012. Add since:2012-02-01 to the end of the query
(Fig. 19.4). Touching Save Search updates the saved search. [Note: If you change the tag
name, a new search is createdthis is useful if you want to base a new query on a previDRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 5 Friday, May 18, 2012 10:32 AM

19.2 Test-Driving the Favorite Twitter Searches App

Fig. 19.4 | Editing a Twitter search.


ously saved one.] You can delete a search by touching the trash can icon ( ) to the right
of a searchs hyperlink. Touching Clear Saved Searches removes all the searches from the
favorites lista dialog asks you to confirm this first.

Viewing Twitter Search Results


To see the search results touch the Google search query link. This opens the web browser
and accesses the Twitter website to obtain and display the search results (Fig. 19.5).

Fig. 19.5 | Viewing search results.


DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 6 Friday, May 18, 2012 10:32 AM

Chapter 19 HTML5 Favorite Twitter Searches App

Adding a Shortcut to the Devices Home Screen in an Android 2.3.x Device


To add a shortcut to your devices home screen, perform the following steps:
1. Touch the bookmark icon ( ) to the right of the address bar in the browser to
view the list of bookmarks (Fig. 19.6(a)). The web page youre currently viewing
shows up in the upper-left corner of the screen with a star and the word Add displayed on top of the page.
a) List of bookmarks

b) Add bookmark dialog

Fig. 19.6 | Viewing the bookmarks list on an Android 2.3.x phone and adding a bookmark.
2. Touch the word Add to display the Add bookmark dialog (Fig. 19.6(b)). If you
like, you can rename the bookmark. By default the bookmark name is the HTML
documents title.
3. Touch OK to add the bookmark.
4. Once the bookmark is added, long touch it to display the menu in Fig. 19.7(a),
then select the Add shortcut to Home option. The shortcut now appears on your
home screen (Fig. 19.7(b)). Youll see how to specify the shortcut icon in
Section 19.5.1

Adding a Shortcut to the Devices Home Screen in Android 3.0 and Higher
The process of adding a shortcut to the home screen in Android 3.0 and higher is similar:
1. In the browsers address bar, touch the star icon at the right side to display the
Bookmark this page dialog.
2. Customize the bookmarks Label if you wish, then select Home screen from the
Add to menu and press OK.
DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 7 Friday, May 18, 2012 10:32 AM

19.3 Technologies Overview

a) Adding the shortcut to the home screen

b) Shortcut on the home screen

Fig. 19.7 | Adding the shortcut to your home screen.

19.3 Technologies Overview


HTML5, CSS3 and JavaScript
In this web-based version of Favorite Twitter Searches app:
HTML5 is used to define the elements of the web apps interface
CSS3 is used to style those elements
JavaScript is used to implement the logic of the app.
CSS Resets
Each web browser provides its own default formatting for HTML5 elements. To ensure that
you get the same look-and-feel for your app across browsers and devices, its considered a
good practice to perform a CSS reset to remove all the default browser formatting before applying your own CSS to a pages elements. There are various predefined CSS resets that you
can download and use in your own web apps. We chose the public domain one provided at
http://meyerweb.com/eric/tools/css/reset/

which we included in the directory with this apps other files.

Web StoragelocalStorage and sessionStorage


Before HTML5, websites could store only small amounts of text-based information on a
users computer by using cookies. A cookie is a key/value pair in which each key has a corresponding value. The key and value are both strings. Cookies are stored by the browser
on the users computer to maintain client-specific information during and between browser sessions. A website might use a cookie to record user preferences or other information
DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 8 Friday, May 18, 2012 10:32 AM

Chapter 19 HTML5 Favorite Twitter Searches App

that it can retrieve during the clients subsequent visits. For example, a website can retrieve
the users name from a cookie and use it to display a personalized greeting. Similarly, many
websites used cookies during a browsing session to track user-specific information, such as
the contents of an online shopping cart.
When a user visits a website, the browser locates any cookies written by that website
and sends them to the server. Cookies may be accessed only by the web server and scripts
of the website from which the cookies originated (i.e., a cookie set by a script on
amazon.com can be read only by amazon.com servers and scripts). The browser sends these
cookies with every request to the server.
There are several problems with using cookies. One is that theyre extremely limited
in size. Todays web apps often allow users to manipulate large amounts of data, such as
documents or emails. Some web apps allow so-called offline accessfor example, a wordprocessing web app might allow a user to access documents locally, even when the computer is not connected to the Internet. Cookies cannot store large documents. Another
problem is that a user often opens many tabs in the same browser window. If the user
browses the same site from multiple tabs, all of the sites cookies are shared by the pages in
each tab. This could be problematic in web apps that allow the user to purchase items. For
example, if the user is purchasing different items in each tab, with cookies its possible that
the user could accidentally purchase the same item twice.
As of HTML5, there are two new mechanisms for storing key/value pairs that help
eliminate some of the problems with cookies. Web apps can use the window objects
localStorage property to store up to several megabytes of key/value-pair string data on
the users computer and can access that data across browsing sessions and browser tabs.
Unlike cookies, data in the localStorage object is not sent to the web server with each
request. Each website domain (such as deitel.com or google.com) has a separate localStorage objectall the pages from a given domain share one localStorage object. Typically, five megabytes are reserved for each localStorage object, but a web browser can
ask the user if more space should be allocated when the space is full.
Web apps that need access to data only for a browsing session and that must keep that
data separate among multiple tabs can use the window objects sessionStorage property.
Theres a separate sessionStorage object for every browsing session, including separate
web browser tabs and windows that are accessing the same website.

Specifying the Web App Icon and Placing a Shortcut to the Web App on the Devices
Home Screen
As you know, installing an Android app on a device creates an icon for that app in the devices list of applications. You can long touch a home screen do diplay a dialog that allows
you to create a home-screen shortcut to any app. Its also possible to specify an icon for a
web app. When the user places a shortcut to a web app on the home screen, the icon specified for the web app is used. An HTML5 link element specifies the apps icon. At the
end of the test-drive, we showed how to add a web app shortcut to the home screen.

19.4 Designing the GUI


Figure 19.8 shows the web page elements and their id values that are used in the CSS and
JavaScript to style the elements and manipulate them programmatically. The id values are
shown in quotation marks ("").
DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 9 Friday, May 18, 2012 10:32 AM

19.5 Building the App

anchor (a) element


nested in a p element

h1

"query" text input element


nested in a p element

"tag" text input element


nested in a p element

"saveButton"

and "clearButton"
button input elements
nested in a p element

h1

unordered list (ul) thats


dynamically generated and
placed in the "searches"
div; each list item (li)
contains an anchor (a)
element for a hyperlink and
two img elements

Fig. 19.8 | Favorite Twitter Searches web page design.

19.5 Building the App


The Favorite Twitter Searches app consists of three files:

FavoriteTwitterSearches.html

styles.css

FavoriteTwitterSearches.js

(Section 19.5.1) defines the web pages GUI.

(Section 19.5.2) specifies how to format and style the GUI.


(Section 19.5.3) defines the apps logic.

19.5.1 HTML5 Document


Figure 19.9 contains the apps HTML5 document, which is described following the figure.
1
2
3
4
5
6
7
8
9
10
11
12

<!DOCTYPE html>
<!-- FavoriteTwitterSearches.html -->
<!-- Favorite Twitter Searches web app. -->
<html>
<head>
<title>Twitter Searches</title>
<link rel = "stylesheet" type = "text/css" href = "css_reset.css">
<link rel = "stylesheet" type = "text/css" href = "style.css">
<link rel = "apple-touch-icon" href = "icon.png">
<link rel = "apple-touch-icon-precomposed" href = "icon.png">
<script src = "FavoriteTwitterSearches.js"></script>

Fig. 19.9 | HTML5 document for the Favorite Twitter Searches web app. (Part 1 of 2.)
DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 10 Friday, May 18, 2012 10:32 AM

10

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

Chapter 19 HTML5 Favorite Twitter Searches App

<meta name = "viewport"


content = "user-scalable=no, width=device-width">
</head>
<body>
<h1>Favorite Twitter Searches</h1>
<p id = "welcomeMessage"></p>
<form action = "#">
<p>
<a href = "https://dev.twitter.com/docs/using-search">
List of Twitter search operators</a>
</p>
<p>
<input id = "query" type = "text"
placeholder = "Enter Twitter search query">
</p>
<p>
<input id = "tag" type = "text" placeholder = "Tag your query">
</p>
<p>
<input type = "button" value = "Save Search" id = "saveButton">
<input type = "button" value = "Clear Saved Searches"
id = "clearButton">
</p>
</form>
<h1>Previously Tagged Searches</h1>
<div id = "searches"></div>
</body>
</html>

Fig. 19.9 | HTML5 document for the Favorite Twitter Searches web app. (Part 2 of 2.)
ElementLoading the CSS Files
In the documents head element, the link element at line 8 loads the css_reset.css file
that we downloaded from http://meyerweb.com/eric/tools/css/reset/. Loading this
file applies the CSS reset that removes the default HTML element formatting performed
by the web browser. Line 9 loads our CSS styles for this app, which we discuss in
Section 19.5.2.
head

ElementSpecifying Home Screen Icons


Lines 10 and 11 specify link elements with the rel attribute values "apple-touch-icon"
and "apple-touch-icon-precomposed", respectively. These were originally created by Apple to enable web-app developers to specify home screen icons for shortcuts to their apps
that ran in the Safari web browser on iPhones and iPads. These link elements are now
widely supported in other browsers as well, including the Android browser. Apple automatically applies styling to the icon specified with "apple-touch-icon" (such as rounded corners and a glossy effect). The icon specified with "apple-touch-icon-precomposed" is
used without modification on Apple devices (i.e., no additional styling is applied by the operating system), allowing web-app developers complete control over the look-and-feel of
the icon image. For Android, you need only the link element in line 10. One of the benefits
of implementing mobile web apps is that they can execute across a wide variety of mobile
devices, so its a good practice to include the link elements in lines 10 and 11.
head

DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 11 Friday, May 18, 2012 10:32 AM

19.5 Building the App

11

ElementLoading the JavaScript file


Line 12 specifies the JavaScript file to load with the app. This file (Section 19.5.3) contains
the code that implements the apps logic.
head

ElementUsing a meta Element to Configure the Viewport


The meta element with the name attribute set to "viewport" (lines 1314) configures the
area in which this apps web page is displayed. Like the link elements with the rel attribute values "apple-touch-icon" and "apple-touch-icon-precomposed", this meta element was originally created by Apple for the mobile Safari web browser and is now widely
supported by other mobile web browsers, including Androids.
By configuring the viewport, you can make your web apps look better on small screens.
By default, the viewport is typically much wider than a smartphones screen and the user
must zoom and pan to view the web page properly. In this case, we set the viewport so that
the user cannot scale it (e.g., to zoom in and out) and so that the width of the viewport is the
screens width. Any elements that we set with CSS to match the device width, will now scale
to fill the screen width. For complete details on configuring the viewport, see
head

http://developer.android.com/guide/webapps/targeting.html

Element of the HTML5 Document


The HTML5 document provides a form (lines 1936) that allows the user to enter new
searches. Previously tagged searches are displayed in the div named searches (line 38).
body

19.5.2 CSS
Figure 19.10 contains the CSS styles for this app. We overview the styles below the figure.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

body { font-family: sans-serif; font-size: 1em; margin: 10px;}


h1 { font-weight: bold; font-size: 1.25em; margin: 1em 0 .5em 0; }
#welcomeMessage { margin-bottom: .5em; font-weight: bold; }
input[type = "text"] { width: 100%; font-size: 1.25em;
margin-top: .25em; }
ul { width: 100%; }
span { margin-left: 10px; display: inline-block; width: 100%; }
li { height: 60px; width: 100%; font-size: 1.25em; }
li a { display: block; float: left; width: 50%; position: relative;
top: 50%; margin-left:1em; margin-top: -0.625em;
text-decoration: none; }
li:first-child { border-top: 1px solid grey; }
li:nth-child(even) { background-color: lightyellow;
border-bottom: 1px solid grey; }
li:nth-child(odd) { background-color: lightblue;
border-bottom: 1px solid grey; }

Fig. 19.10 | Styles used in the Favorite Twitter Searches app.


The styles in lines 15 perform the following tasks:

Line 1 defines the bodys base font and font size and the margin around the entire
element. The font settings are inherited by the nested elements in the body.
For information on CSS measurement units visit, www.w3.org/TR/css3-values/.

body

DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 12 Friday, May 18, 2012 10:32 AM

12

Chapter 19 HTML5 Favorite Twitter Searches App

Line 2 defines font style and margins for the h1 elements in lines 17 and 37 of
Fig. 19.10.

Line 3 defines the style for the


Fig. 19.10.

Lines 45 use a CSS3 attribute selector to select all input elements that have the
type "text" and sets their width to 100%. These elements also have a larger font
size and a top margin to separate them from other elements.

welcomeMessage

paragraph at line 18 of

The styles in lines 616 apply to an unordered list (ul) and its nested elements. These
are generated dynamically as the user creates saved searches.

Line 6 defines the width of the ul element that will display the saved searches list.

Line 7 defines the span styleeach link that represents a saved search is displayed
in a span. To specify the width, we set the display property of the spans to
inline-block.

Line 8 defines the basic formatting for each list item (li) element thats displayed
in the saved searches list.

Lines 911 specify the style for the anchor (a) elements displayed in the saved
searches list.

Line 12 specifies a :first-child selector thats used to select the first list item
(li) in the list of saved searches. This allows us to specify a custom style for the
first list itemin this case, we specify a border for the top of the list item.

Lines 1314 and 1516 use :nth-child selectors to specify the styles of the odd
(first, third, fifth, etc.) and even (second, fourth, sixth, etc.) list items, respectively. We use these selectors or alternate the background colors of the saved searches.

19.5.3 JavaScript
Figures 19.1119.16 present the JavaScript for the Favorite Twitter Searches app. Line 106
in Fig. 19.16 registers the web pages load event listener. When the page loads, function
start (Fig. 19.11, lines 714) registers the event handlers for the web pages buttons
(Fig. 19.9, lines 3234) and calls function loadSearches. The script variable tags (line 4)
stores an array of the keys in the key/value pairs that represent the searches.
1
2
3
4
5
6
7
8
9
10

// FavoriteTwitterSearchs.js
// Storing and retrieving key-value pairs using
// HTML5 localStorage and sessionStorage
var tags; // array of tags for queries
// register event handlers then load searches
function start()
{
var saveButton = document.getElementById( "saveButton" );
saveButton.addEventListener( "click", saveSearch, false );

Fig. 19.11 | Storing and retrieving key/value pairs using HTML5 localStorage and sessionStorage.

(Part 1 of 2.)
DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 13 Friday, May 18, 2012 10:32 AM

19.5 Building the App

11
12
13
14
15

13

var clearButton = document.getElementById( "clearButton" );


clearButton.addEventListener( "click", clearAllSearches, false );
loadSearches(); // load the previously saved searches
} // end function start

Fig. 19.11 | Storing and retrieving key/value pairs using HTML5 localStorage and sessionStorage.

(Part 2 of 2.)

Function loadSearches
Function loadSearches (Fig. 19.12) creates and displays a list of the previously saved
searches, if any. Line 19 uses the windows sessionStorage object to determine whether
the user has already visited the page during this browsing session. The getItem method
receives as its argument the key in a key/value pair. If the key exists, getItem returns the
corresponding string value; otherwise, it returns null. If this is the users first visit to the
page during this browsing session, the key "herePreviously" will not exist in the sessionStorage object. In this case, line 21 uses the setItem method to set the key
"herePreviously" to the string "true", then lines 2223 display a welcome message in
the welcomeMessage paragraph element.
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

// loads previously saved searches and displays them in the page


function loadSearches()
{
if ( !window.sessionStorage.getItem( "herePreviously" ) )
{
sessionStorage.setItem( "herePreviously", "true" );
document.getElementById( "welcomeMessage" ).innerHTML =
"Welcome to the Favorite Twitter Searches App";
} // end if
var length = localStorage.length; // number of key-value pairs
tags = []; // create empty array
// load all keys
for (var i = 0; i < length; ++i)
{
tags[i] = localStorage.key(i);
} // end for
tags.sort(
function( string1, string2 )
{
var comparisonResult = 0;
string1 = string1.toUpperCase();
string2 = string2.toUpperCase();
if ( string1 > string2 )
comparisonResult = 1;

Fig. 19.12 | Storing and retrieving key/value pairs using HTML5 localStorage and sessionStorage.

(Part 1 of 2.)
DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 14 Friday, May 18, 2012 10:32 AM

14

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

Chapter 19 HTML5 Favorite Twitter Searches App

if ( string1 < string2 )


comparisonResult = -1;
return comparisonResult;
} // end function
); // sort the keys
var markup = "<ul>"; // used to store search link markup
var url = "http://search.twitter.com/search?q=";
// build list of links
for (var tag in tags)
{
var query = url + localStorage.getItem(tags[tag]);
markup += "<li><a href = '" + query + "'>" + tags[tag] + "</a>" +
"<img id = '" + tags[tag] + "' src = 'edit.png' alt = '" +
"Edit search: " + tags[tag] + "' onclick = 'editTag(id)'>" +
"<img id = '" + tags[tag] + "' src = 'delete.png' alt = '" +
"Delete search: " + tags[tag] + "' onclick = 'deleteTag(id)'>";
} // end for
markup += "</ul>";
document.getElementById("searches").innerHTML = markup;
} // end function loadSearches

Fig. 19.12 | Storing and retrieving key/value pairs using HTML5 localStorage and sessionStorage.

(Part 2 of 2.)

Next, line 26 gets the localStorage objects length, which represents the number of
key/value pairs stored. Line 27 creates an array and assigns it to the script variable tags,
then lines 3033 get the keys from the localStorage object and store them in the tags
array. Method key (line 32) receives an index as an argument and returns the corresponding key.
Lines 3550 sort the tags array, so that we can display the searches in alphabetical
order by tag name (i.e., key). Lines 3649 define an anonymous JavaScript comparison
function thats passed as an argument to the arrays sort method. The anonymous function receives two parameters representing the strings to compare and performs a case-insensitive comparison. The function returns 1 if the first string is greater than the second, 0 if
theyre equal or -1 if the first string is less than the second, and array function sort uses
the returned value to determine the sorting order.
Lines 5266 build the unordered list of links representing the saved searches. Line 58
calls the localStorage objects getItem method to obtain the search string for a given tag
and appends the search string to the Twitter search URL (line 53). Then lines 5963 create
a list item for that search. The list item contains a hyperlink to load a web page that performs
the search and two img elements that the user can touch to edit or delete the saved search.
For simplicity, lines 61 and 63 use the onclick attributes of the img elements to set their
event handlersthis is an older mechanism for registering event handlers. To register these
with the elements addEventListener method, we could dynamically locate the elements in
DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 15 Friday, May 18, 2012 10:32 AM

19.5 Building the App

15

the page after we create them, then register the event handlers. Also, notice that each event
handler is receiving the img elements id as an argumentthis enables the event handler to
use the id value when handling the event. [Note: The localStorage and sessionStorage
properties and methods we discuss throughout this section apply to both objects.]

Function clearAllSearches
Function clearAllSearches (Fig. 19.13) is called when the user touches the Clear Saved
Searches button. If the user confirms that the saved searches should be cleared, line 75
calls the clear method of the localStorage object to remove all key/value pairs from the
object. We then call loadSearches to refresh the list of saved searches in the web page.
70
71
72
73
74
75
76
77
78
79

// deletes all key-value pairs from localStorage


function clearAllSearches()
{
if ( confirm("Are you sure?") )
{
localStorage.clear();
loadSearches(); // reload searches
}
} // end function clearAllSearches

Fig. 19.13 | Function clearAllSearches allows the user to delete all previously saved
searches.

Function saveSearch
Function saveSearch (Fig. 19.14) is called when the user touches Save Search to save a
search. Line 85 uses the setItem method to store a key/value pair in the localStorage
object. If the key already exits, setItem replaces the corresponding value; otherwise, it creates a new key/value pair. We then call loadSearches to refresh the list of saved searches
in the web page.
80
81
82
83
84
85
86
87
88
89
90

// saves a newly tagged search into localStorage


function saveSearch()
{
var query = document.getElementById("query");
var tag = document.getElementById("tag");
localStorage.setItem(tag.value, query.value);
tag.value = ""; // clear tag input
query.value = ""; // clear query input
loadSearches(); // reload searches
} // end function saveSearch

Fig. 19.14 | Function saveSearch saves a key/value pair representing a search.


Function deleteTag
Function deleteTag (Fig. 19.15) is called when the user touches the delete (trash can)
icon next to a particular search. The function receives the tag representing the key/value
DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 16 Friday, May 18, 2012 10:32 AM

16

Chapter 19 HTML5 Favorite Twitter Searches App

pair to delete, which we set in line 63 (Fig. 19.12) as the imgs id. Line 94 uses the
removeItem method to remove a key/value pair from the localStorage object. We then
call loadSearches to refresh the list of saved searches in the web page.
91
92
93
94
95
96
97

// deletes a specific key-value pair from localStorage


function deleteTag( tag )
{
localStorage.removeItem( tag );
loadSearches(); // reload searches
} // end function deleteTag

Fig. 19.15 | Function deleteTag allows the user to delete a previously saved search.
Function editTag
Function editTag (Fig. 19.16) is called when the user touches the edit (pencil) icon next
to a particular search. The function receives the tag representing the key/value pair to edit,
which we set in line 61 (Fig. 19.12) as the imgs id. In this case, we display the corresponding key/value pairs contents in the input elements with the ids "tag" and "query", respectively, so the user can edit them. Line 101 uses the [] operator to access the value for
a specified key (tag)this performs the same task as calling getItem on the localStorage
object. We then call loadSearches to refresh the list of saved searches in the web page.
98
99
100
101
102
103
104
105
106

// display existing tagged query for editing


function editTag( tag )
{
document.getElementById("query").value = localStorage[ tag ];
document.getElementById("tag").value = tag;
loadSearches(); // reload searches
} // end function editTag
window.addEventListener( "load", start, false );

Fig. 19.16 | Function editTag allows the user to edit a previously saved search.

19.6 Wrap-Up
In this chapter, we reimplemented the Favorite Twitter Searches app as a web app to demonstrate that its possible to create apps without using native Android/Java development.
You saw that with HTML5, CSS3 and JavaScript, you can write apps that are portable
among a great variety of platforms, including the smartphone/tablet platforms for Android
and iPhone/iPad. We used HTML5 elements to define the web apps interface, CSS3 to
style those elements and JavaScript to implement the apps logic.
You learned that each web browser provides its own default formatting for HTML5
elements. To ensure the same look-and-feel for web apps across browsers and devices, we
used the CSS reset capability to remove all the default browser formatting before applying
our own CSS to the pages elements.

DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.

Androidfp_19.fm Page 17 Friday, May 18, 2012 10:32 AM

19.6 Wrap-Up

17

You learned that HTML5 provides APIs for storing key/value pairs that help eliminate some of the problems with the older browser cookie technology. You used the window
objects localStorage object to store key/value-pair string data on the users computer, so
that data could be accessed across browsing sessions and browser tabs. You learned that,
unlike cookies, data in the localStorage object is not sent to the web server with each
request and that each website domain (such as deitel.com or google.com) has a separate
localStorage object that is shared by all the web pages from that domain. You also
learned that the localStorage object can store several megabytes of data by default.
In addition, you used the window objects sessionStorage property to store key/value
pairs that were needed only for the current browsing session. You learned that theres a
separate sessionStorage object for every browsing session, including separate web
browser tabs. Finally, you specified an icon for the web app so that when a user saves a
shortcut to the app on a devices home screen, the icon specified for the web app is used.

DRAFT: Copyright 19922012 by Deitel & Associates, Inc. All Rights Reserved.