Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32...

17
19 DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved. HTML5 Favorite Twitter Searches App Browser-Based Mobile Apps with HTML5, CSS3, JavaScript and Web Storage Objectives In this chapter you’ll: 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 HTML5’s 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 HTML- element formatting before styling an HTML document’s elements. Save a shortcut for a web app to your device’s home screen so you can easily launch a web app. = Androidfp_19.fm Page 1 Friday, May 18, 2012 10:32 AM

Transcript of Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32...

Page 1: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

19

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

HTML5 Favorite Twitter Searches App

Browser-Based Mobile Apps with HTML5, CSS3, JavaScript and Web Storage

O b j e c t i v e sIn this chapter you’ll:

■ 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 HTML5’s 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 HTML-element formatting before styling an HTML document’s elements.

■ Save a shortcut for a web app to your device’s home screen so you can easily launch a web app.

=

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

Page 2: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

2 Chapter 19 HTML5 Favorite Twitter Searches App

Ou

tlin

e

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

19.1 IntroductionThe Favorite Twitter Searches app from Chapter 5 allowed users to save their favorite Twit-ter search strings with easy-to-remember, user-chosen, short tag names. Users could thenconveniently follow tweets on their favorite topics. In this chapter, we reimplement the Fa-vorite Twitter Searches app as a web app, using HTML5, CSS3 and JavaScript. We assumethat you’re already familiar with the basics of web-app development, so we focus only on thekey concepts for implementing the Android app as a web app. Even, if you’re not familiarwith web-app development, there are still two key takeaways from reading this chapter:

• It’s possible to develop apps that run on Android devices without using nativeAndroid/Java development.

• The app in this chapter runs on most web browsers, so using HTML5, CSS3 andJavaScript, you can develop apps that run on a broad range of today’s popularsmartphones and tablets.

Note that, although HTML5, CSS3 and JavaScript are portable technologies, you oftenmust tweak your code to get web apps to work correctly across a wide range of devices.

Favorite Twitter Searches web app executes in the device’s browser, as shown for anAndroid phone and an iPhone in Fig. 19.1 and for an Android tablet and iPad in Fig. 19.2.

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 Document19.5.2 CSS19.5.3 JavaScript

19.6 Wrap-Up

Fig. 19.1 | Favorite Twitter Searches web app running on an Android phone and an iPhone.

a) Running on an Android Phone b) Running on an iPhone

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

Page 3: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

19.1 Introduction 3

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

With HTML5, CSS3 and JavaScript, you can write apps that are portable among agreat 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 thedevice’s HTML5-compliant web browser. The user can even install a shortcut to your appon the device’s home screen. This chapter demonstrates that you can create a web app withsimilar functionality to a native Android app.

As with Chapter 5’s version of Favorite Twitter Searches, the user’s favorite searchesare saved on the device, so they’re immediately available each time the app launches. Inthis web-based version, we use HTML5’s Web Storage APIs to store key-value data pairs.Figure 19.1(a) shows the app with several saved searches—the user can save many searchesand scroll through them in alphabetical order.

HTML5 presents an interesting opportunity for developers. The range of devices thatsupport HTML5 is enormous compared to those that support native Android. Virtuallyall smartphones, tablets and desktop computers have browsers that now support HTML5.Though HTML5 is still under development, it’s continuously improving, so you’ll be able

Fig. 19.2 | Favorite Twitter Searches web app running on an Android tablet and an iPad.

a) Running on an Android tablet

b) Running on an iPad

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

Page 4: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

4 Chapter 19 HTML5 Favorite Twitter Searches App

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

to use it to create an increasing variety of powerful web apps. We’re now writing HTML5for Programmers: A Mobile App-Driven Approach in which we’ll convert most of the appsin this book to HTML5 for use in mobile browsers.

19.2 Test-Driving the Favorite Twitter Searches AppOpening and Running the AppOpen the web browser on your Android device or your AVD and navigate to

