Phonegap Application Development

Listing 2 shows the JavaScript code that makes it all work.

Line 1 is a simple boolean flag that determines whether the script is running on a mobile device or a Web browser. Setting this variable to 0 allows me to run and debug the program in Firefox where I have all of the HTML, DOM and JavaScript development tools that I'm accustomed to using. Setting this variable to 1 targets the program for a mobile device where I can debug the Cordova-specific aspects of my program, knowing that my JavaScript is probably correct.

Lines 91–95 arrange to have the JavaScript init() function called when the DOM is loaded and after the Cordova initialization routines have run. These lines also point out a couple oddities about Cordova development. First, there is no way to detect automatically whether the program is running in a browser or on a smartphone. That's why I set that variable, as discussed earlier. Also, Cordova creates its own event that gets triggered when it's ready to begin JavaScript execution; you can't use window.onload as you normally would, because this event might trigger before Cordova is ready. Either way, the init() function will be called at the appropriate time.

The init() function is on lines 5–13. On line 8, you make a call to the contacts.find method to get an array of contact objects from the device's contact directory. This array is then passed, asynchronously, to store_contacts(), lines 39–44, which simply stores the array in a global variable. Then, init() makes a call to update() to initialize the data display and arranges for update() to be called every second from then on.

The update() function, lines 15–37, is where the fun begins. If the program is running in a browser, you simply populate the Longitude and Latitude fields with random numbers. Having the numbers change like that allowed me to verify that the program was still running. However, if the program is running on a physical device, you use the geolocation.getCurrentPosition method to fetch the real GPS coordinates. If this operation is successful, set_location() is called. Otherwise, location_error() gets called, and you can display an error message (lines 73–83). The only error I've encountered with the getCurrentPosition call was when I actually had the GPS disabled.

Lines 25–36 form an almost embarrassing Ajax call. I've stripped this code down to the least amount of code that would run under Firefox and Cordova. It won't run on IE, and it doesn't do much, if any, error checking. I'm not trying to demonstrate how to do an Ajax call in Cordova. I'm only trying to demonstrate that you can. In this case, you're loading some content from a remote server and putting it inside the quote <div> discussed earlier. During development, I'd simply change the content of that file on the server to verify that it changed inside the app.

Lines 44–58 are onclick handlers for the two buttons in the application. All these routines do is adjust an array index plus or minus one, as appropriate, and do some bounds checking. Finally, they call display_contact() to display the current contact.

The display_contact() function (lines 59–72) is the last of the Cordova-specific functions in the program. In lines 60–64, you blank out all of the contact fields in preparation for setting them with new values. I found that if I didn't blank them out first, they would persist into the next record if the next record didn't happen to have a value for a given field. In lines 65–69, you populate the fields with data from the current contact record. Note that both phoneNumbers and e-mails are arrays of objects, and that for this purpose, you are interested only in the first element.

And there you have it. There's nothing here that would be unfamiliar to the average Web developer, except a really powerful API. But, I've only touched on what this API can do. Figure 2 shows the application running on my Droid Bionic.

Figure 2. Sample Application Running on Android

I did some hand waving over a subtle problem with this application that many JavaScript, particularly Ajax, developers have encountered. On most browsers, your program can't load from one domain, and then load content or code from another domain. However, this program is standalone and needed to load content from a potentially arbitrary Web site. Cordova handles this problem by "whitelisting" the domains from which an application is allowed to fetch content. By default, all domains are blacklisted, and, thus, all network access is disabled. A developer can whitelist a domain by editing /res/xml/cordova.xml and following the examples given for the <access> tag. This is a safe but elegant solution to a potentially nasty problem.

Another interesting possibility is to have your application load all of its HTML and JavaScript from a remote Web server. This easily can be done by making a simple change to ./src/{projectname}/{projectname}.java. This file has only 20 lines of real code, and the necessary change is pretty intuitive.

Being able to load content from a remote server actually makes development easier. I found it easier to do my development on a remote, publicly accessible server, than to develop on my workstation. This way, I could point my Web browser at the application and get all my HTML, CSS and JavaScript working the way I wanted. Then I got the application fully functional on my Android. Once it was fully functional, I copied the project to my workstation for the final build. Doing it this way is the only way you'll be able to test an application that makes any Ajax calls without violating your browser's cross-site scripting security policy.

As neat as Cordova is, there are a few things I didn't like. As I mentioned earlier, there is no way to detect automatically whether a program is running in a browser or on a device. Also, I found the whitelisting functionality to be a bit buggy, but not in any way that broke my application. But, the most disheartening thing I found was when I tried to use the camera API. Instead of simply snapping a picture and either returning the data or storing it, the API actually brought up the device's native camera device as a pop-up. This was extremely intrusive and actually broke my first demonstration app.

I've had a lot of fun playing with Cordova, and I've barely scratched the surface of what it can do or be extended to do. This has to be the easiest way to get into smartphone application development.

______________________

Mike Diehl is a freelance Computer Nerd specializing in Linux administration, programing, and VoIP. Mike lives in Albuquerque, NM. with his wife and 3 sons. He can be reached at mdiehl@diehlnet.com

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

website development in indore

website development in indore's picture

Aking Web Tech a leading IT company & Provides web services :- website Development in just 1,999 Rs/-, software development like {Billing software, School Management Software, Inventory Software, ERP, CRM}, Domain & Hosting , SEO
website development in indore

software companies indore

software companies indore's picture

It is really a nice and helpful piece of info. I’m glad that you simply shared this helpful info with us. Please keep us informed like this. Thank you for sharing.
software companies indore

I found your site very much I

sandra9's picture

I found your site very much I often wonder why I do not do what you did because it is really great congratulations

une voyance gratuite

developing mobile apps using Phonegap

MatthewS's picture

We are soon to begin developing mobile apps using Phonegap, but are deciding on what actual physical devices we need to buy for testing. What do you currently use? You mention above that performance can vary, and can be especially a problem on older devices, so from that point of view would you suggest applying for a pay day loan UK and buying an iphone 4 and 5 to test on? Do you test separately on ipod touches, or I guess that maybe you can use this instead of an iphone 4 to keep costs down? For android I assume you would have a device for 2.3 and 4, and perhaps different screen sizes? And then there are the tablets!

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState