Build a hybrid mobile app with Cordova and the IBM Bluemix Mobile Data service

05 August 2014
PDF (670 KB)
 

Sign up for IBM Bluemix™
This cloud platform is stocked with free services, runtimes, and infrastructure to help you quickly build and deploy your next mobile or web application.

Bluemix is an open PaaS that includes many embedded, predefined services created by IBM, by third-party groups, and even by users like you. These services are middleware — databases, for example — for your web applications.

According to the Bluemix documentation, all of these services must implement the RESTful API, which is accessible from a JavaScript environment such as a modern browser.

Apache Cordova (PhoneGap) is a mobile app-development framework based on HTML5, CSS3, and JavaScript. Cordova wraps all these web resources into the app, acting like a web server and using Ajax on the mobile device.

Bluemix services, as a resource of Ajax, can be used during Cordova development. This article shows the steps for building an Android Cordova application — a contacts app — by using the Bluemix Mobile Data service.

Note: This example is based on Windows 7.

You'll hook up the app with Bluemix so that information can be stored in the Mobile Data layer in the cloud.

Before you start

 
  1. Download and install the Android SDK. You might need to add adt_root/sdk/tools and adt_root/sdk/platform-tools to your system path variable.
  2. Download and install Node.js.
  3. Create a Bluemix account if you don't already have one.
  4. Download the raw code (www-raw.zip) — use the button that's below this section to take you to the project overview page — and extract it into a directory of your choice.
  5. Have your favorite HTML/JavaScript editor ready to use.

READ: Building Mobile Cloud applications

READ: Apache Cordova documentation