Adding a New Favorite SearchEnter from:Google in the top HTML5 "text" input element specifying your search sub-ject. Enter Google in the bottom HTML5 "text" input element (Fig. 19.3(a)). This willbe the short name displayed in the Previously Tagged Searches section. Touch the SaveSearch Button to save the search and hide the keyboard—a Google hyperlink appears un-der the Previously Tagged Searches heading (Fig. 19.3(b)) and the soft keyboard is auto-matically dismissed.

Editing a SearchTo the right of each search hyperlink is a pencil icon ( ). Touch this to reload your queryand tag into the "text" input elements at the top of the app for editing. Let’s restrict oursearch 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 tagname, a new search is created—this is useful if you want to base a new query on a previ-

http://test.deitel.com/androidfp/fts/favoritetwittersearches.html

Fig. 19.3 | Entering a Twitter search.

a) Entering a Twitter search and search tag b) App after saving the search and search tag

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

Page 5: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

19.2 Test-Driving the Favorite Twitter Searches App 5

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

ously saved one.] You can delete a search by touching the trash can icon ( ) to the rightof a search’s hyperlink. Touching Clear Saved Searches removes all the searches from thefavorites list—a dialog asks you to confirm this first.

Viewing Twitter Search ResultsTo see the search results touch the Google search query link. This opens the web browserand accesses the Twitter website to obtain and display the search results (Fig. 19.5).

Fig. 19.4 | Editing a Twitter search.

Fig. 19.5 | Viewing search results.

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

Page 6: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

6 Chapter 19 HTML5 Favorite Twitter Searches App

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

Adding a Shortcut to the Device’s Home Screen in an Android 2.3.x DeviceTo add a shortcut to your device’s home screen, perform the following steps:

1. Touch the bookmark icon ( ) to the right of the address bar in the browser toview the list of bookmarks (Fig. 19.6(a)). The web page you’re currently viewingshows up in the upper-left corner of the screen with a star and the word Add dis-played on top of the page.

2. Touch the word Add to display the Add bookmark dialog (Fig. 19.6(b)). If youlike, you can rename the bookmark. By default the bookmark name is the HTMLdocument’s 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 yourhome screen (Fig. 19.7(b)). You’ll see how to specify the shortcut icon inSection 19.5.1

Adding a Shortcut to the Device’s Home Screen in Android 3.0 and HigherThe process of adding a shortcut to the home screen in Android 3.0 and higher is similar:

1. In the browser’s address bar, touch the star icon at the right side to display theBookmark this page dialog.

2. Customize the bookmark’s Label if you wish, then select Home screen from theAdd to menu and press OK.

Fig. 19.6 | Viewing the bookmarks list on an Android 2.3.x phone and adding a bookmark.

a) List of bookmarks b) Add bookmark dialog

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

Page 7: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

19.3 Technologies Overview 7

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

19.3 Technologies OverviewHTML5, CSS3 and JavaScriptIn this web-based version of Favorite Twitter Searches app:

• HTML5 is used to define the elements of the web app’s interface

• CSS3 is used to style those elements

• JavaScript is used to implement the logic of the app.

CSS ResetsEach web browser provides its own default formatting for HTML5 elements. To ensure thatyou get the same look-and-feel for your app across browsers and devices, it’s considered agood practice to perform a CSS reset to remove all the default browser formatting before ap-plying your own CSS to a page’s elements. There are various predefined CSS resets that youcan download and use in your own web apps. We chose the public domain one provided at

which we included in the directory with this app’s other files.

Web Storage—localStorage and sessionStorageBefore HTML5, websites could store only small amounts of text-based information on auser’s computer by using cookies. A cookie is a key/value pair in which each key has a cor-responding value. The key and value are both strings. Cookies are stored by the browseron the user’s computer to maintain client-specific information during and between brows-er sessions. A website might use a cookie to record user preferences or other information

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

