Build native mobile applications with Jo and PhoneGap

Develop Android applications with HTML and JavaScript code

The mobile application development space is progressing rapidly; this is partly due to new frameworks that have emerged with promises to make mobile development easier and more approachable to a traditional web developer. This article focuses on developing native mobile applications by applying the HTML, CSS, and JavaScript language skills you already have to two frameworks: a new framework called Jo, and an open source framework called PhoneGap that lets you access native features on some of the most popular mobile platforms.

Brice Mason, Senior Web Developer, Equip For Quality

Brice MasonBrice Mason is a husband and father from upstate New York. He is also a developer at EQUIP For Quality, where he works on a team developing the next generation of health care analytics software for the long-term care industry. He maintains a personal site at http://www.bricemason.com.



01 March 2011

Also available in Chinese Japanese Portuguese

Mobile web or mobile application?

Mobile application development can basically take two routes: web and native. Mobile web application development is just like traditional web development but targets a mobile platform. Your application is stored and served by a web server and consumed by a mobile web browser. As you might expect, the resources and capabilities available to you in the browser are limited. Contrast this with native development, which gives you access to core features of a mobile operating system. Therefore, mobile web application development prompts you to work in the browser, while native mobile application prompts you to work with the mobile operating system.

Building a native mobile application opens many more doors for developers. In the past, you needed to master multiple languages and application programming interfaces (APIs) on multiple platforms to build a mobile application. This is no longer necessary.

This article walks through the basic use of Jo and PhoneGap. Jo is lightweight, has extensive cross-platform support, and integrates well with other frameworks. PhoneGap is the key to building the native applications because it acts as a bridge to all the rich core features of the mobile platform while preserving the development environment of HTML, CSS, and JavaScript code.

What is Jo?

Jo is a new framework developed by Dave Balmer from Palm. It is an extremely lightweight HTML5 mobile web application framework with extensive platform support that includes HP webOS, Apple iOS, Android, Symbian, and even Mac OS®X Dashboard widgets. Although Jo is under active development, it lends itself to learning about mobile web application development. Its size and feature set are approachable, letting you focus on the core concepts.

What can Jo do?

This example builds a simple card-based layout that showcases several important characteristics of Jo that will help you start building applications.

Getting started

First make sure you have an appropriate HTML5-capable browser to use as your development environment. Safari and Chrome are the two best browsers to use for Jo development. Work with the console exposed by these browsers to debug scripts, set breakpoints, and dump data for inspection. Next, download the Jo source code from GitHub (see Resources) and extract it to the root of your local web server. Rename this extracted directory to something more generic, such as jo. Now browse to the Jo samples page at http://localhost/jo/samples/test.html and see a screen similar to Figure 1.

Figure 1. The Jo Kitchen Sink Demo
Screenshot of the Jo Kitchen Sink Demo

Now that you have downloaded and extracted Jo, begin building your Jo application. Start by creating two files in your web root: index.html and application.js. The index.html file contains the code shown in Listing 1.

Listing 1. Index page for your sample application
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My First Jo App</title>
<!-- jo styles -->
<link rel="stylesheet" type="text/css" href="jo/css/jo.css" />
</head>
<body>
<!-- jo framework script -->
<script src="jo/js/jo.js"></script>

<!-- our application script -->
<script src="App.js"></script>

<script>
  // initializes jo
    jo.load();
  
  // our app initialization code
    App.init();
</script>

</body>
</html>

Listing 1 shows the index page you’re using to organize and invoke your scripts and styles. This might look familiar if you’ve developed JavaScript applications in the past. The default styles that support Jo are included in the head of the document; the scripts are included in the body. Notice that the jo.js file is also included. This is the version of the framework that has not been minified and is recommended for development. Hook in the jo_min.js file when you're ready to deploy to production. The file ends with the jo.load() statement, which initializes the Jo framework, followed by your initialized code denoted by App.init(). The initialization code is shown in Listing 2.

Listing 2. Initialization code for your sample application
// demonstrates the javascript module pattern
var App = function() {

  // private members
     
  var init = function() {
    alert("the app is initialized");
  };
  
  
    // returns an object literal of members to be made public
  return {
    init: init
  };
}();

Building a Jo layout

