Phonegap Application Development
Listing 2 shows the JavaScript code that makes it all work.
Listing 2. JavaScript Code for the Sample Application
1 var mobile = 1;
2 var contacts;
3 var current_contact = 0;
4
5 function init () {
6
7 if (mobile == 1) {
8 navigator.contacts.find(["*"], store_contacts);
9 }
10
11 update();
12 window.setInterval(update, 1000);
13 }
14
15 function update () {
16 var req;
17
18 if (mobile == 1) {
19 navigator.geolocation.getCurrentPosition
↪(set_location,location_error);
20 } else {
21 document.getElementById("lat").value =
↪Math.floor(Math.random()*46)
22 document.getElementById("lon").value =
↪Math.floor(Math.random()*46)
23 }
24
25 req = new XMLHttpRequest();
26
27 if (!req) {
28 alert("Ajax failed!");
29 return false;
30 }
31
32 req.open("GET", "http://example.com/test.html", true);
33 req.onreadystatechange = set_quote;
34 req.send(null);
35
36 return true;
37 }
38
39 function store_contacts (c) {
40 contacts = c;
41 display_contact();
42 return true;
43 }
44
45 function previous_contact () {
46 current_contact = current_contact - 1;
47 if (current_contact < 0) { current_contact = 0; }
48 display_contact();
49 return true;
50 }
51
52 function next_contact () {
53 current_contact = current_contact + 1;
54 if (current_contact > (contacts.length-1)) { current_contact =
↪contacts.length-1; }
55 display_contact();
56 return true;
57 }
58
59 function display_contact () {
60 document.getElementById("id").value = " ";
61 document.getElementById("name").value = " ";
62 document.getElementById("phone").value = " ";
63 document.getElementById("email").value = " ";
64
65 document.getElementById("id").value =
↪contacts[current_contact].id;
66 document.getElementById("name").value =
↪contacts[current_contact].displayName;
67 document.getElementById("phone").value =
↪contacts[current_contact].phoneNumbers[0].value;
68 document.getElementById("email").value =
↪contacts[current_contact].emails[0].value;
69
70 return true;
71 }
72
73 function set_location (p) {
74 document.getElementById("lat").value = p.coords.latitude;
75 document.getElementById("lon").value = p.coords.longitude;
76 return true;
77 }
78
79 function location_error (e) {
80 document.getElementById("error").innerHTML = e.message;
81 return true;
82 }
83
84 function set_quote (p) {
85 if (!p) { return 1; }
86 if ((p.status) && (p.status > 299)) { return 1; }
87 document.getElementById("quote").innerHTML = this.responseText;
88 return true;
89 }
90
91 if (mobile == 1) {
92 document.addEventListener("deviceready", init, false);
93 } else {
94 window.onload = init;
95 }
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
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
Web Development News
Developer Poll
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- RSS Feeds
- What's the tweeting protocol?
- New Products
- Trying to Tame the Tablet
- Dart: a New Web Programming Experience
- IT industry leaders
4 min 13 sec ago - Reply to comment | Linux Journal
16 hours 52 min ago - Reply to comment | Linux Journal
19 hours 25 min ago - Reply to comment | Linux Journal
20 hours 42 min ago - great post
21 hours 17 min ago - Google Docs
21 hours 39 min ago - Reply to comment | Linux Journal
1 day 2 hours ago - Reply to comment | Linux Journal
1 day 3 hours ago - Web Hosting IQ
1 day 4 hours ago - Thanks for taking the time to
1 day 6 hours ago







Comments
website development in indore
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
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
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
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!
Post new comment