http://meyerweb.com/eric/tools/css/reset/

a) Adding the shortcut to the home screen b) Shortcut on the home screen

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

Page 8: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

8 Chapter 19 HTML5 Favorite Twitter Searches App

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

that it can retrieve during the client’s subsequent visits. For example, a website can retrievethe user’s name from a cookie and use it to display a personalized greeting. Similarly, manywebsites used cookies during a browsing session to track user-specific information, such asthe contents of an online shopping cart.

When a user visits a website, the browser locates any cookies written by that websiteand sends them to the server. Cookies may be accessed only by the web server and scriptsof the website from which the cookies originated (i.e., a cookie set by a script onamazon.com can be read only by amazon.com servers and scripts). The browser sends thesecookies with every request to the server.

There are several problems with using cookies. One is that they’re extremely limitedin size. Today’s web apps often allow users to manipulate large amounts of data, such asdocuments or emails. Some web apps allow so-called offline access—for example, a word-processing web app might allow a user to access documents locally, even when the com-puter is not connected to the Internet. Cookies cannot store large documents. Anotherproblem is that a user often opens many tabs in the same browser window. If the userbrowses the same site from multiple tabs, all of the site’s cookies are shared by the pages ineach tab. This could be problematic in web apps that allow the user to purchase items. Forexample, if the user is purchasing different items in each tab, with cookies it’s possible thatthe user could accidentally purchase the same item twice.

As of HTML5, there are two new mechanisms for storing key/value pairs that helpeliminate some of the problems with cookies. Web apps can use the window object’slocalStorage property to store up to several megabytes of key/value-pair string data onthe user’s 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 eachrequest. Each website domain (such as deitel.com or google.com) has a separate local-Storage object—all the pages from a given domain share one localStorage object. Typ-ically, five megabytes are reserved for each localStorage object, but a web browser canask 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 thatdata separate among multiple tabs can use the window object’s sessionStorage property.There’s a separate sessionStorage object for every browsing session, including separateweb 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 Device’s Home ScreenAs you know, installing an Android app on a device creates an icon for that app in the de-vice’s list of applications. You can long touch a home screen do diplay a dialog that allowsyou to create a home-screen shortcut to any app. It’s also possible to specify an icon for aweb app. When the user places a shortcut to a web app on the home screen, the icon spec-ified for the web app is used. An HTML5 link element specifies the app’s icon. At theend of the test-drive, we showed how to add a web app shortcut to the home screen.

19.4 Designing the GUIFigure 19.8 shows the web page elements and their id values that are used in the CSS andJavaScript to style the elements and manipulate them programmatically. The id values areshown in quotation marks ("").

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

Page 9: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

19.5 Building the App 9

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

19.5 Building the AppThe Favorite Twitter Searches app consists of three files:

• FavoriteTwitterSearches.html (Section 19.5.1) defines the web page’s GUI.

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

• FavoriteTwitterSearches.js (Section 19.5.3) defines the app’s logic.

19.5.1 HTML5 DocumentFigure 19.9 contains the app’s HTML5 document, which is described following the fig-ure.

Fig. 19.8 | Favorite Twitter Searches web page design.

1 <!DOCTYPE html>23 <!-- FavoriteTwitterSearches.html -->4 <!-- Favorite Twitter Searches web app. -->5 <html>6 <head>7 <title>Twitter Searches</title>8 <link rel = "stylesheet" type = "text/css" href = "css_reset.css">9 <link rel = "stylesheet" type = "text/css" href = "style.css">

10 11 12 <script src = "FavoriteTwitterSearches.js"></script>

Fig. 19.9 | HTML5 document for the Favorite Twitter Searches web app. (Part 1 of 2.)

"query" text input elementnested in a p element

"tag" text input element nested in a p element

"saveButton"and "clearButton"

button input elementsnested in a p element