Now that your shell is in place, modify it to produce a basic layout in Jo, as shown in Listing 3. This layout is the beginning of a simple master-detail pattern.

Listing 3. A layout built with Jo
var App = function() {
  var deviceScreen;
  var mainContainer;
  var mainNavBar;
  var mainMenu;
  var cardStack;
  var menuCard;
  
  // initialization function
  var init = function() {    
    // create the main container
    mainContainer = new joContainer([
      mainNavBar = new joNavbar("My First Jo App"),
      cardStack  = new joStackScroller()
    ]).setStyle({position: "absolute", top: "0", left: "0", bottom: "0", right: "0"});
    
    // create the device screen
    deviceScreen = new joScreen(mainContainer);
    
    // hook up the nav bar with the card stack
    mainNavBar.setStack(cardStack);
    
    // create a menu card
    menuCard = new joCard([
      mainMenu = new joMenu([
        { title: "Go to form", id: "form-card" }
      ])
    ]);
    
    // add the menu card to the card stack
    cardStack.push(menuCard);
  };
  
  
  // public members
  return {
    init: init
  };
}();

Here is where you really jump into Jo. First, a number of variables are defined to represent some key assets in the application, such as the device screen, card layout management, and navigation. The main layout is managed by the creation of a joContainer that has a navigation bar (represented as a joNavbar object) and a card management mechanism (represented as a joStackScroller object). This container is added to the device screen and fills all usable space. The mainNavBar.setStack(cardStack) statement is used to bind the card stack to the navigation widget, resulting in the automatic management of navigation between cards. Finally, an instance of joCard that contains a menu—a glorified list of items—is created and added to the card stack. Successful execution of this code results in a screen similar to Figure 2.

Figure 2. The rendered Jo layout
Screenshot of the rendered Jo layout

Advanced layout techniques

Once your list layout has been configured, continue creating the detail cards and wire them together, as shown in Listing 4.

Listing 4. An advanced layout using joCache
var App = function() {
  var deviceScreen;
  var mainContainer;
  var mainNavBar;
  var mainMenu;
  var cardStack;
  var menuCard;
  
  // initialization function
  var init = function() {    
    // ... same code here as listing 3
    
    // register click handler for menu
    mainMenu.selectEvent.subscribe(function(id) {
      cardStack.push(joCache.get(id));  
    });
    
    // initialize the card cache
    initCardCache();
  };
  
  // initializes the cache used to store cards
  // this helps us only use what we need when we need it
  var initCardCache = function() {
    // create the form card
    joCache.set("form-card", function() {
      return new joCard([
        new joLabel("Name:"),
        new joInput(),
        
        new joLabel("Password:"),
        new joPasswordInput(),
        
        new joLabel("Description:"),
        new joTextarea(),
        
        new joLabel("Options:"),
        new joOption([ "Option 1", "Option 2", "Option 3" ]),
        
        new joLabel("Toggle:"),
        new joToggle(true),
        
        new joLabel("Selection:"),
        new joSelect([ "Item 1", "Item 2", "Item 3" ]),
        
        new joButton("Submit")
      ]);
    });
  };
  
  
  // public members
  return {
    init: init
  };
}();

It is important to grasp two big concepts that are demonstrated in Listing 4. The first is the creation of a new function named initCardCache, which takes advantage of Jo's caching feature. Cache entries are added with a string ID (the unique identifier) and a function (the entry’s value). The function returns a newly constructed joCard that is configured with form controls from the Jo framework. Using joCache in this way allows for deferred object creation of the detail views in your application, and results in better performance. The second concept demonstrated is the wiring of the listing card with its detail views through an event handler. When an item is selected in the menu, the ID of the menu item is used to retrieve a view from cache. Though you can only define one view here, this pattern can be easily extended.

Clicking the Go to form list item results in a screen similar to Figure 3.

Figure 3. A sampling of Jo form controls
Screenshot of a sample page that renders various Jo form controls

Notice the Back button at the top left of the screen. This is the result of the binding between the card stack and the navigation widget mentioned earlier. Now hook the empty form to a data source.

Data sources in Jo

Jo offers a number of solutions for managing information stores such as WebKit SQLite and HTML5 databases. However, one of the simplest and most useful classes for managing data is joRecord, which you can use as the interface to your form, as shown in Listing 5.

