Cordova – First Application – Part 2

Here we go with the second part of article series with title Cordova – First Application. In first part of this series I have explained details how to install Cordova, setup Cordova project in NetBeans and finally described some details about application that we are going to develop in this tutorial.  so let’s go into implementation details, first we look at the index.html that is created automatically when you create default project.

<!DOCTYPE html>

 <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; connect-src">
 <meta name="format-detection" content="telephone=no">
 <meta name="msapplication-tap-highlight" content="no">
 <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
 <link rel="stylesheet" type="text/css" href="css/index.css">
 <link rel="stylesheet" href="js/libs/jquery-mobile/"/>
 <script type="text/javascript" src="js/libs/jquery/jquery.min.js"></script>
 <script type="text/javascript" src="js/libs/jquery-mobile/"></script>
 <title>Test Money Convertor</title>
 <div data-dom-cache="false" data-role="page" id="mainpage">
 <div data-role="header">
 <h1 id="header">Currency Converter</h1>
 <a data-role="button" class="ui-btn-right" id="aboutBtn">About</a>
 <div role="main" class="ui-content">
 <label for="select-currency" class="ui-select">Select Currency</label>
 <select name="select-currency" id="select-currency">
 <option value="DEFAULT">...</option>
     <option value="USD">US Dollar</option>
      <option value="EUR">Euro</option>
      <option value="CAD">Canadian Dollar</option>
      <option value="AED">UAE Dirham</option>
 <button class="ui-btn" id="getDataBtn">Fetch Data</button>
 <table id="resultTable" class="ui-responsive table-stroke">
 <tbody id="resultBody"></tbody>
 <div data-role="footer">
 <script type="text/javascript" src="cordova.js"></script>
 <script type="text/javascript" src="js/index.js"></script>

First I shall describe these lines between head tags, especially important are those meta tags that define how application behaves.

Meta tag on line five width http-equiv=”Content-Security-Policy” parameter defines some security policies, some of them are that page can load sources from it’s own package, what kind of media application can load, restrictions on JavaScript, etc. But most important one for us is to enable java script to use resources from other sources, in our case Yahoo REST services. So parameter connect-src enables this.

Next meta tag on line 6 determines determines whether or not telephone numbers in the HTML content will appear as hypertext links (so that you can actually dial phone number by tapping it  in application). In our case this is disabled.

Meta tag on line 7 disables on windows phones tap highlighting feature.

And final meta tag on line 8 gives instructions how to control page’s dimensions and scaling.

Lines from 9 to 12 are loading custom and jquery-mobile css so as jquery and jquery-mobile libraries that we have imported into project in first part of this article.

Now let’s look at the body part of the html file, over there everything is fair simple there couple of div tags that represent footer, header and main section of page. Now  div tags inside body element  have parameter data-role, these are html 5 tags used by JQuery Mobile to allow for markup-based initialization and configuration of widgets, in our case to specify what divs represent page, header, footer, main page, etc, also this can be used on other tags, like <a> tag in our case on line 19 where it is presented as a button in application. More details on these tags and some other tags can be found in JQuery Mobile documentation.

In the div marked as data-role=”header” I have placed title of the application and one small button that will open up a dialog to display some information about application itself.

Important parts inside div marked as data-role=”main” are one select tag with options to select one out of several currencies, button that will call Yahoo REST web services and display result in a table just below, with id set as resultTable. This table initially has only header with two columns to display currency and rate for specific currency.

If you run now in your project this application you would get screen similar to the one in first part of this article series.

And now it is time to implement some functionality, so that buttons on the application are doing some stuff. So to do that we shall have to create some methods in the index.js file. First thing that we shall implement is initialization , actually we are just going to add event listener to the document object ot call another function onDeviceReady when event deviceready is triggered (when all initialization of Cordova framework is initialized this event deviceready is triggered).