anchor (a) elementnested in a p element h1

unordered list (ul) that’sdynamically generated andplaced in the "searches"

div; each list item (li)contains an anchor (a)

element for a hyperlink andtwo img elements

h1

<link rel = "apple-touch-icon" href = "icon.png"> <link rel = "apple-touch-icon-precomposed" href = "icon.png">

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

Page 10: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

10 Chapter 19 HTML5 Favorite Twitter Searches App

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

head Element—Loading the CSS FilesIn the document’s head element, the link element at line 8 loads the css_reset.css filethat we downloaded from http://meyerweb.com/eric/tools/css/reset/. Loading thisfile applies the CSS reset that removes the default HTML element formatting performedby the web browser. Line 9 loads our CSS styles for this app, which we discuss inSection 19.5.2.

head Element—Specifying Home Screen IconsLines 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 Ap-ple to enable web-app developers to specify home screen icons for shortcuts to their appsthat ran in the Safari web browser on iPhones and iPads. These link elements are nowwidely supported in other browsers as well, including the Android browser. Apple automat-ically applies styling to the icon specified with "apple-touch-icon" (such as rounded cor-ners and a glossy effect). The icon specified with "apple-touch-icon-precomposed" isused without modification on Apple devices (i.e., no additional styling is applied by the op-erating system), allowing web-app developers complete control over the look-and-feel ofthe icon image. For Android, you need only the link element in line 10. One of the benefitsof implementing mobile web apps is that they can execute across a wide variety of mobiledevices, so it’s a good practice to include the link elements in lines 10 and 11.

13 14 15 </head>16 <body>17 <h1>Favorite Twitter Searches</h1>18 <p id = "welcomeMessage"></p>19 <form action = "#">20 <p>21 <a href = "https://dev.twitter.com/docs/using-search">22 List of Twitter search operators</a>23 </p>24 <p>25 <input id = "query" type = "text" 26 placeholder = "Enter Twitter search query">27 </p>28 <p>29 <input id = "tag" type = "text" placeholder = "Tag your query">30 </p>31 <p>32 <input type = "button" value = "Save Search" id = "saveButton">33 <input type = "button" value = "Clear Saved Searches" 34 id = "clearButton">35 </p>36 </form>37 <h1>Previously Tagged Searches</h1>38 <div id = "searches"></div>39 </body>40 </html>

Fig. 19.9 | HTML5 document for the Favorite Twitter Searches web app. (Part 2 of 2.)

<meta name = "viewport" content = "user-scalable=no, width=device-width">

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

Page 11: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

19.5 Building the App 11

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

head Element—Loading the JavaScript fileLine 12 specifies the JavaScript file to load with the app. This file (Section 19.5.3) containsthe code that implements the app’s logic.

head Element—Using a meta Element to Configure the ViewportThe meta element with the name attribute set to "viewport" (lines 13–14) configures thearea in which this app’s web page is displayed. Like the link elements with the rel attri-bute values "apple-touch-icon" and "apple-touch-icon-precomposed", this meta ele-ment was originally created by Apple for the mobile Safari web browser and is now widelysupported by other mobile web browsers, including Android’s.

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 smartphone’s screen and the usermust zoom and pan to view the web page properly. In this case, we set the viewport so thatthe user cannot scale it (e.g., to zoom in and out) and so that the width of the viewport is thescreen’s width. Any elements that we set with CSS to match the device width, will now scaleto fill the screen width. For complete details on configuring the viewport, see

body Element of the HTML5 DocumentThe HTML5 document provides a form (lines 19–36) that allows the user to enter newsearches. Previously tagged searches are displayed in the div named searches (line 38).

19.5.2 CSS Figure 19.10 contains the CSS styles for this app. We overview the styles below the figure.

The styles in lines 1–5 perform the following tasks:

• Line 1 defines the body’s base font and font size and the margin around the entirebody 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/.

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