Listing 5. Binding form data with joRecord
var App = function() {
  // ...same as listing 4
  var formRecord;
  
  // initialization function
  var init = function() {
    // ... same as listing 4
  };
  
  // initializes the cache used to store cards
  // this helps us only use what we need when we need it
  var initCardCache = function() {
    // create the form card
    joCache.set("form-card", function() {
      // initialize the persistent form record
      formRecord = new joRecord({
        name: "Nigel Bitters",
        password: "somepassword",
        description: "Some long winded description here.\nWith a line break!",
        option: 1,
        isActive: true,
        selection: 2
      });
                      
      return new joCard([
        new joLabel("Name:"),
        new joInput(formRecord.link("name")),
        
        new joLabel("Password:"),
        new joPasswordInput(formRecord.link("password")),
        
        new joLabel("Description:"),
        new joTextarea(formRecord.link("description")),
        
        new joLabel("Options:"),
        new joOption([ "Option 1", "Option 2", "Option 3" ], formRecord.link("option")),
        
        new joLabel("Toggle:"),
        new joToggle(formRecord.link("isActive")),
        
        new joLabel("Selection:"),
        new joSelect([ "Item 1", "Item 2", "Item 3" ], formRecord.link("selection")),
        
        new joButton("Submit").selectEvent.subscribe(function() {
          // dump out the modified data
          console.dir(formRecord);                            
        })
      ]);
    });
  };
  
  // public members
  return {
    init: init
  };
}();

In the initCardCache function, an instance of joRecord is created that not only initializes the values of the form, but also manages the changes to the form. Figure 4 shows how values are initialized.

Figure 4. Initialized values in the form
Screenshot of a sample page that renders various Jo form controls with initialized values

Run the example in Listing 5, modify the data in the form, and then click the Submit button. Upon inspecting the console in your browser, you should see the modified form record.

You’ve covered the major features that create a working mobile web application. Now consider building a native mobile application by adding PhoneGap.

What is PhoneGap?

PhoneGap is an open source framework for building native mobile applications with HTML and JavaScript code. It is the glue that binds your user interface with the operating system of the mobile platform you want to target. PhoneGap supports such platforms as the iPhone, Android, Blackberry, Symbian, and Palm. The native features exposed by PhoneGap—such as accelerometer access, camera and media support, contacts, geolocation, file, network, and storage—are also highly desirable for mobile application development.

Work through a simple example of a contacts application for the Android platform. First configure your development environment.

Getting PhoneGap up and running might seem a little daunting if you've only done pure web development in the past. Table 1 lists a number of prerequisite software requirements for PhoneGap.

Table 1. PhoneGap software requirements
SoftwareDescription
Eclipse integrated development environment (IDE)Builds and runs your PhoneGap applications
Java Development Kit (JDK)Includes the Java compiler and supporting tools
Android software development kit (SDK)Includes the base code and emulators for running your applications
Android Development Tools (ADT)Accesses development plug-in for Eclipse
Apache AntManages the build process of your projects
RubyManages various tasks in PhoneGap such as project creation

This article does not cover the entire process of configuring the development environment. However, Resources provides some tools to configure it. First, follow the directions in the Installing the SDK document on the Android developers site, which takes you through the first four requirements listed in Table 1. Next, download and install Apache Ant and Ruby.

At this point, all major components are in place. You have an IDE for loading, building, and running PhoneGap projects (Eclipse), along with all the supporting tools. Finish by doing some configuration work.

The build process relies on a number of environment variables being defined on your system, as described in Table 2.

Table 2. Environment variables
VariableDescription
ANDROID_HOMEPoints to the root location of the Android SDK on your computer
ANT_HOMEPoints to the root location of the Apache Ant install on your computer
JAVA_HOMEPoints to the root location of the JDK on your computer
PATHDefines the paths to the bin folders of Ruby, Ant, your JDK, and the tools folder under your Android SDK installation.

Last, define an Android Virtual Device (AVD) in Eclipse. The AVD is a set of configuration options that model an actual Android-powered device and is essential to running your PhoneGap application on an Android emulator. To create an AVD, open Eclipse and navigate to Window > Android SDK and AVD Manager. You should see a screen similar to Figure 5.

