Build a Currency Converter with jQuery Mobile and Cordova: Finishing The App

This entry is part 6 of 6 in the series Build a Currency Converter with jQuery Mobile and Cordova

Build a Currency Converter with jQuery Mobile and Cordova

In the previous part of this series, I showed several other functions of the functions.js file, highlighting their key points. In this sixth and final part, I’ll describe the last function left and the Cordova configuration file that we will use to set properties for our project and define several directives for the Adobe PhoneGap Build service.

Initializing the Application

First, within the index.html file, I’ll attach the function, initApplication()—which I’ll describe in a few moments—to the deviceready event, which is fired when Cordova is fully loaded.

$(document).one('deviceready', initApplication);

Once started, the function translates the multi-language written copy described in Build a Currency Converter with jQuery Mobile and Cordova: Translation and Conversion Logic, calling the translateMainPage() function if the user’s preferred spoken language is available. Then, it calls the openLinksInApp() function to manage external links, as described in part 5. These two actions are independent from the rest of the application, even if the device doesn’t satisfy the requirements.

translateMainPage();
openLinksInApp();

After running the two operations mentioned above, “Currency Converter” tests the device against the requirements (discussed in part 4), and if they aren’t satisfied, it disables the “Convert” button and exits the function.

if (checkRequirements() === false)
{
  $('#submit-button').button('disable');
  return;
}

Now that the basic operations have been executed, we can run the other and more heavy (actually, they’re not really that heavy) functions. So, to give the user a feeling that something is happening behind the scenes, one function displays the loader widget. Then, it continues updating the interface, filling the two select boxes with the stored currency values by calling fillCurrenciesSelection(), the function to update the rates, updateExchangeRates(), and the final function that updates the labels by reading the date and time of the last currency exchange rate update, updateLastUpdate().

$.mobile.loading('show');

fillCurrenciesSelection();
updateExchangeRates();
updateLastUpdate();

At this point, all the necessary processes have been called, and we need to attach handlers to some of the pages’ elements and events. The first handler will update the rates as soon as the online event is fired. The latter, as you may guess, fires when a Cordova application detects that it’s connected to the Internet.

$(document).on('online', updateExchangeRates);

The next handler is very important, since it’s the one the execute the money conversion and because it’s attached to the “Convert” button. After it has retrieved the values of the money and the two currencies selected from the interface, it calls the convert() method of the Currency class to made the conversion calculation. Then, it calls the numberToString() to localize the result based on the user preferences and injects the end result into the page. Finally, it updates the app settings with the last currencies chosen by the user.

$('#submit-button').click(function(event) {
  event.preventDefault();

  // Convert the value
  var result = Currency.convert(
    $('#from-value').val(),
    $('#from-type').val(),
    $('#to-type').val()
  );

   // Localize the result
   navigator.globalization.numberToString(
    result,
    function(number)
    {
      $('#result').text(number.value);
    },
    function()
    {
      $('#result').text(result);
    }
  );

  // Update settings
  var settings = Settings.getSettings();
  if ($.isEmptyObject(settings))
    settings = new Settings();
  settings.fromCurrency = $('#from-type').val();
  settings.toCurrency = $('#to-type').val();
  settings.save();
});

Having finished the “Convert” button functionality, we can now move on to the “Reset” button. Its behavior is quite straightforward. If the user clicks it, we set the input field for the money to convert and the conversion result to zero. We also reset the last chosen currencies by changing the selected currency types for both the select boxes to the first currencies listed.

$('#reset-button').click(function(event) {
  event.preventDefault();

  $('#from-value').val(0);
  $('#form-converter select').prop('selectedIndex', 0).selectmenu('refresh');
  $('#result').text(0);
});

The last handler we need to put in place is for the “Update data” button—the one at the top-right of the main screen. The attached function simply tests for an Internet connection, and if it’s found, runs the updateExchangeRates() function. Otherwise it notifies the user that it’s not connected to the Internet.