1 body { font-family: sans-serif; font-size: 1em; margin: 10px;}2 h1 { font-weight: bold; font-size: 1.25em; margin: 1em 0 .5em 0; }3 #welcomeMessage { margin-bottom: .5em; font-weight: bold; }4 input[type = "text"] { width: 100%; font-size: 1.25em; 5 margin-top: .25em; }6 ul { width: 100%; }7 span { margin-left: 10px; display: inline-block; width: 100%; }8 li { height: 60px; width: 100%; font-size: 1.25em; }9 li a { display: block; float: left; width: 50%; position: relative;

10 top: 50%; margin-left:1em; margin-top: -0.625em; 11 text-decoration: none; }12 li:first-child { border-top: 1px solid grey; }13 li:nth-child(even) { background-color: lightyellow;14 border-bottom: 1px solid grey; }15 li:nth-child(odd) { background-color: lightblue; 16 border-bottom: 1px solid grey; }

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

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

Page 12: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

12 Chapter 19 HTML5 Favorite Twitter Searches App

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

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

• Line 3 defines the style for the welcomeMessage paragraph at line 18 ofFig. 19.10.

• Lines 4–5 use a CSS3 attribute selector to select all input elements that have thetype "text" and sets their width to 100%. These elements also have a larger fontsize and a top margin to separate them from other elements.

The styles in lines 6–16 apply to an unordered list (ul) and its nested elements. Theseare 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 style—each link that represents a saved search is displayedin a span. To specify the width, we set the display property of the spans toinline-block.

• Line 8 defines the basic formatting for each list item (li) element that’s displayedin the saved searches list.

• Lines 9–11 specify the style for the anchor (a) elements displayed in the savedsearches list.

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

• Lines 13–14 and 15–16 use :nth-child selectors to specify the styles of the odd(first, third, fifth, etc.) and even (second, fourth, sixth, etc.) list items, respective-ly. We use these selectors or alternate the background colors of the saved searches.

19.5.3 JavaScript Figures 19.11–19.16 present the JavaScript for the Favorite Twitter Searches app. Line 106in Fig. 19.16 registers the web page’s load event listener. When the page loads, functionstart (Fig. 19.11, lines 7–14) registers the event handlers for the web page’s buttons(Fig. 19.9, lines 32–34) 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 // FavoriteTwitterSearchs.js2 // Storing and retrieving key-value pairs using 3 // HTML5 localStorage and sessionStorage4 var tags; // array of tags for queries56 // register event handlers then load searches7 function start()8 {9 var saveButton = document.getElementById( "saveButton" );

10 saveButton.addEventListener( "click", saveSearch, false );

Fig. 19.11 | Storing and retrieving key/value pairs using HTML5 localStorage and session-Storage. (Part 1 of 2.)

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

Page 13: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

19.5 Building the App 13

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

Function loadSearches Function loadSearches (Fig. 19.12) creates and displays a list of the previously savedsearches, if any. Line 19 uses the window’s sessionStorage object to determine whetherthe user has already visited the page during this browsing session. The getItem methodreceives as its argument the key in a key/value pair. If the key exists, getItem returns thecorresponding string value; otherwise, it returns null. If this is the user’s first visit to thepage during this browsing session, the key "herePreviously" will not exist in the ses-sionStorage object. In this case, line 21 uses the setItem method to set the key"herePreviously" to the string "true", then lines 22–23 display a welcome message inthe welcomeMessage paragraph element.

11 var clearButton = document.getElementById( "clearButton" );12 clearButton.addEventListener( "click", clearAllSearches, false );13 loadSearches(); // load the previously saved searches14 } // end function start15