Figure 5. Android SDK and AVD Manager
Screenshot of the Android SDK and AVD Manager

Select the Virtual Devices item in the left-hand menu and click the New… button. Enter the information, as shown in Figure 6, and then click Create AVD. After closing the Android SDK and AVD Manager, you are ready to load, build, and run a PhoneGap project.

Figure 6. Create new Android Virtual Device (AVD)
Screenshot of Create new Android Virtual Device (AVD)

Running the PhoneGap example project

Configuring a development environment for PhoneGap is an involved process, but loading projects is much easier. To run your first PhoneGap application, download and extract the latest package of the phonegap-android project from GitHub to your computer (see Resources). Next, open a command prompt and change directories to the root of your PhoneGap installation. Run the command, as shown in Listing 6.

Listing 6. Command to create a PhoneGap project
./bin/droidgap create example

This command creates an Android project from the web source files in the example folder. To load the project in Eclipse, navigate to File > New > Project…. Drill down to the Android folder, select Android Project, and click Next >. Configure the project as shown in Figure 7, and then click Finish.

Figure 7. Screenshot of project settings
Screenshot of project settings

The location of the source is the folder named example_android in your PhoneGap installation. This is where the project files were created from the droidgap command. Now that the project is loaded in the Eclipse project explorer, drill down to the libs folder, right-click the phonegap.jar file and select Build Path > Add to Build Path, as shown in Figure 8.

Figure 8. Adding phonegap.jar to the build path
Screenshot of menu path used to add phonegap.jar to the build path

When you run the application in Eclipse as an Android application, you should see a screen similar to Figure 9.

Figure 9. PhoneGap example application running in the Android emulator
Screenshot of the PhoneGap example application running in the Android emulator

Adding Jo to PhoneGap

You might have noticed that although you must complete a number of steps to get PhoneGap up and running, working with the framework is no different than any other modern JavaScript framework. Now that you can create, build, and run a PhoneGap application for Android using Eclipse, you can easily add some Jo to manage your user interface. In fact, the Jo wiki site offers a sample index file that contains the recommended configuration shown in Listing 7.

Listing 7. Sample index page for working with PhoneGap
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>My App</title>

    <!-- stylesheets -->
    <link rel="stylesheet" href="css/aluminum.css" type="text/css">
    <link rel="stylesheet" href="css/chrome.css" type="text/css">
    <link rel="stylesheet" href="css/myapp.css" type="text/css">
</head>
<body>

<!-- lib -->
<script src="phonegap.js"></script>
<script src="js/jo_min.js"></script>

<!-- app -->
<script src="js/myapp.js"></script>

<script>
    jo.load();
    joEvent.touchy = true;
    MyApp.load();
</script>

</body>
</html>

Listing 7 has a familiar format since the stylesheets are included in the head of the document. The body of the document has the framework scripts hooked in first, followed by an application script file. The line you haven't encountered yet is joEvent.touchy = true. This property makes sure that all relevant mouse-based events are translated into touch events for use on mobile devices.

Conclusion

Although you can accomplish a lot with Jo and PhoneGap together, remember that Jo doesn't need PhoneGap and PhoneGap doesn't need Jo. They can both exist on their own or with other frameworks. However, the simplicity and size of Jo coupled with the power of PhoneGap can result in an effective tool to development rich, mobile native applications for a wide range of platforms.

Resources

Learn

Get products and technologies

  • Download source code, read documentation, and join the support forum of the Jo HTML5 Mobile App Framework.
  • Download the PhoneGap source code, read documentation, and connect with the community.
  • Download the Jo source code from GitHub.
  • To run your first PhoneGap application, download and extract the latest phonegap-android project package to your computer from GitHub.
  • The Eclipse IDE is an open source IDE that supports Android application development.
  • Use the Android SDK to download the libraries and tools used to support Android application development.
  • The Apache Ant is a Java library and command-line tool for processing build files in software development.
  • Download an installer for Windows machines that includes the Ruby language and environment.
  • The ADT Plugin for Eclipse installs support for Android project development.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, Open source, Industries, Mobile development
ArticleID=629940
ArticleTitle=Build native mobile applications with Jo and PhoneGap
publish-date=03012011