Intel XDK App Programming Full Course Handout
April 1, 2017 | Author: myfreeiwant | Category: N/A
Short Description
Get started with the Intel XDK App programming using HTML...
Description
(This page intentionally left blank)
Unit 1: Unit 1: Introducing the Course
About the Course Fast Track to Intel XDK New is designed to teach experienced web developers and designers how to design, implement, and package web applications for mobile devices. The course is task-based, with you learning by performing a series of hands-on tasks. Over the next four hours you will create a web application named “Friends with Beer” that enables users to create a themed contact manager that uses many mobile-specific features such as calculating geoposition, video playback, push notifications, phone dialing, sending emails, and more! Along with covering the basics of the Intel XDK New, the course focuses on best practices and design, stressing the importance of usability, optimization, and maintainability of cross-device compatible applications. Lab instructions are designed for Windows or OS/X users who have an Android phone.
2013 Intel Corporation
Figure 1: The app that you'll build in this course.
1-1
Fast Track to Intel XDK New
Introducing Intel XDK New Intel® XDK NEW, enables you to easily create, test, and package crossdevice compatible HTML5-based mobile apps. Intel XDK New runs on Windows 7,8, OS/X and Ubuntu Linux desktops. It seamlessly integrates many best-of-breed mobile web development technologies into an easy-touse, integrated development environment.
Figure 2: The Intel XDK New GUI
Choose a Framework You can develop your apps using popular HTML5 mobile frameworks including
1-2
Bootstrap – a popular front-end framework for faster and easier web development.
jQuery Mobile – the “write less, do more” library for rapidly coding mobile apps.
Intel's App Framework - an open source HTML5 UI framework
Topcoat – a fast-performing CSS framework from Adobe that includes icons, fonts, and themed components for mobile devices.
2013 Intel Corporation.
Unit 1: Introducing the Course
Develop visually, code fast and furiously Intel® XDK NEW integrates an easy-to-use, drag & drop app designer with Brackets, a highly-regarded, open-source editor with syntax helpers and auto-completion.
Figure 3: The integrated Brackets code editor.
Emulate popular devices Use the built-in Apache Ripple device emulator to simulate your app running on multiple devices, from different geographic locations, varying bandwidth conditions, and changing orientations. Use the integrated Google Chrome Dev Tools to troubleshoot runtime issues.
Figure 4: Using the built-in device emulator.
2013 Intel Corporation.
1-3
Fast Track to Intel XDK New
Trust, But Verify By loading Intel App Preview onto your mobile devices, you'll be able to easily:
Run your app on physical devices without rebuilding
Debug your app while it's running on the device, using the integrated weinre remote debugger.
Conduct performance profiling
Check out demo apps.
Intel App Preview is available for iOS, Android, and Windows Phone.
Figure 5: Test your app on physical devices with Intel App Preview
1-4
2013 Intel Corporation.
Unit 1: Introducing the Course
Package for App Stores After you've completed your testing, use Intel XDK's integrated Apache Cordova framework to build native apps for all the popular mobile platforms.
Integrate native features and add cloud support The Intel XDK API that includes features not currently available in Cordova, including:
Facebook login API
Android multi-touch
Oauth support
Enhanced audio
Accelerated canvas
In addition, you can quickly add cloud-based features from appMobi to such as push notification support, user management, e-commerce, and cloud hosting.
2013 Intel Corporation.
1-5
Fast Track to Intel XDK New
Reviewing the Course Objectives After completing this course, you should be able to:
Develop web and native apps for mobile devices
Visually design and implement a graphical user interface.
Create input forms that read and submit data to/from an application server
Request JSON data from an application server
Integrate mapping, geolocation, and push notifications into a mobile app.
Deploy audio and video assets
Theme your application to meet branding standards
Test and package your app to run natively on Android and iPhone devices.
Reviewing the Course Prerequisites The knowledge prerequisites for this course are:
Prior experience with HTML 5
A casual understanding of CSS
Intermediate JavaScript coding skills and, in particular, familiarity with JavaScript Object Notation
Required Software The following software is REQUIRED to be installed on your computer:
Intel XDK http://xdk-software.intel.com/
Fast Track to Intel XDK student files http://www.xdktraining.com/student.zip
The following software is REQUIRED to be installed on your mobile device:
1-6
Intel App Preview Available on iOS, Android, and Microsoft stores. 2013 Intel Corporation.
Unit 1: Introducing the Course
Reviewing the Course Format This course is divided into ten units, each of which presents new information and contains demonstrations, walkthroughs, and a lab. At the end of each unit, you will find a summary and a short review to test your knowledge of the unit’s content. The following icons are used throughout the guide: Concepts introduce new information.
Demonstrations illustrate new concepts.
Walkthroughs guide you, with the instructor’s assistance, through procedures in a hands-on context.
Labs let you practice new skills on your own.
Summaries provide a brief synopsis of the unit’s content.
Reviews test how well you remember the concepts from the unit.
Best Practices provide you with helpful insights and information.
2013 Intel Corporation.
1-7
Fast Track to Intel XDK New
Outlining the Course Content
1-8
Unit 1: Introducing the Course
Unit 2: Getting Started • Introducing the Intel XDK New • Reviewing the features and benefits of HTML5 / CSS3 • Using Debugging Techniques • Getting Help
Unit 3: Designing Views • Defining Pages • Using Layout Controls • Linking to Pages • Adding text and images
Unit 4: Working with Data • Using jQuery to make data requests via AJAX • Outputting structured data into a List • Reading Data from the Contact's list • Storing data on the Device with WebSQL
Unit 5: Implementing Forms • Using the Forms Widgets • Implementing Data Validation • Saving Form Data
Unit 6: Implementing GEO Features • Geocoding Addresses • Acquiring the Device Position • Calculating Distance to Targets • Visualizing Data on a Map
2013 Intel Corporation.
Unit 1: Introducing the Course
Unit 7: Using Device Features • Dialing the Phone • Sending Email • Launching Turn By Turn Directions • Using the Accelerometer • Handling Push Notifications
Unit 8: Handing Multimedia • Understanding the features and capabilities of HTML5 • Playing Audio • Playing Video
Unit 9: Theming your App • Using CSS3 Features and Capabilities • Applying CSS3 Backgrounds • Using ThemeRoller to theme your UI components
Unit 10: Going Native • Creating Production Web Builds • Creating Native Builds for iOS • Exercise: Packaging a Native iOS Build
2013 Intel Corporation.
1-9
Fast Track to Intel XDK New
Demonstration 1-1: Viewing the Applications Observe as your instructor introduces the applications that you will be building during the exercises: You will build the Friends with Beer mobile application during your instructor-led walkthroughs in the following order: •
About Friends with Beer (Home Page)
•
Beer List
•
Friends with Beer Contact List
•
Friends with Beer Contact Data Entry Form
•
Friends with Beer Contact Detail
•
Friends with Beer Video
Reviewing the Application – Intro Screens
The Friends with Beer Home Page contains simple html markup. It's designed to help you get comfortable using the Intel XDK visual designer.
1 - 10
2013 Intel Corporation.
The Beers List displays a list of beers that were downloaded from a REST-based web service and cached into an HTML5 WebSQL database.
Unit 1: Introducing the Course
The Contact List is driven from data stored in a WebSQL database. Clicking on the button in the top-left corner enables you to import data from your phone's native contacts app. Users can actually shake the device to select a friend at random.
2013 Intel Corporation.
The Contact form enables you to edit information about your contacts. It also converts their street address to a lat/lng position on-the-fly and has client-side data validation.
1 - 11
Fast Track to Intel XDK New
Reviewing the Application – Using Device Features
The Friends with Beer Detail Page enables the user to activate the device's phone dialer, email application, and navigation app. It also uses Google Maps to display real-time traffic conditions around your friend's location.
1 - 12
2013 Intel Corporation.
The Video page displays a streaming video from Vimeo and an mp4 from a web server so that the user will never have to feel like they're drinking alone.
Unit 1: Introducing the Course
Walkthrough 1-1: Installing the Courseware In this lab, you will perform the following tasks:
Install Intel XDK New on your desktop
Install Intel App Preview on your mobile device
Download and install the course files
Steps Download and Install Intel XDK
1. Open a web browser to the following URL: http://xdk-software.intel.com/ 2. Click the Download Intel XDK New button. OS/X Users:
3. Open the downloaded .dmg file 4. Double-click on the .pkg file 5. Complete the steps in the installation wizard. 6. Select Go > Applications and verify that XDK New is present. Microsoft Windows 7+ Users:
7. Open the downloaded .exe file 8. Complete the steps in the installation wizard 9. Verify that Intel XDK New appears in your Start menu. Log into Intel XDK
10. Launch Intel XDK New 11. Click on Need to sign up for an Account? 12. Fill out the form, entering your name, email address, password, and country. Note the following: • Passwords must be between 8-15 characters in length • Passwords must contain at least one alpha character • Passwords may not contain non-English characters • Passwords must contain at least one number • Passwords must contain at least one special character (!@#$%) 13. Check the Terms and Conditions checkbox. 14. Sign up for the newsletters. 2013 Intel Corporation.
1 - 13
Fast Track to Intel XDK New
15. Click the Submit button. 16. Enter your username and password. 17. Turn on the checkbox labeled Keep me logged in on this computer. 18. Click Submit. Install Intel App Preview on your Mobile Device
19. Configure your mobile device to be on the same wireless network as your computer. 20. Open Google Play on your Android phone. 21. Search for “Intel App Preview” 22. Tap on Intel App Preview 23. Tap on the Install button. 24. Tap the Accept button. 25. When the installation process as completed, tap the open button. 26. Sign into the app using the Intel XDK credentials that you created earlier in this exercise. Download and Unzip the Exercise Files
27. Download the exercise files from http://www.xdktraining.com/exercises.zip 28. Unzip the files into your home/documents folder. – End of Walkthrough --
1 - 14
2013 Intel Corporation.
Unit 1: Introducing the Course
Unit Summary
The course is presented through a combination of lectures and handson exercises.
The course has been designed assuming that you already understand HTML, CSS, and some Javascript.
The course consists of 10 units that cover the essentials of developing mobile apps with Intel XDK New.
The course focuses on developing web and native applications for mobile devices.
You will build a web application to keep track of your friends with beer.
2013 Intel Corporation.
1 - 15
(This page intentionally left blank)
Unit 2: Getting Started with Intel XDK New
Unit Objectives After completing this unit, you should be able to:
Understand the features and capabilities of Intel XDK New
Use the visual designer to create a “Hello World” page in your app.
Use the code editor to add JavaScript to your app.
Test your app on the simulator and your mobile device.
Package your app as a native application for distribution on App stores.
Introducing Intel XDK New Debugging Your Apps Getting Help
Unit Topics
2-1 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Introducing Intel XDK New The Intel® XDK NEW development system is for those developers who wish to use their HTML5 expertise to build hybrid HTML5 apps for mobile devices (e.g., phones and tablets) and other platforms that host HTML5 web apps (such as a Google Chrome* extension or a mobile web site).
Going with an HTML 5 Solution Developers and corporate IT increasingly turn to HTML5 as a solution to meet the critical, time-sensitive demands of their organizations. Developing mobile apps with HTML5 offers several key advantages over native app development:
Native apps are developed to run on a single device platform whereas HTML5 apps use the same codebase to run on multiple devices and operating systems.
Native apps are typically distributed via app stores, however, HTML5 apps can also be deployed as mobile web sites that run in a user's mobile web browser.
HTML5 apps use open-source technologies.
Native OS apps can get “lost” among the hundreds of thousands of apps in app stores. Mobile web apps are “crawlable” by search engines.
Mobile web apps are instantly updatable on a web server.
Instead of having to learn Java or Objective-C, web developers can leverage their existing skill sets to rapidly create mobile apps.
HTML5-based apps tend to be less affected by changes in the mobile operating system.
Navigating the Tooling Quagmire Historically, one of the biggest challenges faced by mobile web app developers has been dealing with the lack of a truly integrated development environment. Most developers spend their days toggling between an html design tools, a javascript code editor, a CSS editor, web browser, debugger, command-line build utilities, FTP, mobile simulators, and more. Intel XDK NEW is the first truly integrated development environment that application consists of a set of best-of-breed tools that help you code, debug, test and build mobile web apps and hybrid HTML5 apps for multiple target platforms.
2-2 © 2013 Intel Corporation.
Getting Started with Intel XDK New
Reviewing the Intel XDK New Interface Intel XDK New is organized around the sequence that HTML app developers follow when they create and package an application: 1. Develop Use the visual designer to prototype your graphical user interface and handle user interactions by hand-coding javascript with the built-in Brackets editor. 2. Emulate Validate that your application looks and functions properly across multiple screen resolutions, under varying bandwidth conditions, and from different geographic locations by using the embedded Apache Ripple emulator. Debug application errors with the integrated Google debugger. 3. Test Verify that your app performs as expected by running from Intel's App Preview container. Debug the app and chart its performance as it runs on your device by using the embedded weinre remote debugger. 4. Build Package the app for distribution via app stores or the web using the integrated Apache Cordova toolkit. Test device-specific features. 5. Services Integrate cloud-based services into your app from appMobi, including push-notifications, e-commerce, live updates, in-app purchasing, and hosting.
2-3 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Designing Apps As depicted in Figure 1, Develop mode enables you to visually prototype the look and feel of your application.
Figure 1: Develop / Design View
•
The Project Selector enables you to load pre-existing projects or create new projects into the Intel XDK GUI.
•
Your app's views appear in the Project Files panel.
•
While in Design view, you can drag and drop components from the UI Controls Palette onto the Design Canvas.
•
UI controls that you've dropped onto the Design Canvas may be configured by changing settings in the Property Editor.
•
The Product Version indicator alerts you as to the release version of the XDK that is currently in use.
2-4 © 2013 Intel Corporation.
Getting Started with Intel XDK New
Developing Apps As depicted in Figure 2, toggling to Code view enables you to modify the code generated by the visual designer, as well as edit javascript and css application assets. Code hints appear as you type.
Figure 2: Using the integrated Brackets editor to hand-code your app
Running Your App in an Emulator As illustrated in Figure 3, clicking on the Emulate tab runs your app in the Apache Ripple emulator.
Figure 3: Simulate your app running on multiple devices.
The emulator enables you to simulate your app running on multiple devices under varying environmental conditions: 2-5 © 2013 Intel Corporation.
Fast Track to Intel XDK New
The Devices panel allows you to simulate your app running on a variety of popular devices including the iPad, iPhone, Google Nexus, Microsoft Surface Pro, Motorola Droid 2, Nokia Lumina 920, Samsung Galaxy S, and Samsung Galaxy tab.
The Information panel provides you with metrics regarding your selected device, including OS, screen resolution, pixel density, and the http user agent that's transmitted on each request.
The Accelerometer panel enables you to simulate moving the device along its x, y, and z axis. This is vital for testing movement-based controls. You can also have it virtually “shake” the device.
The Live Update Service panel simulates your app receiving an update service request from appMobi.
The Device & Network Settings panel enables you to simulate Figure 4: Testing accelerometerdifferent degrees of network based controls. throughput (from WiFi to no connection), as well as toggle locales from English to French or German.
The Geo Location panel allows you to simulate how your app would behave if it were running from different physical locations. You can also configure heading, speed, altitude, GPS accuracy, and GPS timeout. You can even have it replay a route that was saved to a GPS Exchange Format (GPX) file.
The PushMobi panel allows you to inspect how your application would behave if it received a push-notification message.
2-6 © 2013 Intel Corporation.
Getting Started with Intel XDK New
Testing your app on a device The Test module, depicted in Figure 5, enables you to easily upload your application to a testing server. You can then launch it on any device that's running the Intel App Preview mobile application.
Figure 5: Upload your app and test it on devices using Intel App Preview
You'll typically test apps on physical devices by completing the following steps: 1. In Intel XDK New, click on the Test tab. 2. Click on the Push Files button 3. Open Intel App Preview on your mobile device. 4. Tap on the Server Apps tab. 5. Tap on the camera icon, located in the top-right corner of the app. 6. Scan the QR code in the XDK with your phone's camera. Once the QR code has been scanned, the app will be automatically downloaded and executed. You can debug the app as it's running on yourFigure 6: Intel App Preview device by using the built-in weinre remote debugger. 2-7 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Generating Production Builds The Build tab, as depicted in Figure 7, uploads your app to a cordovabased build server, packaging your code as a native app for distribution across popular app stores or for distribution within your enterprise. Options include:
iOS Ad-Hoc Distribution
Windows 8 Store
iOS App Store
Android
Windows Phone 8
Tizen
Amazon
Nook
Figure 7: Intel XDK uses Apache Cordova to convert your web app into native apps for all popular platforms.
2-8 © 2013 Intel Corporation.
Getting Started with Intel XDK New
As illustrated by Figure 8, some vendors will require you to upload distribution certificates and/or supply authentication credentials.
Figure 8: Uploading certificates and a provisioning profile for an iOS App Store production build
You can also have XDK New create a distribution package for deployment across the following web platforms:
WebApp Enables you to post your code on a local or remote web server, or host in AppMobi. (Your code may be downloaded as a .zip file)
Chrome Packages your app for distribution in the Google Chrome store.
Facebook Packages your app for distribution via the Facebook social network.
2-9 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Using Cloud Services As illustrated by Figure 9, Intel XDK New features tight integration with appMobi cloud services.
Figure 9: Using the appMobi hosting service
While you are not obligated to use appMobi, it is a convenient resource for providing the following application support resources:
HostMobi can host your app in a PHP, .NET, or Node.js server environment. Edge-cached hosting delivers the best performance for on-the-go web apps, and hostMobi provides that through our partnership with Amazon's Elastic Computing Cloud, (which now spans the entire globe).
Live Update enables you to notify users that a new version of your app is available. You have the option to push app updates immediately instead of waiting for your users to upgrade at their leisure.
Storeview is a cloud-based reporting service that aggregates detailed app analytics from the most popular app stores and displays them in an interactive dashboard.
Pushmobi enables you to send push notifications to your subscribers. You can target messages to a particular user target users based on search filters.
1Touch is an in-app purchase (IAP) cloud service, that allows you to interface with various app stores using a single line of javascript. 1Touch takes away the pain of integrating with the various app stores and payment providers. With a single function call you can sell in-app items on IOS, Android, Windows8, Windows8 Phone, Facebook and the Chrome Store.
2 - 10 © 2013 Intel Corporation.
Getting Started with Intel XDK New
Walkthrough 2-1: Getting Started In this lab, you will perform the following tasks:
Log into Intel XDK
Create a new project
Design a “hello world” page
Test your app in the emulator
Package your app for distribution
Install your app on your Android device
Steps Create a New Project
1. Launch Intel XDK New 2. Click on the Start a New Project button 3. Click on Start with App Designer 4. Enter a project name of “MyHelloWorld” 5. Click the Create button. 6. Click the No Thanks button. 7. Click the Let's Go! button. 8. In the left panel, click on index.html. The “Select a Framework” dialog box will appear. 9. Click on the jQuery Mobile radio button. 10. Click on the Select button. Design a Page
11. From the Controls panel, drag a Header and drop it onto the design canvas. 12. In the Header Settings panel, turn on the checkbox adjacent to the Title property and enter the following title: Friends with Beer
13. Turn on the Fixed checkbox. 14. From the Controls > Media panel, drag a Text control and drop it underneath the Header on the Design canvas.
2 - 11 © 2013 Intel Corporation.
Fast Track to Intel XDK New
15. In the Text Settings panel, change the text to the following: Welcome to Friends with Beer!
Display your page in the Emulator
16. Click on the Emulate tab. 17. In the Devices panel, select Google Nexus 4. 18. In the Devices panel, toggle the orientation of the emulated device by clicking on the landscape orientation button. 19. In the Device & Network Settings panel, note that you can emulate different network lag conditions. Run Your App on Your Mobile Device
20. Click on the Test tab. 21. Click the Sync button. 22. Open Intel App Preview on your mobile device. 23. Tap the Server Apps button. 24. Tap the Camera button located in the top right corner of the GUI. 25. Scan the QR code on your desktop. 26. Tap OK. Your app should launch. Build your App for Native Distribution
27. Return to XDK New on your desktop. 28. Click the Build tab. 29. Click the Android Build button. 30. Click the Build App Now button. 31. Click the Download Build button and save the generated .apk file to your desktop. 32. Email the .apk file to yourself. 33. Open the email on your Android phone. 34. Tap on the .apk file attachment. 35. Click on the Install button. 36. Click Open. Your app should open. Congratulations. You've just built a native mobile app!
2 - 12 © 2013 Intel Corporation.
Getting Started with Intel XDK New
Debugging Your Apps As you develop your apps, you'll inadvertently insert bugs into your program which will need to be eradicated as quickly and efficiently as possible. Most of your bugs will likely appear when you run your app in the emulator. Others may not show up until you run the app on a physical device. Fortunately, XDK New has both of these scenarios covered.
Debugging in the Emulator Intel XDK New features an integrated Chromium developer that you can invoke by clicking the debugger button from Emulate mode, as depicted in Figure 10. The debugger enables you to inspect the DOM of your Figure 10: Activating the Debugger application, review all HTTP requests, read the contents of cookies and HTML5 local storage, and can even provide hints as to how to optimize your application's performance. Most importantly, it enables you to set breakpoints and step through your code interactively while monitoring the contents of variables.
Figure 11: The integrated Chromium debugger.
2 - 13 © 2013 Intel Corporation.
Fast Track to Intel XDK New
The debugger is partitioned into the following seven segments:
Label
Description
Elements
Enables you to click on any area in your browser and inspect its markup. It also displays all the CSS applied to the element and allows you to selectively enable, disable, and modify individual styles.
Resources
Enables you to review the contents of HTML5 local database (SqlLite), HTML5 Local Storage, HTML5 Session Storage, HTTP cookies, and the HTML5 Application Cache.
Network
Displays all HTTP communications. This is particularly useful for troubleshooting AJAX requests. Displays both data transmitted via the HTTP header to the server as well as the content returned from the server.
Sources
Displays all of the JavaScript files that were loaded into the browser as part of the request. You can set breakpoints and step through your code one line at a time. You can also define watch expressions to keep an eye on the contents of your variables.
Timeline
Displays the time to download files from the server, the time to execute scripts, and the time to render the output. Use the timeline to develop insights into where your bottlenecks might be in your code as well as benchmark your changes.
Profiles
Similar to the timeline, the Profiles panel captures the execution of your application and then displays the percentage of CPU utilization that was required to execute specific methods or handle events. You can also profile the performance of your CSS to see how long selector matching took and take a heap snapshot to understand memory distribution among your page's Javascript objects and related DOM nodes.
Audits
Evaluates the performance of your application and provides helpful optimization tips.
Console
Displays error messages as well as the output from executing console.log() statements. You can also execute javascript code interactively in this view.
2 - 14 © 2013 Intel Corporation.
Getting Started with Intel XDK New
Programmatically Setting Breakpoints You can set programmatic breakpoints by inserting the following command into your JavaScript: debugger;
If the Chromium debugger is active when this statement is encountered, execution of your app will pause and your script will appear in the Sources section as depicted in Figure 12).
Figure 12: Active breakpoint
As depicted in Figure 13, you can use the debugger controls to interactively step through your code. You can also set watch expressions in order to view how your code changes the contents of your variables.
Figure 13: Using the debugger's step controls
2 - 15 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Outputting Variables to the Debugger Console Use the console.log() command to dump the contents of Javascript variables to the Chromium debugger console as illustrated below: function init() { $('#debugBtn').bind('click', function(e) { debugger; for (var i=0; i Save. 30. Click the Test tab. 31. Click on the Push Files button. 32. Run Intel App Preview on your mobile device. 33. Tap on the Camera button and scan the QR code from the Test tab. 34. On your mobile device, tap OK to launch the app. 35. In the Intel XDK Test tab, click on the Begin Debugging on Device button. 36. Click on the hyperlinked target reference. 37. In the weinre debugger, click on the Console button. 38. In the app running on your mobile device, tap the Debug Me button.
2 - 20 © 2013 Intel Corporation.
Getting Started with Intel XDK New
39. Note that the console output from your mobile app running on your device appears in the weinre remote debugger console view. 40. Click on the End Debugging Button to end your remote debugging session. – End of Walkthrough --
2 - 21 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Getting Help Intel XDK New ships with online documentation and sample applications, and has community support resources available as well. As illustrated by Figure 19, help features are available by clicking on the yellow question mark button.
Figure 19: Accessing help resources.
Using the XDK Documentation Selecting the Visit the Help Page link opens your web browser to the Intel Developer Zone at http://software.intel.com/en-us/html5/articles/xdkdocs. From here, you can get quick access to Intel's App Framework docs, the Apache Cordova API docs, jQuery API, and Google Chrome Dev Tools docs
Figure 20: The Intel XDK New Help Page
2 - 22 © 2013 Intel Corporation.
Getting Started with Intel XDK New
Perhaps the most relevant documentation for this course is the Intel XDK API documentation, which contains information about available javaScript methods in the intel.xdk namespace. You can access these resources directly from: http://www.html5dev-software.intel.com/documentation/jsAPI/index.html Figure 21: Documation for the intel.xdk javascript package
This package documents methods that enable you to access the following resources:
Mobile device physical resources, including the camera and accelerometer
Facebook API support
Supporting multitouch on Android devices
oAuth authentication methods
Interacting with the accelerated Canvas App Game interface plugin
2 - 23 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Using the Forums The Intel XDK New developer forum, depicted in Figure 22, is a great resource for interfacing with other developers and the Intel XDK development team. Post your technical support questions here and receive quick responses from other developers as well as members of Intel's XDK New development team.
Figure 22: The Intel XDK New developer forum.
2 - 24 © 2013 Intel Corporation.
Getting Started with Intel XDK New
Reviewing the Sample Applications As depicted in Figure 23, Intel XDK New ships with 14 separate sample applications that aptly demonstrate how to use commonly requested mobile app features. Documentation for each example, accessed by pressing the document button, highlights the specific API calls that were critical in producing the desired outcome.
Figure 23: Opening a sample application
The examples include the following: Name
Description
Rolling Can
Captures a device’s accelerometer data and animates an HTML element using CSS transformations.
Flood Puzzle
A simple puzzle game implemented as a Single Page App that illustrates how to use Javascript to modify CSS styles based on user interactions.
Springboard
A jQuery-Mobile based application that demonstrates custom styling techniques which adapt to various screen sizes and rotations, and achieve a different look and feel than JQM defaults.
Buttons
A basic example of that reads the touchStart and touchEnd JavaScript events in order to provide a responsive visual cue to the user that a button is being pressed.
2 - 25 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Name
Description
App Framework
A simple app that demonstrates how to use various Intel App Framework UI components.
Geolocation
Plots the user's geolocation on a Google Map, updating every five seconds.
Tab Nav
A multi-page JQM scaffold using tab-based navigation. It demonstrates how to create a custom options menu widget that maintains state across page transitions and how to dynamically inject widgets into the DOM.
RPN Calculator
A themable stack-based calculator that uses different color schemes, styles, and button animations.
Basic Hybrid App
Demonstrates how to use the intel.xdk library to access native device features.
Hello World
The classic. You know it, you love it.
PhoneGap Audio
Uses a Cordova media object to record and playback audio.
Towers of Hanoi
Uses CSS and jQuery to animate solving the classic “Towers of Hanoi” puzzle.
Counting Beads
A simple HTML5-based game that teaches young children how to count up to 50.
IQM List View
A JQM-based app that uses the Rotten Tomatoes API to create a paginated list of DVD rentals. It demonstrates how to populate a list view with live data and dynamically generate pages.
2 - 26 © 2013 Intel Corporation.
Getting Started with Intel XDK New
Walkthrough 2-3: Using a Starter App In this lab, you will perform the following tasks:
Review the Tab Nav sample application
The Friends with Beer application that you're going to create uses a similar navigational structure. You'll review and learn how to apply the techniques used to create this app later in the course.
Steps Create a New Project from a Sample
1. Open Intel XDK New 2. Click on the word Projects in the top left corner of the GUI. 3. Click the Start a New Project button. 4. Click on the Work with a Demo tab. 5. Click on the IQM Tab Nav app. 6. Click Next. 7. Enter the following information:
Name your project: walk2_3 Project Location: /path/to/ftIntelXdkNew/walk/walk2_3
8. Click the Create button. 9. Click No Thanks 10. Click Let's Go Review the App
11. Click on the Emulate tab and review how the application runs onscreen. Note the tab-based navigation that's docked to the bottom of the screen. 12. Click on the Develop tab. 13. Click on the index.html file. 14. Review the structure of the HTML. Note that each page is represented by a set of logical pages, set off by a tag with data-role=”page”. 15. Review the structure of the tab bar which manifests from the markup. 16. Open the file app/tabbedImages.js and review the code. Note that jQM pages fire an event named “pageshow” when they appear to a user. – End of Walkthrough --
2 - 27 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Summary
Designing and developing applications for handheld devices is a completely different process than writing for desktop browsers
Intel XDK New is an integrated development environment for creating mobile applications built on web standards – HTML 5, JavaScript, and CSS3.
Intel XDK New integrates many best-of-breed HTML5 development tools including the following:
MobiOne WYSIWYG visual interface designer Brackets code editor Google Chromium Debugger Apache Ripple Emulator Intel App Preview mobile app launcher weinre remote debugger Apache Cordova native app packager appMobi cloud services
You can develop your application using a variety of Javascript frameworks including jQuery Mobile, TopCoat, Bootstrap, and Intel's App Framework.
Intel's App Framework API extends Apache Cordova features.
The Chromium debugger and weinre remote debugger provide you powerful troubleshooting capabilities and optimization tips.
Intel XDK New ships with over a dozen sample apps that demonstrate frequently requested mobile application features.
2 - 28 © 2013 Intel Corporation.
Getting Started with Intel XDK New
Unit Review 1. Do you need to install any software other than Intel XDK New in order to develop, test, build, and deploy a mobile app?
2. What are some advantages to developing a mobile app using web standards instead of using Objective-C or Java?
3. Which physical device features can you test with the Emulator?
4. You must develop mobile apps using Intel's App Framework (true/false)
5. List two programmatic techniques for inspecting the contents of a javascript variable.
2 - 29 © 2013 Intel Corporation.
(This page intentionally left blank)
Unit 3: Page Layout
Unit Objectives After completing this unit, you should be able to:
Define logical “pages” in your application
Use layout controls to position elements on a page
Implement your app's navigational controls
Enable animated transitions between pages
Add text and image content to your application
Defining Pages Adding Content
Unit Topics
3-1 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Defining Pages jQuery mobile uses a combination of HTML tags and HTML5 custom data properties to implement a page-based architecture for layout. An HTML file may contain either a single page widget, or multiple page widgets. Pages are typically indicated by tags with a data-role property equal to page. Most jQuery Mobile pages, therefore use the the following structure:
Note: The Intel XDK New visual wysiwyg designer does not support defining multiple pages within a single .html file. You'll typically define pages with the following attributes: Attribute
Description
data-dom-cache
Determines whether to keep the page in the DOM when the user navigates away from it.
data-theme
Sets the theme that will be used to render the page.
In most transactional-based apps, you'll also need to write an event handler that executes when a page is instantiated in the DOM. Typically your event handler will download .JSON data from a REST-based webservice or static .JSON file and use it to populate the contents of the page. The structure of your page creation event listener will resemble the following: $("#page1").on("pagecreate", function( event, ui ) { // page initialization logic goes here. });
3-2 © 2013 Intel Corporation.
Page Layout
Adding New Pages in Intel XDK You can add new pages to your app by right/cmdclicking in the files panel as indicated in figure 1.
Figure 1: Adding new files to your project
As indicated by Figure 2, you''ll be prompted to select a mobile Javascript framework for each new .html file that you add to your project.
Figure 2: You must select a framework for each html file.
3-3 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Defining Page Headers The page header typically displays a page title and can display up to two buttons which are aligned to the left and right of the title, respectively. Headers are usually placed in a fixed position at either the top or bottom of a page. The title text is normally an H1 heading element but it's possible to use any heading level (H1-H6) to allow for semantic flexibility. The basic syntax for implementing a header or resembles the following: Friends with Beer
Adding Buttons to Headers The header container automatically sets the first child link to the left button slot and the second child link in the right as depicted by the following example: Cancel Edit Contact Save
You can also set button position by applying the ui-btn-right and ui-btn-left style classes. This is particularly useful if you need to place a single button on the right of a header as illustrated by the following example: Edit Contact Save
3-4 © 2013 Intel Corporation.
Page Layout
Adding Back Buttons Jquery Mobile will automatically add a “back” button on a header if the following conditions exist:
The page must have the data-add-back-btn=”true” property.
Using the data-rel=”back” property on an anchor.
The data-rel=”back” property causes the default href action to Figure 3: Automatic back button support be ignored in favor of mimicking the browser's back button behavior, going back one history entry. Back Edit Friend Info Save
3-5 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Defining Navigation Bars with the NavBar widget The NavBar widget enables you to place a navigation bar containing up to five buttons, within a header or footer by using the following syntax:
Figure 4: Implementing a Nav Bar About Contacts Beers Drink!
Buttons are automatically sized to occupy the available width/height of their container.
3-6 © 2013 Intel Corporation.
Page Layout
Setting the Default Button State To set an item to be active by default, add class="ui-btn-active" to the corresponding anchor. Add a class of ui-state-persist to make the jQuery automatically restore the active state each time the page is shown. For instance, a nav bar on the index.html page should resemble the following: About Contacts Beers Drink!
Adding Page Transitions Add the data-transition property to each anchor tag in order to apply a transition animation when a user taps on a navbar button. About Contacts
Beers Drink!
Supported transitions include the following:
fade
turn
slide
pop
flow
slideup
flip
slidefade
slidedown
none
3-7 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Defining Navigation Bars with the Button Group Widget The ControlGroup widget groups buttons together so that they look similar to a navigation component. The effect is generated by applying a data-role=”controlgroup” property to a tag that wraps a series of anchor-based buttons as Figure 5: Control Group Buttons illustrated by the following code snippet: Click Me! No, Click me! Always click me!
You can set the buttons to display horizontally by adding the datatype=”horizontal” attribute to the controlgroup container as illustrated below:
Figure 6: A horizontally aligned button group. Click Me! No, Click me! Always click me!
Other configuration properties for the controlgroup widget include: Property
Description
data-corners
Boolean. Sets whether to draw the controlgroup with rounded corners. Defaults to true.
data-mini
Boolean. Controls whether to display more compact buttons that use less space. Defaults to false.
3-8 © 2013 Intel Corporation.
Page Layout
Defining Buttons Buttons are coded with standard HTML anchor and input elements, then enhanced by jQuery Mobile to make them more attractive and useable on a mobile device. You'll typically use anchor links to define navigation buttons, reserving input or button elements for form submission. As previously described, the basic syntax for defining a button is the following: Home
You can add icons to buttons by applying the data-icon property to the anchor tag as illustrated below: Home
The complete set of bundled icons is illustrated in Figure 7:
Figure 7: jQuery Mobile Icons
Icons may be positioned at the top, left, bottom, or right of the button's text by setting the data-iconpos property: Home
You can change the button's theme, causing it to display with either a light background and dark text or a dark background and light text by applying the data-theme property: Home 3-9 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Creating Button Groups with the WYSIWYG Designer As depicted in Figure 8, you can drag a controlgroup widget to the center of a footer, and then style each button individually through the properties panel.
Figure 8: Using the controlgroup widget and styling buttons in the WYSIWYG designer
Navigating Between HTML Files jQuery Mobile automatically ''hijacks” standard links and form submissions, converting them into an AJAX requests. Whenever a link is clicked or a form is submitted, that event is automatically intercepted by the AJAX nav system. An AJAX request based on the href or form action is issued instead of reloading the page. While the framework waits for the AJAX response, a loader overlay is displayed. When the requested page loads, jQuery Mobile parses the document for an element with the data-role="page" attribute and inserts that code into the DOM of the original page. Any widgets in the incoming page are enhanced to apply all the styles and behavior. The title of the incoming page is noted and the “home” page is updated when the new page is transitioned into view. NOTE: The rest of the incoming page is discarded so any scripts, stylesheets or other information will not be included.
3 - 10 © 2013 Intel Corporation.
Page Layout
Walkthrough 3-1: Designing Pages In this lab, you will perform the following tasks:
Define your application pages
Implement a basic header and footer
Implement the app's basic navigational structure
Figure 9: During this lab, you'll Implement tab-style navigation and create placeholder pages.
Steps Open a Project
1. Open Intel XDK New 2. Click on the word PROJECTS in the top-left corner of the GUI. 3. Click the Open a Project button. 4. Select the following file: /ftIntelXdkNew/walk/walk3_1/walk3_1.xdk
5. Click the open button. Design the Page Footer
6. Open the index.html file in Design view. 7. Drag a FOOTER control from the Controls-Layout panel and drop it onto the design canvas. 8. Drag a BUTTON GROUP control from the Controls-Form panel and drop it onto the center of the footer. 9. Click on the first button on the left in the control group.
3 - 11 © 2013 Intel Corporation.
Fast Track to Intel XDK New
10. In the Button Settings panel, configure the following properties:
Label : Home Theme: (b) dark Icon: home Icon position: top
11. Click on the button adjacent to the Home button and configure the following properties:
Label : Friends Icon: user Icon position: top
12. Click on the button adjacent to the Friends button and configure the following properties:
Label : Beers Icon: heart Icon position: top
13. Drag an additional button from the Controls > Form panel and drop it to the far right of the controlgroup in the footer. 14. Configure the following properties:
Label : Drink! Icon: video Icon position: top
15. Go to Code view and add the following attributes to the “Home” button:
href : index.html data-transition: slide
16. Add the following attributes to the “Friends” button:
href: friends.html data-transition: slide
17. Add the following attributes to the “Beers” button:
href: beers.html data-transition: slide
18. Add the following attributes to the “Drink” button:
href: drink.html data-transition: fade
19. Save the file.
3 - 12 © 2013 Intel Corporation.
Page Layout
20. Click on the Emulate tab. The footer should appear similar to Figure 10 .
Figure 10: The completed page footer. Create the Contacts, Beers, and Drink! Placeholders
21. Return to Develop mode. 22. In the Files panel, right/cmd-click on index.html and select New File. 23. Enter the following file name: friends.html
24. When prompted, select the jQuery Mobile framework and click Select. 25. Return to the index.html file 26. Enter Code View 27. Copy the contents of the entire page to your clipboard 28. Return to friends.html 29. Enter Code view 30. Paste the contents of your clipboard into the friends.html file. 31. Cut the following code to your clipboard and paste it into the anchor tag that points to contacts.html: data-theme="b"
32. Return to Design mode. 33. Click on the page header. 34. In the Header Settings panel, change the title to the following: Friends
35. Save the file. 36. Repeat steps 21-35 for the following files, changing the page header and footer as appropriate:
beers.html drink.html
37. Click the Emulate tab.
3 - 13 © 2013 Intel Corporation.
Fast Track to Intel XDK New
38. Confirm that you can navigate between the pages by clicking/tapping on the footer's navigation bar. – End of Walkthrough –
3 - 14 © 2013 Intel Corporation.
Page Layout
Adding Content You'll typically implement the page content area as a tag with the attribute data-role="content", placing it between the page header and footer as illustrated below: Friends with Beer Hello World
As illustrated in Figure 11, the Intel XDK New WYWIWYG designer enables you to quickly lay out your content into a series of columns and rows by dragging and dropping the Column and Row widgets onto the design canvas.
Figure 11: Drag and dropping rows and columns into the content area
Note that as you drag widgets from the Controls pallette, valid drop targets become highlighted with a cyan colored background in the design canvas. When you hover over a valid drop target, its color changes to orange.
3 - 15 © 2013 Intel Corporation.
Fast Track to Intel XDK New
The designer generates a series of styled elements, as illustrated by the following code snippet: Column 1 Column 2 This row spans both columns
3 - 16 © 2013 Intel Corporation.
Page Layout
Adding Text As depicted in Figure 12, you can add text to page by dragging and dropping the Text widget from the Controls-Media panel and dropping it onto the design canvas.
Figure 12: Adding text to an app page.
The Text Settings panel enables you to perform the following functions:
Replace the Lorum ipsum placeholder text
Set the id property of the generated element.
Set display and visibility properties
Define CSS Styles for text and margins
Create define media queries that apply styles based on screen resolution (covered in unit 9)
3 - 17 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Applying Typographic Styles As illustrated in Figure 13, the WYSIWYG interface enables you to define typographic styles for your page elements. Configurable options include:
Font Size
Font Style
Font Weight
Color
Font Family
Text Decoration
Text Align
Line Height
Figure 13: Defining typographic styles
Style classes that are defined for one element can be applied to other elements in the WYSIWYG designer. You'll learn how to extend these styling capabilities via Code View in unit 9.
Adding Images The IMG widget enables you to add jpg, png, or gif images to your content. As depicted in Figure 14, any images that have been placed in your project's folder structure may be selected from the drop-down list in the IMG Settings panel. You can also configure Alt text (to meet section 508 accessibility requirements), edit a visible caption, and set the generated elements DOM identifier. Figure 14: Configuring an IMG widget
3 - 18 © 2013 Intel Corporation.
Page Layout
Walkthrough 3-2: Adding Content In this lab, you will perform the following tasks:
Add text content to the home page.
Define typographic styles.
Add an image to the home page.
Steps Open a Project
1. Open Intel XDK New 2. Click on the word PROJECTS in the topleft corner of the GUI. 3. Click the Open a Project button.
Figure 15: Your goal
4. Select the following file: /ftIntelXdkNew/walk/walk3_2/walk3_2.xdk
5. Click the open button. Add Text
6. From the Controls > Media panel, drag a Text widget and drop it onto the design canvas, placing it between the header and footer. 7. Open walk3_2/resources/homepagetext.txt in Code view. 8. Copy the contents of the first paragraph of homepagetext.txt to your clipboard. 9. Open index.html in Design view. 10. In the Design canvas, click on the Text widget. 11. In the Text Settings panel, paste the contents of your clipboard into the Text field. Define Typographic Styles
12. In the Text Settings panel, click on the Text button and select New... 13. Enter a style class name of “homepage” 14. Enter the following properties:
Font-Size: Font-Family: Line-Height:
0.9em sans-serif normal 3 - 19 © 2013 Intel Corporation.
Fast Track to Intel XDK New Add an Image
15. From the Controls > Media panel, drag an IMG widget and drop it underneath the Text block on the Design Canvas. 16. Configure the following IMG settings:
Src: Resources/Beer.jpg Alt: Beer: The cause and solution to all of our problems
Add a Second Text Widget
17. From the Controls > Media panel, drag a Text widget and drop it onto the design canvas, placing it directly underneath the image. 18. Open walk3_2/resources/homepagetext.txt in Code view. 19. Starting with the second paragraph, copy the contents of homepagetext.txt to your clipboard. 20. Open index.html in Design view. 21. In the Design canvas, click on the Text widget. 22. In the Text Settings panel, paste the contents of your clipboard into the Text field. Apply the homepagetext Text Style
23. In the Text Settings > Styles panel, click on the Text menu and select homepagetext as illustrated below:
24. Save the file 25. Click the Emulate button. Your app should appear similar to Figure 15 on the previous page. – End of Walkthrough --
3 - 20 © 2013 Intel Corporation.
Page Layout
Unit Summary
jQuery mobile uses a combination of HTML tags and HTML5 custom data properties to implement a page-based architecture for layout.
jQuery mobile behaviors are typically defined by adding custom data properties to html elements.
When pages are created in the mobile browser's DOM, the “pagecreate” event is fired.
Every html page in your app must be linked to a mobile JavaScript framework.
Page headers and footers can be docked into a fixed position.
JQM can automatically add a “back” button on a header.
Use the ButtonGroup widget to easily add navigation to your apps.
JQM supports slide and fade transitions between pages.
Buttons may be styled with icons and themes.
The Intel XDK App Designer enables you to lay out your pages using a rows/column metaphor.
Style classes that are defined for an element can be applied to other elements within your app.
The App Designer will automatically locate all images that have been placed within your project folder.
3 - 21 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Review 1. Pages do not need to be linked to a mobile javascript framework (true/false)
2. You cannot define custom icons for your buttons (true/false)
3. An HTML file may only contain a single page view (true/false)
4. The App Designer generates HTML table markup to ensure compatibility with the broadest range of browsers (true/false)
5. How can you impement a page transition animation?
3 - 22 © 2013 Intel Corporation.
Unit 4: Working with Data
Unit Objectives After completing this unit, you should be able to:
Use jQuery Mobile to make asynchronous data requests
Output structured data into a ListView
Transfer data read from an application server into an HTML5 Local SQL Database
Read data from the device's Contacts list
Making External Data Requests Working with the ListView Caching Data in a Local Database Importing Data from the Contacts List
Unit Topics
4-1 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Making External Data Requests Jquery mobile supports making two different types of data requests from a web browser:
Use the $.ajax() method to read and post external data using Javascript's native XmlHttpRequest() method.
Use the $.getJSON() method to read structured data in JavaScript Object Notation format (JSON) from a remote domain by dynamically injecting a tag into your application's DOM.
Making AJAX Data Requests from JQM You can make AJAX requests to a server using the $.ajax() method illustrated below. $.ajax() should be used whenever you need to retrieve external data that's not in JSON format or if you need to POST data to a server. $.ajax({ url: 'myservice.cfc?method=getdata', type: 'GET', dataType: 'json', error : function (){ alert('there was an error'); }, success: function (data) { console.log(data); // debugger; } });
Note the following:
The callback to the success or error handler is executed asynchronously.
The success handler receives the data as a javascript object. You do not need to use the eval() method or an equivalent to parse the JSON into a native JavaScript object.
Use the console.log() method to output results to your debugger. Alternately, you can use the debugger; command to set a programmatic breakpoint.
Web apps will not be able to make cross-domain requests unless the remote host supports cross-origin resource sharing (CORS)
Cordova-based apps will need to whitelist all external domains (covered in unit 10).
4-2 © 2013 Intel Corporation.
Working with Data
Making JSONP Requests from JQM You can make cross-domain JSON-P requests from jQuery using the $getJSON method illustrated below: var url='http://someurl/someAppServerService.php?'; $.getJSON(url + 'method=somemethod&callback=?', function(data) { console.log(data); } );
Note that the ? Used in the callback url is replaced at runtime by a jQuery with a randomly generated set of numbers. JSONP GET requests therefore typically resemble the following:
Figure 1: A typical JSONP Request.
Use $.getJSON() whenever you need to retrieve JSON data from a remote domain that does not support CORS.
4-3 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Deferring Data Requests Until Page Activation One of the challenges that you will have with building larger, more complicated JQM apps is minimizing the amount of memory that your app consumes. One strategy for managing memory is to not load data until it is absolutely needed. For instance, if a data request is required to populate a list view, you might want to defer making the request until such time as the page is requested by the user. The typical pattern to trigger the execution of code on page visibility is the following: $(document).bind('pageinit', function() { $(document).on( "pagechange", function(event,page) { switch(page.toPage[0].id) { case 'page1' : // initialize page 1 break; case 'page2' : // initialize page 2 break; }; }); });
In the preceding code snippet, the pageinit event is triggered once the index.html page has completed loading in the browser. In jQuery Mobile, listening for pageinit event should be used in lieu of document.onready(). The pagechange event is triggered whenever an anchor tag is activated by a user, causing jQM to intercept the request and load the requested html page. You can parse the second argument returned to the pagechange event handler to determine the id property contained within the div tag containing the data-role=”page” attribute as illustrated below:
4-4 © 2013 Intel Corporation.
Working with Data
Developing Javascript Classes to Encapsulate Event Handlers As your application grows in size, you may find it useful to bundle all of a page's event listeners into a single Javascript object. This approach has several benefits:
Encapsulation
Protected variable scoping
Code Reuse
The general approach to implement this coding style is to define a global javascript object in your index.html file for each “page” of your app. For example, you might define a Javascript object container for your beerspage related subroutines as illustrated by the following: var BeersPage = { };
Inside of the JavaScript object, you'll place all of the page's dynamic properties and methods: var BeersPage = { initialized: false, init: function() { this.initialized = true; } }
Note that in the preceding case, the init() method refers to the initialized variable using the this scope as both the init() method and the initialized property are both members of the same object. You could then invoke the init() method for beersPage through the following syntax: BeersPage.init();
You will use this development methodology throughout this course.
4-5 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Caching Data In a Local Variable From a performance perspective, HTTP transactions from mobile devices are very costly. You can reduce external calls by caching data in memory, html5 local storage, or html5 local database. It's relatively straightforward to extend our class system in order to persist remote data in a local variable. In the following code, we've extended the Beers class described on the prior page by adding an additional property named data. Once the JSON-P data has been successfully read from the server, it's placed into the data property where it can be referred for the duration that the app remains running. A strategically placed if() condition prevents the remote data from being fetched more than once. var Beers = { initialized: false, data : null, init: function() { var me = this; // use closure to retain scope if (me.data === null && !me.initialized) { me.initialized = true; var url= "http://xdktraining.com/ftxdknew/data/beer.cfc"; $.getJSON(url + "?method=getBeerList&callback=?", function(data) { me.data = data; } ); } } }
4-6 © 2013 Intel Corporation.
Working with Data
Walkthrough 4-1: Making External Data Requests In this walkthrough, you will start developing the “Beer List” feature of the application.
Make a local data request to retrieve a list of Beers that's encoded in JSON format.
Display the results from the transaction in the debugger.
Steps Open the Project
1. Open Intel XDK New 2. Click on the word PROJECTS in the top-left corner of the GUI. 3. Click the Open a Project button. 4. Select the following file: /ftIntelXdkNew/walk/walk4_1/walk4_1.xdk
Define a pageinit Event Listener
5. Open the following URL and review the output: http://xdktraining.com/ftxdknew/data/beer.cfc? method=getBeerList
6. Open the index.html file in Code view. 7. Immediately prior to the closing tag, insert a Javascript block:
8. Inside the , listen for the pageinit event to be triggered by the index page: Your code should appear similar to the following: $(document).bind('pageinit', function() { });
4-7 © 2013 Intel Corporation.
Fast Track to Intel XDK New
9. Inside the event handler function, define a variable named page that retrieves the file name of the current url. Your code should resemble the following: var page = event.target.baseURI.split('/'); page = page[page.length - 1];
10. After the code that you inserted from the prior step, check for the existence of the global variable App.initialized. If the variable has bot been defined, set it equal to true and call a method named App.init() which you will define later in this exercise. $(document).bind('pageinit', function(event,obj) { var page = event.target.baseURI.split('/'); page = page[page.length - 1]; if (!App.initialized) { App.initialized = true; App.init(); } }
11. After the code that you inserted from the prior step, insert a switch/case statement that evaluates the contents of the page variable and checks it against each of your application's pages. switch (page) { case 'index.html' : break; case 'beers.html' : break; case 'friends.html' : break; case 'drink.html' : break; }
Create the App Class and Get the Data
12. Where indicated by the comment, define an object named App with the following properties:
initialized: false beers: null
13. Verify that your code appears as follows: var App = { initialized: false, beers: null }
4-8 © 2013 Intel Corporation.
Working with Data Retrieve and Cache the Data
14. Define two method for the App object named init() and cacheBeers(). var App = { initialized: false, beers: null, init: function() { }, cacheBeers: function() { } }
15. Invoke the cacheBeers() method from the init() method as illustrated below: var App = { initialized: false, beers: null, init: function() { this.cacheBeers(); }, cacheBeers: function() { } }
Make a JSON-P Request
16. Inside the cacheBeers method, define a local variable named me that points to the Beers class and set the initialized property to true. var me = this;
17. Immediately after the code that you inserted from the prior step, make a JSON-P request to the following URL, placing the result in the Beers class data property and dumping its results to the debugging console. http://xdktraining.com/ftxdknew/data/beer.cfc? method=getBeerList&callback=?
18. Verify that your code appears similar to the following: cacheBeers: function() { var me = this; var url = "http://xdktraining.com/ftxdknew/data/beer.cfc"; $.getJSON(url + "?method=getBeerList&callback=?", function(data) { me.beers = data; console.log(data); } ); }
19. Save the file.
4-9 © 2013 Intel Corporation.
Fast Track to Intel XDK New
20. Click on the Emulate tab. 21. Open the debugger. You should see the array output from the data request as illustrated in Figure 2:
Figure 2: Inspecting the results of the JSON-P request.
22. Type the following code in the debugger's console view to output the list of Beers: App.beers
--End of Walkthrough--
4 - 10 © 2013 Intel Corporation.
Working with Data
Working with the ListView Use the ListView widget, depicted in Figure 3, to display the contents of either unordered or ordered lists. Add a data-role=”listview” property to a or entity in order to instantiate a ListView: Aaron Adam Alexander
Figure 3: A simple listview
Grouping Lists You can create grouped lists as illustrated in Figure 4 by applying the data-autodividers="true" property to the entity as illustrated below. Note the following:
Grouped items must be placed in alphabetical order.
By default, the group name will be the uppercased first character of the item's text.
Drucker, Aidan Drucker, Dylan Drucker, Steve Gallerizzo, David
Figure 4: Using autodividers
4 - 11 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Defining Custom Group Names The following code snippets illustrate how to define custom group names by completing the following steps:
Add a custom data attribute to your entities that define the group name.
Define an autodividersSelector method that dynamically returns the group name based on list item properties.
Programmatically refresh the list
Markup:
Figure 5: Defining custom group names
Drucker, Aidan Drucker, Dylan Drucker, Steve Watts, David Watts, Tiberius
Script: $("#personsList").listview({ autodividers: true, autodividersSelector: function(li) { return li.attr("data-lastname"); } }); $("#personsList").listview("refresh");
Dynamically Populating a List from JSON In most use cases you'll need to dynamically construct a list from data that was returned from an AJAX or JSON-P call. In order to pull this off, you'll usually need to perform the following tasks:
Dynamically sort the array returned from the AJAX/JSON-P call.
Construct a template for generating list item markup.
Generating html markup for each item and append to the ListView.
Refresh the ListView.
4 - 12 © 2013 Intel Corporation.
Working with Data
Dynamically Sorting an Array Use Javascript's array.sort() method to sort an array of objects so that it may be grouped correctly into a list. Passing a function as an argument to the sort() method enables you to sort based on two or more fields – typically the field that you're grouping on, and the label for each list item. In this context, Javascript automatically passes in two objects to your custom function. The function, in turn, must return the following:
-1 if a < b
0 if a == b
1 if b > a
The following code snippet illustrates an ascending alphabetical sort for a group-based sort. data.sort(function(a,b) { if(a.groupfield == b.groupfield) { return (a.label < b.label) ? -1 :(a.label > b.label) ? 1:0; } else { return (a.groupfield < b.groupfield) ? -1 : 1; } });
Constructing a Template Using templates improves code readability while reducing syntax errors that inevitably result from performing complex multi-variable string concatenation with the “+” operator. While, jQuery 1.x no longer supports built-in template methods, but you can easily add a substitute by extending JavaScript's String class as illustrated by the following snippet: String.prototype.format = function () { var args = arguments; return this.replace( /\{(\d+)\}/g, function (m, n) { return args[n]; } ); };
This String.format() method enables you to easily perform dynamic string replacement of placeholders through the following invocation: var template = "The rain in {0} falls mostly on the {1}"; template.format("Spain","plain"); // output: The rain in Spain falls mostly on the plain
4 - 13 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Dynamically Generating List Items The problem with using the aforementioned syntax, however, is that creating a multi-line “template” remains somewhat error-prone since you can't insert line breaks within a Javascript string. Sharing the template across multiple applications would also be problematic. The solution is to break the template out into a separate script as illustrated below: {1}
You can then convert the contents of the script to an HTML string using jQuery's html() method: var itemTemplate = $("#tplListItem").html();
Now that you've got your template in place, you can easily loop through your dataset, appending markup to your list. Note that once you have completed adding list items, you must programmatically refresh the list as illustrated by the following example: var list = $('ul#personsList'); list.empty(); // remove all items for (var i=0; i< data.length; i++) { var item = data[i]; var str = itemTemplate.format(item.id, item.name); list.append(str); } // redraw the list – absolutely REQUIRED!!! list.listview("refresh");
4 - 14 © 2013 Intel Corporation.
Working with Data
Adding a Search Filter Adding the data-filter="true" property to a list causes the jQuery Mobile framework to prepend a search box that filters out list items that don't contain the text that the user types into the box. The input's placeholder text defaults to "Filter items..." Drucker, Aidan Drucker, Dylan Drucker, Steve Watts, David Watts, Tiberius
Displaying Counts and Carats in a List The framework includes text formatting conventions for common list patterns like header/descriptions, secondary information and counts through semantic HTML markup.
To add a count indicator to the right of the list item, wrap the number in an element with a class of ui-li-count
To add a carat indicator, insert the following into each list item:
Listening for a Tap Event Listen for tap events on list items by using the bind() method as illustrated below: $('#personsList > li').bind('tap', function(e) { var targetValue = this.getAttribute('data-lastname'); alert("You selected the " + targetValue + " family"); });
4 - 15 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Walkthrough 4-2: Dynamically Generating Lists In this walkthrough, you will enhance your application by outputting the data that you retrieved in the previous walkthrough into a ListView.
Generate a list view
Sort an array of records
Output records into a grouped list
Steps Open the Project
1. Open Intel XDK New 2. Click on the word PROJECTS in the top-left corner of the GUI.
Figure 7: Output a list of Beers, grouped by country of origin.
3. Click the Open a Project button. 4. Select the following file: /ftIntelXdkNew/walk/walk4_2/walk4_2.xdk
Sort the Dataset
5. Where indicated by the comment, sort the dataset. Group on the country field Sort by the name field 6. Your code should appear similar to the following: data.sort(function(a,b) { if(a.country == b.country) { return (a.name < b.name) ? -1 : (a.name > b.name) ? 1 : 0; } else { return (a.country < b.country) ? -1 : 1; } });
7. Save the file and run the app in the emulator. 8. Open the debugger's console view. 9. Inspect the results from the console.log(). You should see that the data retrieved from the getJSON() method has been sorted by country name and beer name. 10. Click on the Develop tab.
4 - 16 © 2013 Intel Corporation.
Working with Data Create the List
11. Open the Beers.html file in Design mode. 12. From the Controls > Widgets panel, drag a ListView widget and drop it onto the design canvas between the page's header and footer. 13. In the ListView Settings panel, turn on the following checkboxes:
Filter Auto Dividers id
14. Enter the following id for the ListView: beerslist
15. Save the file and test the application in the emulator. The list should appear. Define a List Item Template
16. Where indicated by the comment, define a template for the list items that you need to dynamically instantiate. Assign an id property to the template of “tplBeerItem” The output from the template needs to contain markup similar to the following: Samuel Adams Boston Lager 0
17. Verify that your code appears similar to the following: {2} {3}
Populate the List
18. Return to Develop mode. 19. Open index.html in Code view. 20. Inside the populateList() method, define a variable named list that points to the ListView component. var list = $('#beerslist > ul');
21. Clear the default list items from the list. Your code should appear similar to the following: list.empty();
22. After the code that you inserted from the prior step, define a variable named beerTemplate that points to the html in the tplBeerItem element. var beerTemplate = $("#tplBeerItem").html();
4 - 17 © 2013 Intel Corporation.
Fast Track to Intel XDK New
23. After the code that you inserted from the prior step, loop through the data retrieved from the JSON-P transaction. Your code should appear similar to the following: for (var i=0; i Form palette, drag a button widget and drop it on the right edge of the page header. 43. Configure the following properties:
Icon: ui-icon-plus Icon Position: Icon only id: btnAdd
44. Go to Code mode and locate the generated markup for the button. 45. Add the following attributes to the anchor tag that wraps the add button:
href=”contactform.html” data-transition=”flip”
46. Save the file. 47. Return to index.html in Code mode. 48. In the Contacts object, at the end of the init() method, bind a tap event handler to the “Add Contact” button. $("#btnAdd").bind("tap", function(e) { });
49. Inside the button tap callback function, set the friendId property in the ContactForm object to null. $("#btnAdd").bind("tap", function(e) { ContactForm.friendId = null; });
50. Save the file and test in the emulator. – End of Walkthrough --
5 - 11 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Validating Form Input Unfortunately, mobile browsers do not support the native form field validation properties that are stipulated as part of the HTML5 specification. You can adapt the jQuery Validation Plugin, however, to easily ensure that users are entering data in the format that you intended. The jQuery Validation Plugin is maintained by Jörn Zaefferer, a member of thejQuery team, lead developer on the jQuery UI team and maintainer of QUnit. It was started back in the early days of jQuery in 2006, and updated and improved since then. The plugin comes bundled with a useful set of validation methods, including URL and email validation, while providing an API to write your own methods. All bundled methods come with default error messages in english and translations into 37 other languages. It's free to use under an MIT license and hosted at http://jqueryvalidation.org/ The plugin validates the following patterns for correctness: Type
Description
required
Makes data input required.
remote
Requests a resource check the element for validity.
minlength
Requires strings to be a specified minimum length
rangelength Requires strings to be within a specified size range. email
Requires the string to be a properly formatted email address.
url
Requires the input string to be a properly formatted url.
date
Requires the input string to be a valid date.
dateISO
Requires the input to be a properly formatted ISO date
number
Requires the input to be a decimal number
digits
Makes the element require numeric values only.
creditcard
Validates that the creditcard number has been properly formatted.
equalTo
Requires the input data in one field be identical to the input data in another field.
It also comes with extensions to validate other data types as well, including US phone numbers. 5 - 12 © 2013 Intel Corporation.
Creating Input Forms
Loading the Library You can load the jQuery Validation Library (jquery.validate.js) by simply inserting a tag into your document's section: ...
Adding Validation Rules to Form Fields You can add validation rules to fields by invoking the form.validate() method which requires a javascript object that defines rules, behaviors, and other options. Typical validate() invocations appear as follows: $( "#myform" ).validate({ submitHandler: function(form) { $(form).ajaxSubmit(); }, invalidHandler: function(event,validator) { var errors = validator.numberOfInvalids(); alert("Invalid data in " + errors + " fields"); }, rules: { lastName: { required: true } }, messages: { lastName: "Please enter you family name" } });
In the preceding snippet, note the following:
The submitHandler is invoked when the the user presses the form's submit button and all form fields pass validation.
The invalidHandler is called when the form is submitted when the user presses the form's submit button but not all fields have passed validation.
The rules object defines data validation rules on form fields. In this case, “lastName” is the id of a text field.
The messages object enables you to define custom validation error messages.
5 - 13 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Requiring Data Input You can require data input on a field by adding the required attribute to any field as illustrated below:
You can also attach the required validation rule to a field by invoking a form's validate() method (injected by the plugin): $( "#myform" ).validate({ rules: { lastName: { required: true } } });
Validating Email Addresses Require that a properly formatted email address be entered into a form field by applying the following validation rules: $( "#myform" ).validate({ rules: { userEmail: { required: true, email: true } } });
5 - 14 © 2013 Intel Corporation.
Creating Input Forms
Validating String Length You can set validation on string field length by using the rangelength validator as illustrated below: $( "#myform" ).validate({ rules: { lastName: { required: true, rangelength: [2,20] } } });
Validating Numeric Input Require that input data may only contain characters in the range of 0-9 by applying the digits rule as noted below: $( "#myform" ).validate({ rules: { zipcode: { required: true, digits: true } } });
Programmatically Execute Validation Rules You can invoke form field validating programmatically by invoking the validator.form() method as illustrated below. var validator = $("form#contactform").validate(); validator.form();
5 - 15 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Configuring Validation Message Placement and Theming By default, error validation messages are injected into the form field's element. You can modify this behavior on a field-level basis by specifying an errorPlacement method. The following example moves the validation method into a parent for a element with an id of “beerid”: var form = $("form#contactform"); form.validate({ errorPlacement: function(error, element) { if (element.attr("name") === "beerid") { error.insertAfter($(element).parent()); } else { error.insertAfter(element); } } });
As illustrated in the following snippet, you can style the error message by defining a css class on the label.error selector. label.error { float: left; color: red; padding-top: .5em; vertical-align: top; font-weight:bold }
5 - 16 © 2013 Intel Corporation.
Creating Input Forms
Walkthrough 5-2: Implementing Form Validation In this walkthrough you will add data input validation rules to the contact form.
Load the jQuery Validation plugin.
Define validation rules for form fields
Customize the display of error messages
Programmatically trigger form validation
Steps Open the Project
1. Open Intel XDK New 2. Click on the word PROJECTS in the top-left corner of the GUI. 3. Click the Open a Project button. 4. Select the following file: /ftIntelXdkNew/walk/walk5_2/walk5_2.xdk
Add an ID Property to Your Form
5. Open the contactform.html file in Code view. 6. Add the following attribute to the element: id="contactform"
Define the Validation Rules
7. Open the index.html file in Code mode. 8. On line 34, insert a tag to load the jQuery Validation library.
9. Inside the ContactForm object, underneath the populateBeerField method, define a function named initValidation. 10. Inside the initValidation method, define a local variable named form that points to the form that you defined in the prior walkthrough. var form = $("form#contactform");
5 - 17 © 2013 Intel Corporation.
Fast Track to Intel XDK New
11. After the code that you inserted in the prior step, invoke form.validate and configure the following rules:
Data input for the lastName field is required Data input for the lastName field must have between 2 and 20 characters Data input on the firstName field is required Data input on the address field is required Data input for the zipcode field may only be digits
12. Review your code to ensure it appears similar to the following: initValidation: function() { var form = $("form#contactform"); form.validate({ rules: { lastName: { required: true, rangelength: [2,20] }, firstName: { required: true }, address: { required: true }, zipcode: { required: true, digits: true } } }); }
13. Inside the init() method of the ContactForm object, invoke the initValidation() method. var ContactForm = { init: function() { this.populateBeerField(); this.initValidation(); }, populateBeerField: function() { // omitted for brevity }, initValidation: function() { // omitted for brevity } }
5 - 18 © 2013 Intel Corporation.
Creating Input Forms Programmatically Validate the Form
14. Define an additional method of the ContactForm class named submitForm() 15. Inside the submitForm() method, execute the validation rules that you defined in step 9 and output the number of errors to an alert box. Your code should appear similar to the following: submitForm: function() { var validator = $("form#contactform").validate(); validator.form(); alert(validator.numberOfInvalids()); }
16. Save the file Link the Save button to the submitForm Method
17. Open contactform.html in Design mode. 18. Click on the button to the right of the Friends with Beer header and configure the following property:
id: btnSave
19. Save the file. 20. Return to index.html in Code view. 21. Inside the init() method of the ContactForm object, define a tap event handler for the save button that invokes the submitForm method. Your code should appear similar to the following: init: function() { this.initialized=true; this.populateBeerField(); this.initValidation(); var me = this; $("#btnSave").bind("tap", function(e) { me.submitForm(); }); }
22. Save the file and test the app in the emulator. Clicking the save button should trigger the display of the error validation messages. Theme the Error Messages
23. Return to index.html in Code mode. 24. Add the following style definition to the block on line 14. label.error { float: left; color: red; padding-top: .5em; vertical-align: top; font-weight:bold }
5 - 19 © 2013 Intel Corporation.
Fast Track to Intel XDK New
25. Save the file and re-test the app in the emulator. You should see that your error messages are now formatted. – End of Walkthrough --
5 - 20 © 2013 Intel Corporation.
Creating Input Forms
Persisting Form Data Transactional CRUD interfaces require that you support four major functions:
Create new records
Read and display records
Update pre-existing records
Delete records
In order to update pre-existing records, you'll typically need to populate a form with data, allow the user to edit the record, and then post it back to the server.
Dynamically Setting Form Field Values To programmatically set the value of an input field, invoke the field's .val() method as illustrated below: $("#firstName").val("Steve");
To programmatically set the value of other types of JQM form controls, you must first manipulate the native control and then use the widget's refresh method to synchronize the enhanced control with its native html counterpart as illustrated by the following examples: // updating checkboxes var myCheckbox = $("input[type='checkbox']#check1") myCheckbox.prop("checked",true).checkboxradio("refresh"); // updating radio buttons var myRB = $("input[type='radio']#rb1") myRB.prop("checked",true).checkboxradio("refresh"); // select controls var myselect = $("select#beerid"); myselect.selectedIndex = 1; myselect.selectmenu("refresh");
Dynamically Getting All Form Field Values The form.serializeArray() method creates a JavaScript array of objects consisting of your form field names and their associated input values. var formData =
$("form#contactform").serializeArray();
5 - 21 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Posting Data to an Application Server In jQuery Mobile, form submissions are automatically handled using Ajax whenever possible, resulting in a smooth transition between the form and the result page. If left unspecified, a form's method will default to get and its action will default to the current page's relative path ($.mobile.path.get()) Note that forms accept attributes for transitions just like anchors, so you can attach a data-transition="pop" and datadirection="reverse". If you do not want a page transition to occur or simply want more control over the submission process, you'll need to invoke the $.ajax() method as illustrated by the following example: submitForm: function() { var form = $("form#contactform"); var validator = form.validate(); validator.form(); if (validator.numberOfInvalids() == 0) { $.ajax({ type: "POST", url: "http://www.xdktraining.com/savecontact.cfm", data: form.serialize(), success: function(data) { alert("Record Saved"); }, error: function(XMLHttpRequest, textStatus, err){ var msg = ''.concat( 'status:', XMLHttpRequest.status, '\n', 'status text: ', XMLHttpRequest.statusText ); alert(msg); } }); } }
Note the following from the preceding example:
Call the form.serialize() method to retrieve all form field values and serialize them into a single encoded string for posting to the app server.
You should always include a failure handler in your AJAX transactions
5 - 22 © 2013 Intel Corporation.
Creating Input Forms
Walkthrough 5-3: Inserting and Updating Records In this walkthrough you will add data input validation rules to the contact form.
Insert contact records into the WebSQL database
Set the values of form fields
Update contact records in the WebSQL database
Programmatically load pages
Steps Open the Project
1. Open Intel XDK New 2. Click on the word PROJECTS in the top-left corner of the GUI. 3. Click the Open a Project button. 4. Select the following file: /ftIntelXdkNew/walk/walk5_3/walk5_3.xdk
Add Disabled Lat/Lng Fields to the Form
5. Open contactform.html in Design mode. 6. Drag an Input widget from the Controls > Form palette and drop it directly underneath the beers select box on the design canvas. 7. Configure the following properties:
Label: Lat (unchecked) Placeholder: Latitude Name: lat id: lat
8. Drag an Input widget from the Controls > Form palette and drop it directly underneath the beers select box on the design canvas. 9. Configure the following properties:
Label: Lng (unchecked) Placeholder: Longitude Name: lng id: lng
10. Go to code mode and add a disabled property to the lat and lng fields. 5 - 23 © 2013 Intel Corporation.
Fast Track to Intel XDK New Create a New Record
11. Open the index.html file in Code mode. 12. Refactor the ContactForm.submitForm() method as indicated below: submitForm: function() { var form = $("form#contactform"); var validator = form.validate(); validator.form(); if (validator.numberOfInvalids() == 0) { } else { alert("Invalid data input"); } }
13. Inside the if() block, use the form.serializeArray() method to serialize all of the form fields into a local variable named fields. var fields = form.serializeArray();
14. Immediately after the code that you inserted in the last step, append the values of the disabled lat and lng fields to the fields array. fields[fields.length] = { name: 'lat', value: $('#lat').val() }; fields[fields.length] = { name: 'lng', value: $('#lng').val() };
15. Immediately after the code that you inserted in the last step, invoke the FriendsWithBeerDB.writeRecord() method to transfer the data from the fields variable into your webSQL database. FriendsWithBeerDB.writeRecord( 'friend', this.friendId, fields, function() { } );
16. Inside the writeRecord() callback function, use the alert() method to output a message to the user and then reload the contacts.html page.
5 - 24 © 2013 Intel Corporation.
Creating Input Forms
17. Review your submitForm() method to ensure that it appears similar to the following: if (validator.numberOfInvalids() == 0) { var fields = form.serializeArray(); fields[fields.length] = { name: 'lat', value: $('#lat').val() }; fields[fields.length] = { name: 'lng', value: $('#lng').val() }; FriendsWithBeerDB.writeRecord( 'friend', this.friendId, fields, function() { alert("Record Saved"); $.mobile.changePage('friends.html'); } ); } }
18. Save the file and test the application in the emulator. You should now be able to create new contact records! Attach a tap event listener to the List Items in the Friends List
19. In the FriendsList.displayList() method, where indicated by the comment, attach a tap event listener to the list items. $('#friendsList > li').bind('tap', function(e) { });
20. Inside the event handler, retrieve the numeric identifier in the list item and transfer its value to the ContactForm.friendId property. $('#friendsList > li').bind('tap', function(e) { ContactForm.friendId = this.getAttribute('data-value'); });
21. Immediately after the code that you inserted in the prior step, programmatically change the page to contactform.html $('#friendsList li').bind('tap', function(e) { var ContactForm.friendId = this.getAttribute( 'data-value'); $.mobile.changePage('contactform.html'); });
22. Save the file and test in the emulator. Clicking on an item in the Friends list should now transfer control to the data entry form. Load Data Into the Form
23. Add a new method named loadRecord to the ContactForm object. 5 - 25 © 2013 Intel Corporation.
Fast Track to Intel XDK New
24. Inside the loadRecord() method, define an if() block that evaluates whether the value of the ContactForm.friendId property is null. loadRecord: function() { if (this.friendId != null) { } }
25. Inside the if() block, invoke the FriendsWithBeerDB.runQuery() method to retrieve the record from the WebSQL friends table where the friendId is equal to the friendId stored in the ContactForm object. loadRecord: function() { if (this.friendId != null) { var sql = "select * from friend where id = {0}"; sql.format(this.friendId); FriendsWithBeerDB.runQuery(sql, function(records) { }); } }
26. Inside the runQuery callback function, loop through the properties of the first record that was returned from the database query, transferring the values from the query result into the form. loadRecord: function() { if (this.friendId != null) { var sql = "select * from friend where id = {0}"; sql.format(this.friendId); FriendsWithBeerDB.runQuery(sql, function(records) { var rec = records[0]; for (var i in rec) { $("#" + i).val(rec[i]); } }); } }
27. Immediately after the for-loop that you entered in the prior step, refresh the beerId select menu. $("#beerId").selectmenu("refresh", true);
Invoke the loadRecord() method
28. Inside the ContactForm.init() method, invoke the ContactForm.loadRecord() method. init: function() { this.initialized=true; this.populateBeerField(); this.initValidation(); this.loadRecord(); var me = this; $("#btnSave").bind("tap", function(e) { me.submitForm(); }); } 5 - 26 © 2013 Intel Corporation.
Creating Input Forms
29. Save the file. 30. Test the application. You should now be able to edit existing contact records. – End of Walkthrough --
5 - 27 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Summary
Intel XDK New and jQuery Mobile support all HTML5 form element types.
jQuery Mobile replaces standard checkbox, radio button, and select field controls with controls that have been optimized for a mobile device.
Native HTML5 form field validation is not supported by most mobile browsers.
You can easily adapt the jQuery Validation Plugin to work with jQuery mobile.
The jQuery Validation Plugin supports validating basic patterns including email address, required data input, string length, numeric input, and more.
You can persist data in memory, transmit form information to an application server, or store it in WebSQL or HTML5 localStorage.
5 - 28 © 2013 Intel Corporation.
Creating Input Forms
Unit Review 1. The name and id properties of an input field should always be identical (true/false)
2. Which method do you invoke in order to get the value of a form field?
3. Which method do you invoke in order to set the value of a form field?
4. You must call the refresh method of a text input field after changing its value (true/false)
5. Which method can you invoke to easily combine the values from all of your form fields in order to transmit them to a server?
6. What are the relative advantages/disadvantages to storing information locally in WebSQL instead of posting it to an application server?
7. Describe how to populate a control with options that are read dynamically from an application server.
5 - 29 © 2013 Intel Corporation.
(This page intentionally left blank)
Unit 6: Adding GEO Features
Unit Objectives After completing this unit, you should be able to:
Load the Google API
Instantiate a map
Programmatically geocode an address from data input by the user
Programmatically center a map and understand the basic Google map configuration options
Add overlays to a map
Getting Started with Google Maps Deploying a Simple Map Programmatically Geocoding Addresses Adding Overlays and Map Markers
Unit Topics
6-1 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Getting Started with Google Maps The Google Maps Javascript API is a free service that lets you embed Google Maps in your own web pages. Version 3 of the API was specifically designed to support mobile devices as well as traditional desktop browser applications. It includes a number of utilities for manipulating maps and adding content to the map through a variety of collateral services. To facilitate the integration of Google Maps into a jQM-based app, use the Google Maps v3 plug-in for jQuery and jQM, available at http://code.google.com/p/jquery-ui-map/.
Working with the Google Maps Javascript API The Google Maps Javascript API V3 now comes in three different versions. All versions support the same features, however, they are limited in the number of requests that they will process during a 24-hour period. In the current model each of these API versions is limited to a number of Page Views a day and a max number of queries per second (QPS). Google considers a “Page View” to be an instance of the Maps Javascript API being loaded in the browser or a single request for a static map. It is important to note that the API contains many different web services and that making request to those collateral services (e.g. the Google Geocoding service) will also count against your Page View limit. Page View Limitations for the Google Maps Javascript API V3 are as follows: 1. The Free Version – Limited to 1000 Page Views a day per individual IP address, across all services 2. Purchased Key Version – Users of the API can purchase an overall daily Page View quota, that is not limited by IP address 3. Google Maps for Business API – 100,000 Page Views a day per each different service all different API services: •
Directions API
•
Distance Matrix API
•
Elevation API
•
Geocoding API
•
Places API
Regardless of whether you use the free or paid-for versions of the API you will be limited to a maximum of 10 queries per second per API. You can purchase more bandwidth on an as-needed basis.
6-2 © 2013 Intel Corporation.
Adding GEO Features
Using the Purchased Key Version of Google Maps The free version of Google Maps v3 enables you to load the API using the following syntax:
However, if you wish to track map usage or you need a larger number of daily Page Views then utilizing the Purchased Key Version. API keys are tied to both your Google account and the domain name from where your application will be hosted. The process to obtain an API key can be found at the following URL: https://developers.google.com/maps/documentation/javascript/tutorial#api_ key As noted in the instructions, you are allowed to use the key from any domain, but it is strongly encouraged to restrict the usage from the domain(s) you manage. Your Purchased Key license comes with the following restrictions: 1. 25,000 per Page View per day limit on map loads. 2. The Maps API does not include advertising. 3. Your service must be freely accessible to end users. Read terms of use for details governing this. 4. You may not alter or obscure the logos or attribution on the map. 5. Maps should not be used to display illegal activity or reveal personal information
6-3 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Working with the Purchased Key Version of Google Maps When you sign up for a paid API key, you'll be prompted to register a new Project ID. This allows multiple Google services to be tied to a single project/API key for tracking purposes.
Figure 1: Registering a Google Map project
After registering you'll be presented with the following screen which contains your API key.
Figure 2: Generating the Google Maps API Key
Take the API key and inject it into the script tag that loads the maps API as illustrated below:
For additional licensing information, please see: https://developers.google.com/maps/documentation/javascript/usage 6-4 © 2013 Intel Corporation.
Adding GEO Features
Deploying a Simple Map Deploy a Google map in your app by completing the following steps:
Load the Maps JavaScript library
Load the plug-in for jQuery and JQM
Position your map on a page
Place a marker on your map that identifies a location
Loading the Google Maps API The following is a simple example of loading the Google Maps Javascript API V3:
As explained previously, Google Maps Javascript API V3 now allows you to implement a mapping solution without requiring an API key. If you are using an API Key is it important to note the following:
If Maps services are restricted to a specific set of domains, and the load request if performed from a domain that is NOT in that set, you will receive errors upon calling any function from the library.
You must specific true or false for the sensor URL parameter, depending on if the device has Geospatial System (GS) capabilities or not. You should set this to TRUE for mobile apps..
For cases where you are using the Free Version of the Google Maps Javascript API V3, the following call would suffice for most solutions:
6-5 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Loading the Google Maps V3 plugin for jQuery and JQM The Google Maps V3 plug-in for jQuery and JQM is a very flexible, highly customizable, lightweight (3.2kB or 3.9kB for the full) library One of its best features is that you can populate a map from microformats, RDFa or micro-data on your site, which can be used as a fallback if a user doesn't have Javascript enabled. The plug-in is well-documented and acts as an abstraction library for the most commonly used functionality available from Google Maps. The jQuery Google Maps plug-in documentation integrates links to Google Maps Javascript V3 APIs, classes and methods, shortening the learning curve for including Google Maps in a mobile web app. The Google Maps V3 plug-in for jQuery and JQM comes with a variety of libraries, in both full source and minified versions. Depending on your implementation you may use one or more of these: •
jquery.ui.map.js – Main library file
•
jquery.ui.map.extensions.js – Used with Geocoding
•
jquery.ui.map.microdata.js – Used for microdata implementations
•
jquery.ui.map.microformat.js – Used with microformats
•
jquery.ui.map.overlays.js – Used with shapes and KML
•
jquery.ui.map.rdfa.js – Used with RDFa data
•
jquery.ui.map.services.js – Used with Directions and Street view
Each of these libraries has an associated minified version for you to work with. When implementing for JQM you will use a special minified version of the main library file jquery.ui.map.full.min.js. To handle the most basic of map implementations your to implement the plug-in will look like the following:
6-6 © 2013 Intel Corporation.
Adding GEO Features
Placing your map on a page You can instantiate a map into any HTML element that has a unique identifier (typically a ). The map will conform to the defined size of the container. A typical map container would resemble the following:
In order to style the map you will either provide in-line styles for the tag or provide some parameters for the div to constrain the size. In this example, you could include a block at the top of the file, or place the style within a CSS file. The entry for the ID 'map_canvas' could look like this: html { height: 100% } body { height: 100%; margin: 0; padding: 0 } #map_canvas { width: 100%; height: 380px }
When implementing for mobile you will want pay particular attention to the map canvas parameters. Depending on how the styles have been implemented with the application you may have to push the map into a fixed height. Instantiating a map with the JQM Google Maps plugin typically requires you to call a constructor named gmap() as illustrated below. Note the use of #map_canvas which is used to point the map to our “map_canvas” and the use of the mapOptions variable to set some basic parameters for the map,. var mapOptions = { 'center': '38.986000000, -76.940131000', 'zoom': 15, disableDefaultUI: false }; $('#map_canvas').gmap({ center: mapOptions.center, mapTypeId: google.maps.MapTypeId.SATELLITE, zoom: mapOptions.zoom, disableDefaultUI: mapOptions.disableDefaultUI });
6-7 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Setting Options for your Map The Google Maps Javascript API Map class supports over 30 different configuration properties, generally referred to as MapOptions. A full listing can be found here: https://developers.google.com/maps/documentation/javascript/reference#M apOptions At a minimum, the following options must be included when instantiating a new Map object:
zoom (type int) – max zoom value is 19
mapTypeId – indicates the type of map to display
center – center point on the map, in Latitude/Longitude
Refreshing the Map In some user-cases, as illustrated by Figure 3, your map may only partially instantiate. To handle this glitch, invoke the gmap refresh() method after a brief delay to allow the map to initialize. var loc = new google.maps.LatLng( "38.908696", "-77.036527"); $mapContainer.gmap({ center: loc, Figure 3: Partially zoom: 16, mapTypeId:google.maps.MapTypeId.SATELLITE rendered map. }); setTimeout("$('#map').gmap('refresh')",500);
6-8 © 2013 Intel Corporation.
Adding GEO Features
Geocoding a starting position One of the most important MapOptions is the the center option. This option gives the map its starting center latitude and longitude coordinates. You can manually geocode a starting address by going to http://geocoder.us
Figure 4: Manually convert street addresses to lat/lng positions
Using Different Map Types One of the main features of Google Maps are the different map types. In the example below we used a MapOption called MapTypeID to name of the map type displayed. These are defined in the Google API documentation as follows:
ROADMAP (Default) - displays the normal, default 2D tiles of Google Maps.
SATELLITE - displays photographic tiles.
HYBRID - displays a mix of photographic tiles and a tile layer for prominent features (roads, city names).
TERRAIN - displays physical relief tiles for displaying elevation and water features (mountains, rivers, etc.).
The value of the map type is case sensitive and coincides with the different map types you can choose from the standard maps UI. $('#map_canvas').gmap({ 'center': mapOptions.center, 'mapTypeId': google.maps.MapTypeId.SATELLITE, 'zoom': mapOptions.zoom, 'disableDefaultUI': mapOptions.disableDefaultUI }); 6-9 © 2013 Intel Corporation.
Fast Track to Intel XDK New
Customizing the look/feel of a map Another set of commonly used MapOptions are the controls. Google Maps allows you to customize the various controls within your maps. In our example on the previous page we set the disableDefaultUI option to false. This enables the zoom, map type, and street view controls by default. Other supported controls, which allow you more granularity, include the following: Property
Description
streetViewControl
Boolean. The initial enabled/disabled state of the Street View control. This control is part of the default UI, and should be set to false when displaying a map type on which the Street View road overlay should not appear (e.g. a non-Earth map type).
panControl
Boolean. The enabled/disabled state of the Pan control.
scaleControl
Boolean. The initial enabled/disabled state of the Scale control.
mapTypeControl
Boolean. Buttons that let the user toggle between map types (such as Map and Satellite). There are several levels of sub options for controlling the position and style if the map type controls that can be defined here.
overviewMapControl Boolean. A collapsible overview map in the corner of the screen
6 - 10 © 2013 Intel Corporation.
Adding GEO Features
Walkthrough 6-1: Getting Started with Maps In this walkthrough you will manually geocode an address and center a map on that location using the JQM Plug-in and Google Maps Javascript API V3.
Steps Open the Project
1. Open Intel XDK New 2. Click on the word PROJECTS in the topleft corner of the GUI. 3. Click the Open a Project button. 4. Select the following file: /ftIntelXdkNew/walk/walk6_1/walk6_1.xdk
Manually Geocode a Location
5. Open a web browser to http://geocoder.us 6. Enter your address and click search. 7. Note the latitude and longitude of your address. Load Google Maps and the Google JQM Maps Plugin
8. Open index.html in code view. 9. Where indicated by the comment, insert the script declarations to initialize the Google Maps Javacript API V3 library. Your code should resemble the following:
View more...
Comments