Androidfp_19

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

description

Android

Transcript of Androidfp_19

  • 19

    DRAFT: Copyright 19922012 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 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 HTML-element 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.

    =

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

  • 2 Chapter 19 HTML5 Favorite Twitter Searches App

    Ou

    tlin

    e

    DRAFT: Copyright 19922012 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 youre 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 youre not familiarwith 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 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 todays 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 devices 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

  • 19.1 Introduction 3

    DRAFT: Copyright 19922012 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 thedevices HTML5-compliant web browser. The user can even install a shortcut to your appon the devices home screen. This chapter demonstrates that you can create a web app withsimilar functionality to a native Android app.

    As with Chapter 5s version of Favorite Twitter Searches, the users favorite searchesare saved on the device, so theyre immediately available each time the app launches. Inthis 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 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, its continuously improving, so youll 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

  • 4 Chapter 19 HTML5 Favorite Twitter Searches App

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

    to use it to create an increasing variety of powerful web apps. Were now writing HTML5for Programmers: A Mobile App-Driven Approach in which well 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 keyboarda 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. Lets 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 createdthis 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

  • 19.2 Test-Driving the Favorite Twitter Searches App 5

    DRAFT: Copyright 19922012 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 searchs hyperlink. Touching Clear Saved Searches removes all the searches from thefavorites lista 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

  • 6 Chapter 19 HTML5 Favorite Twitter Searches App

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

    Adding a Shortcut to the Devices Home Screen in an Android 2.3.x DeviceTo 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 toview the list of bookmarks (Fig. 19.6(a)). The web page youre 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 HTMLdocuments 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)). Youll see how to specify the shortcut icon inSection 19.5.1

    Adding a Shortcut to the Devices 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 browsers address bar, touch the star icon at the right side to display theBookmark this page dialog.

    2. Customize the bookmarks 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

  • 19.3 Technologies Overview 7

    DRAFT: Copyright 19922012 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 apps 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, its considered agood practice to perform a CSS reset to remove all the default browser formatting before ap-plying your own CSS to a pages 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 apps other files.

    Web StoragelocalStorage and sessionStorageBefore HTML5, websites could store only small amounts of text-based information on ausers 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 users 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

  • 8 Chapter 19 HTML5 Favorite Twitter Searches App

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

    that it can retrieve during the clients subsequent visits. For example, a website can retrievethe users 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 theyre extremely limitedin size. Todays web apps often allow users to manipulate large amounts of data, such asdocuments or emails. Some web apps allow so-called offline accessfor 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 sites 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 its 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 objectslocalStorage property to store up to several megabytes of key/value-pair string data onthe 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 eachrequest. Each website domain (such as deitel.com or google.com) has a separate local-Storage objectall 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 objects sessionStorage property.Theres 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 Devices Home ScreenAs you know, installing an Android app on a device creates an icon for that app in the de-vices 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. Its 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 apps 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

  • 19.5 Building the App 9

    DRAFT: Copyright 19922012 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 pages GUI.

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

    FavoriteTwitterSearches.js (Section 19.5.3) defines the apps logic.

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

    Fig. 19.8 | Favorite Twitter Searches web page design.

    1 23 4 5 6 7 Twitter Searches8 9 10 11 12

    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) thatsdynamically generated andplaced in the "searches"

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

    element for a hyperlink andtwo img elements

    h1

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

  • 10 Chapter 19 HTML5 Favorite Twitter Searches App

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

    head ElementLoading the CSS FilesIn the documents 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 ElementSpecifying 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 its a good practice to include the link elements in lines 10 and 11.

    13 14 15 16 17 Favorite Twitter Searches18 19 20 21 22 List of Twitter search operators23 24 25 27 28 29 30 31 32 33 35 36 37 Previously Tagged Searches38 39 40

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

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

  • 19.5 Building the App 11

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

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

    head ElementUsing a meta Element to Configure the ViewportThe meta element with the name attribute set to "viewport" (lines 1314) configures thearea in which this apps 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 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 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 thescreens 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 1936) 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 15 perform the following tasks:

    Line 1 defines the bodys 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

  • 12 Chapter 19 HTML5 Favorite Twitter Searches App

    DRAFT: Copyright 19922012 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 45 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 616 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 styleeach 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 thats displayedin the saved searches list.

    Lines 911 specify the style for the anchor (a) elements displayed in the savedsearches 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 thefirst 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, respective-ly. 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 106in Fig. 19.16 registers the web pages load event listener. When the page loads, functionstart (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 // 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

  • 19.5 Building the App 13

    DRAFT: Copyright 19922012 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 windows 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 users 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 2223 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

  • 14 Chapter 19 HTML5 Favorite Twitter Searches App

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

    Next, line 26 gets the localStorage objects length, which represents the number ofkey/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 tagsarray. Method key (line 32) receives an index as an argument and returns the corre-sponding key.

    Lines 3550 sort the tags array, so that we can display the searches in alphabeticalorder by tag name (i.e., key). Lines 3649 define an anonymous JavaScript comparisonfunction thats passed as an argument to the arrays 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 iftheyre 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 5266 build the unordered list of links representing the saved searches. Line 58calls the localStorage objects getItem method to obtain the search string for a given tagand appends the search string to the Twitter search URL (line 53). Then lines 5963 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 handlersthis 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 = ""; // 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 += "" + tags[tag] + "" +60 "" +62 "";64 } // end for6566 markup += "";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

  • 19.5 Building the App 15

    DRAFT: Copyright 19922012 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 elements id as an argumentthis 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

  • 16 Chapter 19 HTML5 Favorite Twitter Searches App

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

    pair to delete, which we set in line 63 (Fig. 19.12) as the imgs 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 imgs id. In this case, we display the correspond-ing key/value pairs 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 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 portableamong a great variety of platforms, including the smartphone/tablet platforms for Androidand iPhone/iPad. We used HTML5 elements to define the web apps interface, CSS3 tostyle those elements and JavaScript to implement the apps 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 pages 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

  • 19.6 Wrap-Up 17

    DRAFT: Copyright 19922012 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 windowobjects localStorage object to store key/value-pair string data on the users 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 objects sessionStorage property to store key/valuepairs that were needed only for the current browsing session. You learned that theres 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 devices home screen, the icon specified for the web app is used.

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