16 // loads previously saved searches and displays them in the page17 function loadSearches() 18 {19 if ( !window.sessionStorage.getItem( "herePreviously" ) )20 {21 22 document.getElementById( "welcomeMessage" ).innerHTML = 23 "Welcome to the Favorite Twitter Searches App";24 } // end if2526 27 tags = []; // create empty array2829 // load all keys30 for (var i = 0; i < length; ++i) 31 {32 33 } // end for3435 tags.sort(36 function( string1, string2 )37 {38 var comparisonResult = 0;39 string1 = string1.toUpperCase();40 string2 = string2.toUpperCase();4142 if ( string1 > string2 ) 43 comparisonResult = 1;

Fig. 19.12 | Storing and retrieving key/value pairs using HTML5 localStorage and session-Storage. (Part 1 of 2.)

Fig. 19.11 | Storing and retrieving key/value pairs using HTML5 localStorage and session-Storage. (Part 2 of 2.)

sessionStorage.setItem( "herePreviously", "true" );

var length = localStorage.length; // number of key-value pairs

tags[i] = localStorage.key(i);

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

Page 14: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

14 Chapter 19 HTML5 Favorite Twitter Searches App

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

Next, line 26 gets the localStorage object’s length, which represents the number ofkey/value pairs stored. Line 27 creates an array and assigns it to the script variable tags,then lines 30–33 get the keys from the localStorage object and store them in the tagsarray. Method key (line 32) receives an index as an argument and returns the corre-sponding key.

Lines 35–50 sort the tags array, so that we can display the searches in alphabeticalorder by tag name (i.e., key). Lines 36–49 define an anonymous JavaScript comparisonfunction that’s passed as an argument to the array’s sort method. The anonymous func-tion receives two parameters representing the strings to compare and performs a case-insen-sitive comparison. The function returns 1 if the first string is greater than the second, 0 ifthey’re equal or -1 if the first string is less than the second, and array function sort usesthe returned value to determine the sorting order.

Lines 52–66 build the unordered list of links representing the saved searches. Line 58calls the localStorage object’s getItem method to obtain the search string for a given tagand appends the search string to the Twitter search URL (line 53). Then lines 59–63 createa list item for that search. The list item contains a hyperlink to load a web page that performsthe 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 theirevent handlers—this is an older mechanism for registering event handlers. To register thesewith the elements’ addEventListener method, we could dynamically locate the elements in

4445 if ( string1 < string2 )46 comparisonResult = -1;47 48 return comparisonResult;49 } // end function50 ); // sort the keys5152 var markup = "<ul>"; // used to store search link markup53 var url = "http://search.twitter.com/search?q=";5455 // build list of links56 for (var tag in tags) 57 {58 var query = url + ;59 markup += "<li><a href = '" + query + "'>" + tags[tag] + "</a>" +60 "<img id = '" + tags[tag] + "' src = 'edit.png' alt = '" + 61 "Edit search: " + tags[tag] + "' onclick = 'editTag(id)'>" +62 "<img id = '" + tags[tag] + "' src = 'delete.png' alt = '" + 63 "Delete search: " + tags[tag] + "' onclick = 'deleteTag(id)'>";64 } // end for6566 markup += "</ul>";67 document.getElementById("searches").innerHTML = markup;68 } // end function loadSearches69

Fig. 19.12 | Storing and retrieving key/value pairs using HTML5 localStorage and session-Storage. (Part 2 of 2.)

localStorage.getItem(tags[tag])

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

Page 15: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

19.5 Building the App 15

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

