The book provides an introduction and detailed tutorial on PhoneGap .. In the past, we have seen similar OS fragmentations, beginning with the cross-desktop. In this chapter, you'll learn the essentials of PhoneGap. Beginning App Development with Parse and Phonegap pp | Cite as Download chapter PDF. “Beginner” in this context not only encompasses those who might be beginning PhoneGap developers, but also those who may be extremely experienced and.

    Language:English, Spanish, German
    Genre:Academic & Education
    Published (Last):29.01.2016
    Distribution:Free* [*Register to download]
    Uploaded by: ELIDA

    53957 downloads 108731 Views 26.65MB PDF Size Report

    Beginning Phonegap Pdf

    In this video course, Chris Griffith introduces the PhoneGap ecosystem and the basics of Starting from the beginning, this book will cover how to set up your. Adobe Systems Incorporated. All Rights Reserved. Introduction to Mobile Development with PhoneGap. Yeah it's prey awesome. Build cross-platform mobile applications with the PhoneGap . Did you know that Packt offers eBook versions of every book published, with PDF and ePub .. This verifies that your setup is ready to begin writing PhoneGap applications for iOS.

    Open your terminal or command-line, and navigate to a directory where you would like to create your first Cordova project. To bootstrap an application, type in the following command: cordova create toptal toptal. The subcommand is invoked with three additional parameters: The folder where the application will be placed, the namespace of the application, and its display name. This is where you will place your application code which is common for all platforms. While Cordova allows you to easily develop an app for different platforms, sometimes you need to add customizations. At this point you can also open up the config. Add your first platform using: cordova platform add android If you change your mind later on, you can remove a platform from the build process easily: cordova platform rm android Upon inspecting the platforms directory, you will notice the android folder within it.

    Or, you could just enhance device-only applications with richer data — for example, for the previously mentioned note-taking application that lets users take pictures and record audio, you could use SQLite to store any notes and metadata for each of the pictures taken.

    So, here are the API components in alphabetical order: Furthermore, if you will be using other frameworks such as jQuery, which is very popular , you must have a solid understanding of how those work as well.

    It does you no good to just dump a bunch of scrolling text and gigantic design elements such as background images into a pixel by pixel screen on the iPhone, for example. A better approach is to re-chunk any content, or provide a more cut-down version of user interface UI elements particularly navigation. This is not a book about the mobile device user experience, nor will this book provide any advice on layout or usability on a small screen. A good approach is to use HTML elements that bring semantic structure to your content — specifically, headers, lists, and buttons, for starters — and that you can easily style using CSS.

    Another thing to consider is that mobile devices have different latency and initialization characteristics than your average web browser running on a desktop or laptop machine. In other words, when a user loads your PhoneGap application, that app must go through a series of initialization procedures to be ready for use.

    Having large, crufty, or extremely convoluted layouts will just make for slower going and slower parsing. The jQTouch framework www.

    The jQuery Mobile framework Different devices respond differently to the different frameworks for example, the animations on jQTouch seem to make certain Android devices extremely unhappy, and xuijs seems to be the only framework that works on the older Blackberry devices. Using a framework to create a usable UI will always be faster than putting something together yourself, and then testing on the different devices. Last, but not least, on some phones, linking from one page to another might cause memory problems or slower interaction.

    One of the best practices is to try to keep as much functionality as you can on one page, and then use JavaScript functions to load information dynamically onto the page. You can do this with document. You also learned about various frameworks and approaches that might help you in your future development of PhoneGap applications.

    Note that this chapter also covers the brand-new PhoneGap Build feature, which enables you to submit code to a service and get app-store—ready apps in return.

    Current version of PhoneGap shown in upper-right corner Downloading PhoneGap for iOS Before you can get started, ensure that you meet the following requirements: To install PhoneGap, follow these steps: Open your web browser and point it at www. It should be on the far-right margin. A ZIP fi le should download to your Downloads folder. Double-click the ZIP fi le to uncompress it. You should see a folder that contains various fi les and directories, as shown in Figure You can confi rm that everything is installed correctly by opening Xcode and starting a new project.

    As shown in Figure , you should see a PhoneGap-based project as one of your options. PhoneGap Installer screen www. You should see a folder that contains various fi les and directories. Open the Android folder. You should see a Sample folder, a pair of JavaScript fi les, and a. In the root directory of the project, create two new directories: Copy phonegap. Right-click the AndroidManifest. Paste the following permissions under versionName: You are now also required to have a plugins.

    This fi le is included in the latest 1. Ensure that you add it to your PATH variable. Copy the contents of the ZIP fi le to C: NOTE You can download cygwin at www. Copy the contents of this folder to a more permanent location. This service is designed specifically for coders who want to create their web projects, submit this code, and receive back app-store—ready apps for iOS, Android, webOS, Symbian, BlackBerry, Windows Phone 7, and other devices.

    To use PhoneGap Build, you must register for a beta invite, as shown in Figure Within the hour, you will receive an e-mail from PhoneGap with instructions on signing up for the service, as shown in Figure This e-mail should contain a link and a signup code. Registering for a beta invite at build. E-mail acknowledgment www.

    As simply as that, you are signed up! For now, the service is free, and will remain free for public open source projects. BBEdit shown in Figure is a popular choice. Other good choices include TextMate, Dreamweaver, and vi. Still others of you may choose to use a standard text editor like Notepad on Windows. You can create your web projects in any environment you like.

    Just understand that your process will likely involve having a set of web project fi les that you then port from one environment to another, especially if you are supporting multiple devices. Clicking it will load a project with the PhoneGap tools made available to you.

    Installing PhoneGap for On Android devices, you must install a series of tools and Android devices extensions for Eclipse, but you can also use the droidgap wizard discussed in more detail in Chapter 3. Using Build Use Build. Com different options when supporting multiple platforms.

    In Figure , you can see that Xcode is divided into five major sections: Figure shows what you should see in the simulator usually a blank page. What appears in the Simulator www. How do you know if something actually happened? This function runs when the deviceready PhoneGap event returns true. You learn more about events in Chapter 4.

    Instead of having an empty function, change it so that it fi res an alert, as shown here: Alert box www. This is a fairly compelling reason to develop your code outside of Xcode in other words, in your favorite editor and then copy your code to where Xcode can see it. This displays a path to your target folder. In terms of importance, the plist which stands for property list fi le for your project is fairly high on the list. Other important items in the Resources folder are two images: Both of these.

    You can overwrite the existing fi les. Last, but not least, are the Objective-C classes that exist in the Classes, Plugins, and Frameworks folders.

    Subscribe to RSS

    In Appendix D, you will fi nd a whole bunch of PhoneGap plug-ins that you can add to your projects, and these consist of both Objective-C fi les that go in the Plugins folder and JavaScript fi les that go in your www folder. A target is a version of Android. To fi nd out which targets are available, you can run the following command from a Terminal window if you are using Mac OS X or a similar shell: Available Android targets: Android 1.

    Platform API level: Android 2. A complete command might be as follows: Just press Enter when asked about the custom hardware profi le.

    The fi rst time you run this command, it will take several minutes to cycle through. Essentially, you run the following command from the command line: Here is a sample run: Making output directory Building phonegap. The result is a mytestapp folder copied to the desktop.

    This folder contains a whole bunch of files and folders that constitute the Android project, as shown in Figure Ensure that the emulator is running. See the previous instructions for how to get an emulator to run. Enter ant debug on the command line and press Enter. This creates a debug. In the case of the previous example, the fi le will be called mytestapp-debug. You can now run the following command to make your project show up in the emulator for further testing: To open the app in the emulator, simply click its icon, and then test your app to make sure everything works.

    On the command line, enter the following: On the command line, change directories to that project directory, and then open the project.

    Display Files with PhoneGap Document Handler Plugin

    Edit the following line: After that, you can run ant load-simulator to run your app in the Simulator. In both cases, you want to open a Terminal or shell window and navigate to the folder into which you placed the PhoneGap code, then navigate to either the webOS or Symbian folder as appropriate.

    Next, open the prescribed emulator for your device that you installed along with PhoneGap in Chapter 2, and type make in the Terminal window. This deploys your code to the Simulator and lets you test your code. SUMMARY This chapter has walked you through the process of working with the various simulators, virtual devices, and other tools needed to actually test your code.

    Working with the The Android emulator lets you quickly test your code without a device. Android emulator Working with On BlackBerry, you build and run code via the command line, and then can Blackberry view it on an emulator. In this chapter, you learn how PhoneGap handles events.

    An event in PhoneGap is similar to other JavaScript events. By using the DOM, you can easily manipulate a document — adding, removing, and editing nodes as needed.

    For example, if you want to display status messages to the application user, create an HTML div with an id of statusmessages, then use JavaScript to populate that div with HTML messages.

    In traditional JavaScript programming, any element on a web page can have certain events that can trigger a bit of JavaScript. For example, an onrollover event on a link might cause a pop-up window to appear, or an onclick event might cause a preview pane to open. But other events are specific to PhoneGap, including the following: Once it has fi red, you can safely call any PhoneGap function, which, in turn, can safely access the native API.

    To put it even more strongly, the first thing you should do on any PhoneGap project is to listen for the deviceready event. Once it fires, you know two things: At that point, you can try to detect other events, or do anything else with your application. All the other event listeners would be registered inside the onDeviceReady function.

    So, if you wanted to detect a pause or resume event, your code would look like this: It only works within a PhoneGap context. If you tried to run this event in a normal web browser, it would never fi re. In terms of primacy, you must detect it fi rst, before you do anything else, because, once it fi res, you are cleared to call the PhoneGap API.

    To detect this event, register an event listener as shown here: An application is considered paused when it leaves the foreground, not when it is shut down.

    Any calls of this nature, as well as any calls made by plug-ins, will occur when your application resumes. This is a new event added with Version 0. How It Works The fi rst event listener is the key. It detects when the deviceready event fi res. When it does fi re, the deviceready event runs the onDeviceReady function, which, in turn, registers two new listeners: SUMMARY In this chapter, you learned how to detect the different PhoneGap events, specifically deviceready, online, offline, pause, resume, menubutton, searchbutton, and backbutton.

    Open the Google homepage as soon as you detect that the PhoneGap application is online. Display the current time when the device is ready. In this chapter, you take the next logical step and learn more about the device itself, network connectivity, and custom notifications. Following are the elements of device: Version — The version of the OS that is running www. In other words, both of the following variables reference the same device: For example, here is a quick list of return values for various phones: The device.

    On iPhone, this returns whatever name has been set for the device in iTunes. Also, some BlackBerry devices might return the platform version instead of the platform name. For example, it might return 1. The UUID can be different lengths; depending on the device, it should always be specific to a model and platform.

    For example, Android uses a random bit integer; BlackBerry uses a nine-digit personal identification number PIN ; and iPhone uses a string of hash values. For example, on Android, Froyo OS returns 2. An iPhone running iOS 3. Enter the following code: Next, you wrote an onLoad function that registers an event handler using addEventListener. Specifically, you want to listen for the deviceready event, and when that fires, run the onDeviceReady function.

    If you were using jQuery, you could simplify the process like this: For example, the body tag uses the onload parameter to initiate the onLoad function, which registers the event handler that detects for deviceready. The signal may be nonexistent, or it may be very weak, or the user might switch from cellular to WiFi, or back again. In this section, you learn how to determine the connection type.

    Following is an example: For example: First, you load the phonegap library, and then register the event handler for deviceready events. Once the device is ready, you run navigator.

    In other words, you might not want to test a server that might be down when you do the test. The most important bit about this attempt to connect is the callback function imaginatively named myCallback , which will contain the reachability code returned by the network. Once again, note that some devices will store the reachability code in different formats, so check for both reachability.

    Next, you set up a simple object that contains the network status constants from PhoneGap as keys, with your own custom messages as values — that way, you avoid any cryptic-looking messages being delivered to the person using the device.

    Next, you run a JavaScript alert that contains the connectivity message. This will pop open a window on the device that the user can then close. Finally, be sure to run the onLoad function from the body tag, because this will set the entire process in motion.

    Although you can use this kind of alert system on a device, PhoneGap comes with four different types of notifications you can use. In this section, you learn how to use the following: The notification.

    Be sure you replace all tabs in your code with five spaces. Selecting one or the other results in different outcomes. To create a confirmation dialog, use the notification.

    To create a beep, use the notification. The iPhone will also ignore the beep count argument. For these kinds of situations, PhoneGap provides a vibrate function available as notification.

    For example, by clicking the fi rst link, the showAlert function is triggered, which displays a custom alert box. The second link triggers the showConfirm function, which displays a custom confi rmation box. The third link triggers playBeep , and the fourth, vibrate.

    SUMMARY In this chapter, you learned how to get information from the device, detect the presence of the network, and send notifications to the user using a variety of options. In Chapter 6, you will learn how to use the accelerometer. Create a simple HTML form that allows a user to enter a web address and then press a button to test the network connectivity. Have the default site be google.

    Create an informational footer that contains information about the device the person is using. Checking for network connectivity Use connection. Creating custom alerts Create custom alerts with notification.

    Creating beeps Create beeps with confirmation. Creating vibrations Create vibrations with confirmation. What Is the Accelerometer? The accelerometer is a device that captures motion in the X, Y, and Z directions. To help visualize the X, Y, and Z directions, place your device face-up on a flat surface, like a desk. Ideally, this surface would offer very little friction so that, for example, you can push the device left and right without having to lift it.

    Any which way you move the device will result in a change of coordinates, either into the positive or negative quadrants. Moving it to the left gives you a negative result; moving it to the right gives you a positive result.

    Moving it away would result in a positive result along the axis; and moving it toward you would result in a negative result. So far, so good. The Z direction represents up and down, adding a third dimension. If you were to drop the device under the surface or somehow push it through the surface! The accelerometer inside the device would detect all kinds of movement along the X, Y, and Z directions. Here are just three: All that person would have to do is turn on your application and put the device in a pocket.

    The idea behind this game is to guide a cute little monkey through a variety of obstacles by tilting and turning your iPhone. The game was featured on the SyFy channel in the U. This object is created and populated by PhoneGap, and returned by an accelerometer method. Instead of giving you the current acceleration, it will report the last value reported from a PhoneGap accelerometer call. If you set a variable to contain the method call, and pass in a frequency parameter as one of the options, you will get acceleration data on a periodic basis.

    A more useful function might be something like the following, in which certain document object model DOM elements are refreshed in the HTML, thus giving you a more functional readout, as shown here: PhoneGap will restrict the interval to a minimum of every 40 milliseconds ms and a maximum of every 1, ms. So, if you request an update every 3, ms 3 seconds , PhoneGap will request an interval of 1, ms from the device, but invoke the success callback at your requested interval of 3, ms.

    As soon as the application loads, move your device around to get updates on its X, Y, and Z acceleration. How It Works As soon as the application loads, the startWatch function is fi red. This function uses the watchAcceleration method to start watching the accelerometer and reporting X, Y, Z, and timestamp information back to the HTML display. You now know how to detect movement on the device in X, Y, and Z directions.

    In Chapter 7, you learn how to use the compass. Write an application that beeps if the device is held at a certain angle. Feel free to establish what those X, Y, and Z parameters should be.

    Acceleration object To capture read-only data about the current state of acceleration, use the data returned in the Acceleration object. What Is the Compass? Simply put, the compass built into your device obtains the direction in which the device is pointing. Specifically, your device has a solid-state or digital compass. It uses two or three depending on the model of your device magnetic field sensors to supply data back to your device. The device uses this data to provide a correct heading with some rapid trigonometric calculations.

    If your device is any of the following, it also contains a magnetometer: This chapter does not go into detail about magnetometers. Differences Among the Different Devices Just about all modern smartphones come with a built-in compass. All of them can provide you with a heading. While the application is running, simply turn in different directions to display a heading.

    From a look-and-feel perspective, the various native compasses look slightly different, but they all provide pretty much the same amount of information. For example, the compass in the iPhone 3GS shown in Figure offers a visual compass that tells you where north is, plus a readout in degrees and cardinal points for example, NW of your heading.

    At the bottom, it provides a GPS readout of your latitude and longitude. The compass in an Android device shown in Figure also offers a compass display with a heading, and lets you bookmark your current location. The compass in the iPhone 3GS in an Android device The compass in the BlackBerry Torch shown in Figure offers the same visual compass as the iPhone and Android, but includes a direction of travel, presumably an alternative to providing a degree heading.

    Finally, the compass in a webOS phone shown in Figure offers just a compass display with a heading, and a button that links back to a map display.

    Using the Compass Why use the compass at all? Why would you want to create an application that contains a compass, if your device already includes a native compass application? Well, for one thing, if you create an application that uses the Compass API, you can create more specific results than just a general heading. Here are just three creative ways to add a compass to any application: For example, if you were Muslim, knowing the current direction for Mecca would be very important for prayers.

    This application is only for the iPhone 3G. Figure shows how this application also enables you to write notes about locations. Notes for To get the current heading, use compass. This is an entirely optional item. If you set a variable to contain the method call, and pass in a frequency parameter as one of the options, you will get heading data on a periodic basis. Following is an example of how to use this method: A more useful function might be something like the following, in which certain document object model DOM elements are refreshed in the HTML, thus giving you a more functional readout: Enter the following code.

    As soon as the application loads, tap the Start Watching button, and move your device to get heading updates. This function uses the watchHeading method to start watching the compass, and reports heading information back to the HTML display.

    Copy the jqtouch and themes folders into your Xcode project. The easiest way to do that is to right-click the www folder in Xcode and select Open With Finder, as shown in Figure Contents of the new www folder www. Stick the following code above the fi rst call to load phonegap. Inside that DOM element is a second div with a class of toolbar.

    The DOM element with an id of heading comes after that. This is where the heading information will be placed. After that comes an unordered list with two elements. This code uses the individual class to simulate having two buttons side by side.

    Display a special message if the device is oriented north. What Is Geolocation? Simply put, geolocation involves the identification of a real-world geographic location of a device — in this case, the smartphone you have with you. Because of the wide divergence of methods used www.

    Using Geolocation The most obvious reason to use geolocation is the recent trend to indicate where something happened. Some existing applications also combine geolocation data particularly readings of latitude and longitude to pinpoint your location on a map, or add important information to a compass display. From your point of view as a developer, the biggest consideration you will have is how accurate geolocation data will be on any given device.

    Depending on the type of smartphone being used, the resolution in other words, accuracy will vary. Bad weather might cause interference with the GPS satellite, or the user might be indoors or underground and not getting good reception.

    If the user is in a place where many stores, restaurants, and other landmarks are in close proximity to one another, the user might not get very accurate readings of where he or she is. Anyone who has used a social location service to check in to a bar has experienced this problem. Following are three creative ways you might add geolocation data to any application: Many Twitter users post geolocation data with their tweets, and you could use the Twitter search API to pull down tweets that are within a few miles of a smartphone user.

    Both apps are free and available on lots of different device platforms. You can sign up and start using them right away.

    On Gowalla, you can take trips and pick up items that other players have left for you. You can then select a location from the list of nearby venues, add a note and a photograph, and post it to your stream. Following are the two properties for this object: For example, calling geolocation. This function returns both an error code and an error message in case of a problem, encapsulated as a read-only PositionError object.

    Coordinates Object The Coordinates object contains a set of read-only properties. In fact, the Coordinates data is attached to the Position object, which is then returned to the user via the onSuccess callback function. Following are the properties of the Coordinates object: The optional callback that is called in case of an error is geolocationError. The getCurrentPosition method is an asynchronous function that returns current position data.

    As mentioned earlier in this chapter, you use the onSuccess callback function to actually retrieve the position data, as shown here: If you set a variable to contain the method call, and pass in a frequency parameter as one of the options, you will get data on a periodic basis. So, for example, the following options would set a maximum age of 5 seconds, a timeout of 5 seconds, and enable high accuracy: How It Works As soon as the application loads, the watchPosition method is fi red.

    Every 3 seconds the device will get a new update on longitude and latitude. In fact, all it does is keep adding geolocation information to the screen until you turn it off. Rather bland geolocation UI www. Improved Figure shows the result. How can you improve it? Well, for one thing, you can simplify the return data from the onSuccess function.

    Instead of spewing out all that information, perhaps this would do: The information is more compact, certainly, and you could improve it even more with bolding and other tricks. You now know how to retrieve latitude, longitude, maybe some altitude , and other data points of your current position.

    Write an application that displays a special message if the speed drops below a certain threshold. Feel free to set any threshold you like. What Are Media Files? The Media API lets you record and play back audio on a device. You can typically play audio fi les loaded locally on the device, or play audio files retrieved from the Internet. Furthermore, the capability to record audio has been pretty convenient, too. The audio quality was just fi ne, and it was easy to incorporate the resulting MP3 fi le into audio-editing tools.

    Showcase of Media Applications An abundance of voice recorders and music-playing applications exist for both iOS and Android devices — almost too many to mention here.

    Figure shows just a partial list of voice recorders available on the App Store. All of these provide the same basic functions — record, pause, play, and stop recording. Some offer the capability to share your recordings with others via e-mail, fi le sharing, or social media services.

    You can create all kinds of voice recordings, give them custom names, and even set an automatic start and stop time for recordings. The best way to learn about the Media API is to start learning about its methods. The methods allow you to play, record, and pause, among other things. The getCurrentPosition method is an asynchronous function that returns the current position of the underlying audio file of a Media object, and is supported only on Android.

    To convert to seconds, you will need to divide by 1, If the duration is unknown, a value of -1 is returned.

    Following is an example of an audio fi le being paused after 15 seconds a great way to offer up an audio sample, by the way: This is particularly important because there is a fi nite number of OpenCore instances for media playback. The OpenCore libraries support media playback for audio, video, and image formats. You should always call this release function when you no longer need a media resource.

    It contains two parts: The predefi ned error codes are constants: That way, you could display the friendlier message to the user. The user can also play the same fi le by pressing the Play Audio button.

    How It Works As soon as the application loads, the user can start recording and stop recording using two links at the bottom of the HTML window. It is also difficult to use because it uses links. Current media player application look and feel www.

    Place the following code above the fi rst call to load phonegap. The Play button has a class of whitebutton, and the other two buttons get a class of graybutton. The result is similar to what is shown in Figure Create an application that will start recording after a 5-second delay. What Is the Camera?

    Just about every smartphone these days comes with a camera. There are absolutely no standards that govern megapixels, optical zoom, the existence of a flash, shutter speed, and ISO. For the non-photographers, ISO is used to defi ne sensitivity to light — the higher the number, the more light is gathered. Therefore, it reduces the amount of flash, for example, that you might use in a low-light situation.

    Those that do offer different support for HD capture. Still others support removable memory cards. What Is the Photo Gallery? If your smartphone has a camera, it also has a photo gallery. On most phones, the photo gallery usually displays a grid of thumbnail images, any of which you can tap to view a larger version of the image. Android photo gallery photo gallery www.

    Figure shows what happens when you tap the share icon on an iOS device. Also, most devices have the capability to organize photos into photo albums. It is important to mention the photo gallery and photo albums because when you work with the Camera API, you have the option of taking a picture with the camera, or selecting an image from the gallery or photo albums.

    Even those who would never consider themselves good photographers or who are intimidated by the options on a digital camera, or even a point-and-shoot camera can use their smartphones to capture memories. Here are just three creative ways to use the camera as part of any application: Flickr, which was one of the fi rst social photography services now part of Yahoo!

    You can easily view photos of your own and from your photo galleries of your friends with the app, as shown in Figure It contains a dozen modern and vintage photo effects that you can apply to your pictures. You can even save multiple effects onto your images.

    Flickr photo subjects. The by-product of tilt-shifting is that the subjects appear to be little toys, as you can see in Figure Of course, if used selectively, it can also simulate depth-of-field to a certain degree. This object has one method, getPicture , which you learn more about shortly. Following are the options for the Camera object: You use the camera. It then closes the camera application and returns the user to your application. The cameraSuccess callback function contains the image data from the camera operation.

    For example, the following code snippet shows how you would take an image with the camera at 35 percent quality and return the data as a Baseencoded image: The higher the number, the better the quality. For example, the following options set quality to 70 percent, return a Baseencoded image, and allow editing the CAMERA is set by default: Table highlights some idiosyncrasies for various devices.

    How to Display .pdf, .xlsx, .docx Files in a PhoneGap App

    BlackBerry Ignores the quality, sourceType, and allowEdit parameters. Application must have key injection permissions to close the native Camera application after a photo is taken. Taking a very large image may result in the inability to encode the image for later- model devices with higher-resolution cameras.

    Palm Ignores the quality, sourceType, and allowEdit parameters. Enter the following: How It Works As soon as the application loads, the user can take a picture by clicking the Capture Photo button.

    This button triggers the capturePhoto function, which takes a picture with the default camera with a quality of 50 percent , and then stuffs the Baseencoded image into the myImage document object model DOM element in the HTML.

    How It Works Instead of taking a picture with the default camera application, this example allows the user to select an image from the photo gallery or a photo album. Figure shows how the fi rst camera application looks on the device. Ensure that your project has the necessary jQTouch folders in it, as described in Chapter 7. You get the idea.

    Using the button stand out blueButton class www. Create a 3-second delay before taking a photo. Add an option that allows the user to choose the quality of a photo taken with a camera. In this chapter, you learn how to use HTML5 storage options directly in your code.

    You learn how to use each of them here. For the fi rst time, PhoneGap developers are able to create client-side applications that use a somewhat reliable database back end.

    For example, if you use Chrome or Safari to visit html5demos. Now, at fi rst glance, this page appears to be powered by a traditional database like mySQL. Result of clicking Inspect Element If you click the Resources tab and then scroll down to the databases portion, you will see that that an html5demos database exists, and inside that is a table called tweets. If this is more your speed, then the local and session storage methods are what you want.

    Figure shows the result of entering a value of hello for the sessionStorage variable, and a value of goodbye for the localStorage variable. Entering values for sessionStorage and localStorage If you still have the Resources tab open, scroll down to Session Storage to see the value of hello stored there, as shown in Figure In Figure you can see the value of goodbye stored in Local Storage.

    Value of goodbye stored in Local Storage www. Well, the Session Storage objects are deleted when you close the browser window, but the Local Storage ones persist. Another thing to remember is that Storage objects are usually good for 5 MB to 10 MB of data, depending on the browser used. Well, some devices will already support these features, and, in that case, the PhoneGap API will defer to the device implementation.

    Specifically, you learn how to do the following: To open a database, use the window. For example, you can run the following command: This object contains methods that let you execute SQL statements against a previously opened database. Also note that you can use whatever legal SQL statement you want. The example shows a select statement, but you could run others. Following is an example of a drop statement: If you need to run a whole bunch of queries at once, you can create a transaction, which then calls your queries, as shown here: You learn more about result sets next.

    The transaction method provides you with a success callback. The executeSql method also provides you with success and error callbacks. What you get back from the success callback function is the SQLResultSet object, which contains the following three properties: This applies only if you ran an insert statement. This returns 0 if none were affected, as with a select statement.

    Each time you use it, you get back a row of data specified by the index you pass it. You end up with a JavaScript object with properties that match the database column names from your select statement. So, to rewrite the querySuccess function from the previous example, you would use the following: In order to loop through a record set, you must know the length of that record set hence the use of results.

    But once you have that, you can start at the fi rst record retrieved, and process each row using results. The error codes themselves are constants, as shown here: Enter the following code to create a database app: How It Works As soon as the application loads and the device is ready, the code runs openDatabase to create a test database. Following that, the code then runs a series of transactions that create a test1 database table, and inserts three records into that database.

    Once that particular transaction runs, the success callback runs, which calls a second transaction that queries the database. The result of that function is to loop through the record set and display the names in the document object model DOM element with an ID of status. Figure shows what this might look like. That error will look something like Figure The localStorage object does exactly that, giving you access to the local storage interface. To use it, invoke window.

    How It Works As soon as the app loads, the user can enter his or her fi rst name into the field. As he or she enters each key, the storeName function is triggered, which takes the value from the input field and stores it in the local storage variable called name.

    Finally, it displays this value in the result DOM element, as shown in Figure As soon as the user taps Done on the keyboard, or, for example, moves to another field, the storeName function will trigger.

    So, the new code would look like this: Result of download on Wrox. You learned how to open a database; create transactions; execute SQL statements; and get, set, and remove local storage data. In Chapter 12, you learn about the fi lesystem. Apply the jQTouch look and feel to the database example.

    In this chapter, you learn how to work with fi lesystems, directories, and fi les. At the end of the day, that access is usually fairly limited. What this chapter focuses on is what probably matters most to you: It has the following two properties: Directories are represented by DirectoryEntry objects, and fi les are represented by FileEntry objects.

    In this section, you learn about the following: It has the following properties: Furthermore, DirectoryEntry has the following methods: It features two callback functions as parameters: Any of the following conditions will create an error: Apache Cordova in Action by Raymond K.

    Camden Apache Cordova in Action teaches you to create and launch hybrid mobile apps using Cordova or Phonegap. For readers just learning to design mobile apps, the book will discuss ways to build mobile friendly, professional-quality UI and UX. Apache Cordova in Action simplifies the entire process of app development and makes it accessible to web developers. Using Apache Cordova, mobile developers can write cross-platform mobile apps using standard HTML 5, JavaScript, and CSS, and then deploy those apps to every leading mobile platform with little or no re-coding.

    Instead of just showing short snippets of code to explain a particular API, the book is chock full of complete, contextual examples. The sample applications provide developers with applications they can run on every Cordova supported mobile device platform to see exactly what the API does, how it works and what the limitations are on each platform. PhoneGap 3.

    To explore these topics, the book guides you through the development of several apps, including a productivity app, a path-recording app, and a game. Approach: A practical guide written in a tutorial-style, this book walks you step-by-step through 12 individual projects to create real world apps.

    Each project moves through design and implementation of the app, and also provides suggestions to enhance it. Who this book is for: If you are a mobile developer who is familiar with Phonegap basics and wants to quickly create some cool mobile applications with PhoneGap, this book is for you. No experience with Java, or ObjC is required. This book cover easy step by step guide to build mobile application as well as PhoneGap Build advance features.

    Users will learn the basics of PhoneGap, get started with building their first app, and gradually work on complex tasks like building and improving the CSS defining the app style, font, colors, and views using jQuery themes.

    Similar articles

    Copyright © 2019