Step 1. Create a mobile boilerplate on Bluemix

 
  1. In your web browser, log in to Bluemix.
  2. In the Bluemix dashboard, click the CREATE AN APP button and choose the Mobile Cloud boilerplate: Screenshot of the Mobile Cloud boilerplate option
  3. Provision the boilerplate with the back-end services (such as the Mobile Data service) that will be needed in your hybrid application, and then click CREATE APPLICATION: Screenshot of the UI for creating a Mobile Cloud app
  4. Enter an app name and a unique name for the Host value (Bluemix doesn't allow duplicate host names), and click CREATE:

    Screenshot of the dialog box for setting the app name and host values

    The Bluemix application is added for you on the dashboard:

    Screenshot of the new app's entry in the dashboard
  5. Click the app link to open the app's overview page. Record the application ID, which you will need later: Screenshot of example app ID
  6. Click the Download SDKs link that's to the left of the ID, choose the JavaScript SDK, and extract the SDK's contents into the directory of your choice:

    Screenshot of the SDKs available for download

    Refer to the API docs in the JavaScript SDK as needed.

Step 2. Create a Cordova project

 
  1. Open a command prompt on your PC and pick a directory to use as your workspace, such as c:/workspace/android. The workspace is a folder for storing your Cordova project.
  2. Use the Node.js npm command to install Cordova:
    npm install -g cordova

    Installing Cordova this way provides scaffolding for building a Cordova app quickly.
  3. Create a Cordova project by running this sequence of commands:
    cordova create demo com.ibm.demo MyDemo
    cd demo
    cordova platform add android

    The cordova platform add android command creates Android support because you have the Android SDK installed.
  4. To add the necessary plugins for Cordova, run:
    cordova plugin add org.apache.cordova.device
    cordova plugin add org.apache.cordova.console

    Optionally, run these commands to add other plugins:
    cordova plugin add org.apache.cordova.camera
    cordova plugin add org.apache.cordova.contacts
    cordova plugin add org.apache.cordova.dialogs
    cordova plugin add org.apache.cordova.geolocation
  5. In the demo subdirectory, replace the www folder in the root path with the extracted www folder from the expanded www-raw.zip that you downloaded earlier from my DevOps Services project.
  6. From the root directory of your Cordova project, run the emulator to verify that everything is okay:
    cordova emulate android

    The emulator shows the initial UI of the app you are creating. In the text box, type Jim to bring up the contact named Jim Halpert: Screenshot of the app in the Android emulator displaying a contact in response to input

Step 3. Implementing the Bluemix Mobile Data API

 

Now you'll hook up the app with Bluemix so that information can be stored in the Mobile Data layer in the cloud:

  1. You need two modules — IBMBaaS and IBMData — from the SDK that you downloaded in Step 1.6. Copy IBMData.js and IBMBaaS.js to the www/js/plugin folder of the extracted raw code.
  2. Create a new JavaScript file called blue-store.js in the project_name/www/js/storage folder.
  3. Using your favorite editor, add the following code to the blue-store.js script, entering the application key from step 1.5 in the first line where indicated;
    IBMBaaS.initializeSDK("place your bluemix app key here");
    IBMData.initializeService();
    var data = IBMData.getService();
    var query = data.Query.ofType("Person");
    var BlueStore = function(successCallback, errorCallback) {
        this.findByName = function(searchKey, callback) {
        	var employees = [];
        	query.find().then(function(people) {
        	    people.forEach(function(person) {
        	    	var fullName = person.get("firstName") + " " + person.get("lastName");
        	    	if(fullName.toLowerCase().indexOf(searchKey.toLowerCase()) > -1){
        	    		employees.push(person.get());
        	        }
        	    });
        	    callback(employees);
        	});
        }
        this.findById = function(myid, callback) {
        	console.log(myid);    	
        	query.find({id:myid}).then(function(person) {
        		//callLater(callback, person[0].get());//callback(person);
        	   callback(person[0].get());
        	});       
        }
        var callLater = function(callback, data) {
            if (callback) {
                setTimeout(function() {
                    callback(data);
                });
            }
        }
        callLater(successCallback);
    }
  4. In project_name/www/js/main.js, replace MemoryStore in the init function with BlueStore.
  5. Modify the JavaScript markup in index.html in the project_name/www folder, adding the Bluemix JavaScript lib and the BlueStore script. Cordova.js is automatically added when the app runs in the emulator or real devices. The final HTML code should look like this:
       <script src="js/plugin/IBMBaaS.js"></script>
       <script src="js/plugin/IBMData.js"></script> 
       <script src="cordova.js"></script> 
       <script src="lib/jquery-1.8.2.min.js"></script>
       <script src="js/storage/blue-store.js"></script> 
       <script src="js/HomeView.js"></script>
       <script src="js/EmployeeView.js"></script>
       <script src="js/main.js"></script> 
    </body>
    </html>

    This is all the JavaScript you will need; remove anything else.
  6. Check the config.xml file in the root folder and ensure that index.html is the booting page and that the Bluemix site is in the cross-domain whitelist:
    <content src="index.html" />
        <access origin="https://mobile.ng.bluemix.net" />
    </widget>

    There's no need to check the generated AndroidManifest.xml file.
  7. Run the emulator and test:
    cordova emulate android

    The Bluemix app is accessible but contains no data yet.

Step 4. Add data to the Mobile Data service

 
  1. Build your data into a JSON string and then save it to a text file, using an approach similar to the following:
    [{"id": 1, "firstName": "Robin", "lastName": "Shi", "title":"Vice President, North East", 
    "managerId": 0, "city":"New York, NY", "cellPhone":"212-999-8888", "officePhone":"212-999-8887", 
    "email":"ryan@ibm.com"},...]

    (The ID, FIRSTNAME, and LASTNAME attributes are required.)
  2. In the Bluemix dashboard, find and click the Mobile Data service: Screenshot of the Mobile Data service for the app
  3. In the service detail page, drag/click the text file to the dial: Screenshot of the drag/click dial
  4. In the Import Data dialog bog, enter Person in the Class Name field: Screenshot of the Imort Data dialog box
  5. Click Import to upload the data to the server side: Screenshot of the data classes list
  6. Drop your portrait images in the project_name/www/img folder of your Cordova project. Call each file Firstname_Lastname (matching what you have in the JSON object). For example, for the record shown in step 4.1, the image file name should be Robin_Shi.jpg.

Step 5. Run the application

 
  1. Start the application in the emulator. On startup, the application opens the index.html page, where the only items displayed are the app title and an empty text box: Screenshot of the app's initial index.html page
  2. Enter a contact's name or part of the name. The onkeyup is triggered and retrieves the name and job title for that contact from the cloud: Screenshot of the app after a contact is retrieved
  3. Select the contact, and the page slides to the contact's detail page:

    Screenshot of the retrieved contact's details page

If you installed the optional plugins in step 2.4, you could also add the person to your local contacts, change the portrait using the camera, or even locate yourself with GPS on this page.

Conclusion

 

Bluemix provides a simple and powerful solution for web-based or mobile applications. The open platform also involves many of the IBM products as a service, making Bluemix the Swiss Army knife of the IT realm.


RELATED TOPICS:AndroidCordova

Add a comment

Note: HTML elements are not supported within comments.


1000 characters left

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.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Mobile development, Cloud computing
ArticleID=979604
ArticleTitle=Build a hybrid mobile app with Cordova and the IBM Bluemix Mobile Data service
publish-date=08052014