the page after we create them, then register the event handlers. Also, notice that each eventhandler is receiving the img element’s id as an argument—this enables the event handler touse the id value when handling the event. [Note: The localStorage and sessionStorageproperties 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 SavedSearches button. If the user confirms that the saved searches should be cleared, line 75calls the clear method of the localStorage object to remove all key/value pairs from theobject. We then call loadSearches to refresh the list of saved searches in the web page.

Function saveSearch Function saveSearch (Fig. 19.14) is called when the user touches Save Search to save asearch. Line 85 uses the setItem method to store a key/value pair in the localStorageobject. If the key already exits, setItem replaces the corresponding value; otherwise, it cre-ates a new key/value pair. We then call loadSearches to refresh the list of saved searchesin the web page.

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

70 // deletes all key-value pairs from localStorage71 function clearAllSearches() 72 {73 if ( confirm("Are you sure?") )74 {75 76 loadSearches(); // reload searches77 }78 } // end function clearAllSearches79

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

80 // saves a newly tagged search into localStorage81 function saveSearch() 82 {83 var query = document.getElementById("query");84 var tag = document.getElementById("tag");85 86 tag.value = ""; // clear tag input87 query.value = ""; // clear query input88 loadSearches(); // reload searches89 } // end function saveSearch90

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

localStorage.clear();

localStorage.setItem(tag.value, query.value);

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

Page 16: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

16 Chapter 19 HTML5 Favorite Twitter Searches App

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

pair to delete, which we set in line 63 (Fig. 19.12) as the img’s id. Line 94 uses theremoveItem method to remove a key/value pair from the localStorage object. We thencall loadSearches to refresh the list of saved searches in the web page.

Function editTag Function editTag (Fig. 19.16) is called when the user touches the edit (pencil) icon nextto 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 img’s id. In this case, we display the correspond-ing key/value pair’s contents in the input elements with the ids "tag" and "query", re-spectively, so the user can edit them. Line 101 uses the [] operator to access the value fora specified key (tag)—this performs the same task as calling getItem on the localStorageobject. We then call loadSearches to refresh the list of saved searches in the web page.

19.6 Wrap-UpIn this chapter, we reimplemented the Favorite Twitter Searches app as a web app to dem-onstrate that it’s possible to create apps without using native Android/Java development.You saw that with HTML5, CSS3 and JavaScript, you can write apps that are portableamong a great variety of platforms, including the smartphone/tablet platforms for Androidand iPhone/iPad. We used HTML5 elements to define the web app’s interface, CSS3 tostyle those elements and JavaScript to implement the app’s logic.

You learned that each web browser provides its own default formatting for HTML5elements. To ensure the same look-and-feel for web apps across browsers and devices, weused the CSS reset capability to remove all the default browser formatting before applyingour own CSS to the page’s elements.

91 // deletes a specific key-value pair from localStorage92 function deleteTag( tag ) 93 {94 localStorage.removeItem( tag );95 loadSearches(); // reload searches96 } // end function deleteTag97

Fig. 19.15 | Function deleteTag allows the user to delete a previously saved search.

98 // display existing tagged query for editing99 function editTag( tag )100 {101 document.getElementById("query").value = ;102 document.getElementById("tag").value = tag; 103 loadSearches(); // reload searches104 } // end function editTag105106 window.addEventListener( "load", start, false );

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

localStorage[ tag ]

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

Page 17: Androidfp 19.fm Page 1 Friday, May 18, 2012 10:32 …ptgmedia.pearsoncmg.com/imprint_downloads/informit/...The Favorite Twitter Searches app from Chapter 5 allowed user s to save their

19.6 Wrap-Up 17

DRAFT: © Copyright 1992–2012 by Deitel & Associates, Inc. All Rights Reserved.

You learned that HTML5 provides APIs for storing key/value pairs that help elimi-nate some of the problems with the older browser cookie technology. You used the windowobject’s localStorage object to store key/value-pair string data on the user’s computer, sothat 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 eachrequest and that each website domain (such as deitel.com or google.com) has a separatelocalStorage object that is shared by all the web pages from that domain. You alsolearned that the localStorage object can store several megabytes of data by default.

In addition, you used the window object’s sessionStorage property to store key/valuepairs that were needed only for the current browsing session. You learned that there’s aseparate sessionStorage object for every browsing session, including separate webbrowser tabs. Finally, you specified an icon for the web app so that when a user saves ashortcut to the app on a device’s home screen, the icon specified for the web app is used.

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