$('#update-button').click(function(event) {
  event.preventDefault();

  if (navigator.network.connection.type === Connection.NONE)
  {
    console.log('The connection is off. Can't update exchange rates.');
    navigator.notification.alert(
      'Your device has the connections disabled. Can't update exchange rates.',
      function(){},
      'Error'
    );
  }
  else
    updateExchangeRates();
});

Now that all of the pieces are in their place, we can hide the loading widget from the user so that they’ll know that that all background operations are finished.

$.mobile.loading('hide');

As a conclusion of the whole discussion, here is a screenshot of our “Currency Converter” app:

Currency Converter main page

Create the Cordova Configuration

Since we’ll use the Adobe PhoneGap Build service to package our project, in order to set its metadata (the version, the name, the author, and so on), we’ll use a configuration file called config.xml. Explaining the format in detail is outside the scope of this article, but I’ll highlight the main concepts and focus on the important <access> tag. To have an in-depth look of what you can do with this file, you can read the official documentation page.

The cited file follows the W3C widget specification and must reside in the root of the project files, at the same level as the index.html file. The root of the whole document is a <widget> tag that has several attributes, but the mains ones are id (the unique identifier of the app) and version (that specifies the version of the app). Inside the <widget> tag, you can include several elements:

  • name (required): Specify the name of the application. It doesn’t have to be unique.
  • description (required): Specify the description of your work. This will be shown in the app’s marketplace listing.
  • author (optional): The app’s author. Unfortunately, you can only specify one author, so you can’t have details for multiple authors.
  • icon (optional): The icon to display on the devices that will install your app. If you do not specify it, the Cordova logo will be used.
  • feature (optional): Specify the features you want to use. Some operating systems, before installing the app, ask the user to provide permissions for those features. In “Currency Converter”, the only required feature is access to the Internet connection.
  • preference (optional): A set of preferences you want to apply, such as the Cordova version, to use when packaging the project.
  • splash (optional): This tag sets the splash screen of the application—the image to show while it’s loading.

The <access> tag is very important because, citing the documentation, it provides your app with access to resources on other domains—in particular, it allows your app to load pages from external domains that can take over your entire webview. Recalling what we discussed in the section “Managing External Links” of the previous part, in order to open the external links in the Cordova WebView, we must add them to the app whitelist. Using the <access> tag, you have several ways to add links. In fact, you can specify each link you want to add individually. Consider the following example:

<access origin="https://www.audero.it" />
<access origin="https://www.buildmobile.com" />

For each of the above approved domains, you can also include all the subdomains using the subdomains attribute:

<access origin="https://www.audero.it" subdomains="true" />

Since our app won’t retrieve links from external and unsafe sources, we can shorten the process allowing for any external resource using the * special character like the following example:

<access origin="*" />

Now that I’ve pointed out the key points of the format, you can understand the source of the configuration file of our project. The complete file is below.

<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns     = "http://www.w3.org/ns/widgets"
        xmlns:gap	= "http://phonegap.com/ns/1.0"
        id        = "com.audero.free.utility.currencyconverter"
        version   = "1.0.0">

   <name>Currency converter</name>

   <description>Currency converter is a simple app that helps you convert from a currency to another. You can update the exchange rates anytime you want so you'll have always an up-to-date conversion.</description>

   <author href="http://www.audero.it" email="aurelioderosa@gmail.com">Aurelio De Rosa</author>

   <feature name="http://api.phonegap.com/1.0/network"/>

   <preference name="phonegap-version" value="2.3.0" />
   <preference name="target-device" value="universal" />

   <access origin="*" />

   <!-- Icons -->
   <icon src="icon.png" width="64" height="64" gap:role="default" />
   <icon src="images/icon-72x72.png" width="72" height="72" gap:platform="android" gap:density="hdpi" />
   <icon src="images/icon-96x96.png" width="96" height="96" gap:platform="android" gap:density="xhdpi" />
   <icon src="images/icon-72x72.png" width="72" height="72" gap:platform="ios" />

   <!-- Splash Screens -->
   <gap:splash src="splash.png" />
   <gap:splash src="images/splash-160x220.png" gap:platform="android" gap:density="ldpi" />
   <gap:splash src="splash.png" gap:platform="android" gap:density="mdpi" />
   <gap:splash src="images/splash-450x650.png" gap:platform="android" gap:density="hdpi" />
</widget>

Conclusion

I have to compliment those of you who completed the whole series. The growing number of hybrid apps released, including the one we just built, prove that you can build amazing games and utilities using web technologies that you’ve already mastered. There are pros and cons in choosing to develop a hybrid app, but this is definitively one additional tool in your development tool belt. My last contribution is giving you the link to the Currency Converter repository. Here you’ll find and download the full and ready-to-work package. For those of you that are too lazy to build the app, I have also created a public page where you can download the installer for every platform supported by the Adobe Build PhoneGap service. As a final note, Currency Converter is released under the CC BY 3.0 (“Creative Commons Attribution 3.0″) license.

I hope you enjoyed the series and have more comfort and confidence with hybrid apps. Thanks for following!

Build a Currency Converter with jQuery Mobile and Cordova

<< Build a Currency Converter with jQuery Mobile and Cordova: Rate Updates

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.sacbta.org JITESH NAIDOO

    I loved your series Aurelio. Hope to get more projects from your in the future. Bene grazia!

    • http://www.audero.it/ Aurelio De Rosa

      I’m glad you like it. Thank you for reading reading us!