$(document).ready(function() {
  document.addEventListener(&amp;amp;amp;quot;deviceready&amp;amp;amp;quot;, onDeviceReady, false);

function onDeviceReady() {
  document.getElementById(&amp;amp;amp;quot;getDataBtn&amp;amp;amp;quot;).addEventListener(&amp;amp;amp;quot;click&amp;amp;amp;quot;, getData);
  document.getElementById(&amp;amp;amp;quot;aboutBtn&amp;amp;amp;quot;).addEventListener(&amp;amp;amp;quot;click&amp;amp;amp;quot;, showAbout);

var callUrl;
var prefixUrl = '*';
var posfixUrl = ')&amp;amp;amp;amp;format=json&amp;amp;amp;amp;diagnostics=false&amp;amp;amp;amp;';

function createQuery(currency){
  if(currency == "USD"){
    callUrl = prefixUrl + '%22USDEUR%22%2C%20%22USDCAD%22%2C%20%22USDAED%22' + posfixUrl;
  }else if(currency == "EUR"){
    callUrl = prefixUrl + '%22EURUSD%22%2C%20%22EURCAD%22%2C%20%22EURAED%22' + posfixUrl;
  }else if(currency == "CAD"){
    callUrl = prefixUrl + '%22CADUSD%22%2C%20%22CADEUR%22%2C%20%22CADAED%22' + posfixUrl;
  }else if(currency == "AED"){
    callUrl = prefixUrl + '%22AEDEUR%22%2C%20%22AEDCAD%22%2C%20%22AEDUSD%22' + posfixUrl;

If we check onDeviceReady function, first to lines of this function are just registering functions that will be called on click events for buttons, one button is to show about dialog and another is to fetch data by calling web service and display result in a table. Final and third line of this method is to set table that has id set as resultTable to be initially hidden.

Also I have defined couple of additional variables below this onDeviceReady function, callUrl will represent url that will be a call to a REST web service with all needed parameters, beside this one there are two more representing parts of URL that are static – prefixUtl and postfixUrl, using these two variables final url will be formed by concatenating these two static variables with dynamic part  that will be formed by calling createQuery function defined as last in this section of code.

function showAbout() {
   showAlert("Created by Djordje Popovic", "Currency Converter");
function showAlert(message, title) {
   if (window.navigator.notification) {
      window.navigator.notification.alert(message, null, title, 'OK');
   } else {
      alert(title ? (title + ": " + message) : message);

In above block of code we have a method showAbout, if you check the first part of this article with code from index.html file and that initialization part of code you will figure out that this method is called by pressing that About button. This  method just simply calls another method showAlert that is supposed to bring simple alert notification, inside this method there in if condition that determines if application is able to display native alerts by running on device or in case application is running in browser to call standard alert method.

And now final part of code that will actually call web service and display results of response. This code represents one method that is called by clicking that button Fetch Data, defined in code of index.htmls file.

function getData(){
   var selectedValue = document.getElementById("select-currency").value;
   if (selectedValue == 'DEFAULT'){
     showAlert("Please select currency", "Alert");
        type: "GET", 
        url: callUrl, 
        dataType: "json", 
        success: function(resp){ 
          $("#resultTable tbody tr").remove();
          var rates = resp.query.results.rate;
          for(var i =0; i< rates.length; ++i){
        error: function(e){ 
          showAlert("There is an error in accessing web service, please check your connection", "Error");

At line 2 of this code above, we are fetching selected value from that select input field where user needs to specify currency that he wants to see conversions for. Lines 3 and 4 just handles case if user did not select any of the currencies. On line 6 we are calling method createQuery that will generate that url with all parameters in order to call web service. Finally, lines from 7 to 21 represent actual call of web service, I will not go into details of calling web service since this is not topic of this article, anyhow I believe this part of code is pretty  much self explanatory.

Now we can say that we are done with coding and ready to run application. NetBeans allows you to select device, emulator or browser that you would like to run this application for, since we have prepared this project to be built for android device we shall select existing android device that is already registered by using option shown on below screen capture


After this all you have to do is select run and application will be deployed on your device. You can test application by selecting currency and submitting request by pressing Fetch Data button, result should be rendered in table below. One note, you can take your device off the network and try same scenario, since application is not able to call and get response from web service you showl get alert message that there is a problem in calling web service and to check network connection.

I believe you got the idea now how development of Cordova application is easy and I would say clean.

Well this is for now all that I have created using Cordova, I shall continue exploring and in couple of next articles present some new use cases that I have built.



Posted in General Programming Tagged with: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.