Book Image

PhoneGap 3 Beginner's Guide

By : Giorgio Natili
Book Image

PhoneGap 3 Beginner's Guide

By: Giorgio Natili

Overview of this book

<p>You don’t have to know complex languages like Objective C to compete in the ever-growing mobile market place. The PhoneGap framework lets you use your web development skills to build HTML and JavaScript-based mobile applications with native wrappers that run on all the major mobile platforms, including Android, iOS, and Windows Phone 8.</p> <p>"PhoneGap 3 Beginner's Guide" will help you break into the world of mobile application development. You will learn how to set up and configure your mobile development environment, implement the most common features of modern mobile apps, and build rich, native-style applications. The examples in this book deal with real use case scenarios, which will help you develop your own apps, and then publish them on the most popular app stores.</p> <p>Dive deep into PhoneGap and refine your skills by learning how to build the main features of a real world app.</p> <p>"PhoneGap 3 Beginner's Guide" will guide you through the building blocks of a mobile application that lets users plan a trip and share their trip information. With the help of this app, you will learn how to work with key PhoneGap tools and APIs, extend the framework’s functionality with plug-ins, and integrate device features such as the camera, contacts, storage, and more. By the time you’re finished, you will have a solid understanding of the common challenges mobile app developers face, and you will know how to solve them.</p>
Table of Contents (22 chapters)
PhoneGap 3 Beginner's Guide
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – rendering localized messages


Refer to the following steps to render different messages in your app according to the device's language settings:

  1. Open the command-line tool and create a new PhoneGap project called globalization.

    $ cordova create ~/the/path/to/your/source/globalization com.gnstudio.pg.globalization Globalization
    
  2. Add the Globalization API plugin using the command line.

    $ cordova plugins add https: //git-wip-us.apache.org/repos/asf/cordova-plugin-globalization.git
    
  3. Using the command-line tool, add the platform you want to use for this test (Android, Blackberry, iOS, or Windows Phone 8).

    $ cordova platforms add android
    
  4. Go to the www/js folder, create the libs folder and the subfolders needed to store the require.js file and the i18n plugin.

    |-libs
    |---require
    |-----plugins
  5. Download and save the minified version of Require.js available at http://requirejs.org/docs/download.html#requirejs in the js/libs/require folder and the i18n plugin available at http://requirejs.org/docs/download.html#i18n in the js/libs/require/plugins folder.

  6. Go to www/js and create a new folder named nls (the plugin will search for a folder named in this way to load language files). In this folder create a subfolder to store the data for each supported locale and a root folder to be used in case the user locale is not yet implemented (i.e., root).

    |-nls
       |---en-us
       |---es-es
       |---fr-fr
       |---it-it
       |---root
  7. Create a file named connection.js in the nls/root folder containing all the default messages to render in case the app is having connection issues. The syntax required by the i18l plugin is very similar to the one used to define a new Require.js module except that the name of the module is not required.

    // root
    ;define({
        'cannotConnect':  'The app can\'t connect to internet.',
        'connectionSlow': 'The connection is slow be patient.',
        'connectionError':'Please try again later.'
    });  
  8. Create a language file for each supported locale using the same name and the same syntax but with different content so that you can easily get the differences when testing your app. Save the file in the language-specific folder (for example, fr-fr).

  9. Go to the nls folder and create another JavaScript file named connection.js in order to specify the supported locales.

    ;define({
        'root': true,
        'fr-fr': true,
        'en_us': true,
        'es-es': true,
        'it-it': true
    });
  10. Go to the js folder, create a new JavaScript file named main.js, and define a new Require.js module specifying a dependency to the connection.js language files.

    ;define('main', ['i18n!nls/connection'],
           (function(connection){
    
                // All the methods and variables will go here
    
    }));
  11. Create in the main module a function named init and define in its body a listener for the deviceready event.

    var init = function(){
    
        document.addEventListener('deviceready', onDeviceReady);
    
    };
  12. Return the init function at the end of the module in order to be able to call it from other modules.

    return{
    
            init: init
    
        }
  13. Once the deviceready event is triggered and the PhoneGap framework is loaded, it's possible to access the Globalization API and discover the device current locale using the getLocaleName method.

    var onDeviceReady = function(evt){
    
        var g = navigator.globalization; 
        g.getLocaleName(onLocaleName, onGlobalizationError);
    
    };
  14. Define the handler onLocaleName and use the values returned by the i18n plugin to display all of them on the screen.

    var onLocaleName = function(locale){
    
        console.log('onLocaleName', locale.value);
    
        var deviceready = document.querySelector('#deviceready');
        var element = document.createElement('span');
    
        element.innerHTML += 'The cannotConnect message is:<i>' +
                      connection.cannotConnect + '</i><br>';
    element.innerHTML += 'The connectionSlow message is:<i>' +
                      connection.connectionSlow + '</i><br>';
    element.innerHTML += 'The connectionError message is:<i>' +
                      connection.connectionError + '</i><br>';
    
        deviceready.appendChild(element);
    
    };  
  15. Define the onGlobalizationError handler and notify the user that an issue has occurred.

    var onGlobalizationError = function(error) {
    
        var message = 'code: ' + error.code + '\n';
        message += 'message: ' + error.message;
        navigator.notification.alert(message, null);
    
    };
  16. In the js folder create a new JavaScript file named app.js and use it to configure the paths for Require.js to load the main module and call the init method.

    require.config({
    
        paths: {
    
            i18n: 'libs/require/plugins/i18n'
        },
    });
    
    require(['main'], function(main){
    
        main.init();
    
    });
  17. Open the index.html file and add a script tag in the head section to load Require.js and the app.js file.

    <script data-main="js/app" src="js/libs/require/require.js"></script>
  18. Open the command-line tool, go to the project folder, and build and run the app on a real device or an emulator.

    $ cordova build
    $ cordova run
    

What just happened?

You developed an app i.e. able to render different text messages based on the user's device language settings.