08- SOA for Mobiles

Introduction

Service Oriented Architecture (SOA) is very relevant in the mobile environment. As mobiles have limited storage capacity, most of the data is stored off the device on some servers and mobile apps contact the server to access the required data. Later, the app might process the data locally on the mobile device (if it is not already processed on the server) and then display it to the viewer in the required format. This is made possible through web services. You can create web services in the language you are comfortable with. For example, you can create web services in PHP, .Net or any other server side language. Explaining how to create a web service is out of the scope of this tutorial. Here, we will see how to contact a PHP web service from the mobile app and get the required data.

Create a Web Service that Calculates Body Mass Index (BMI)

Let me first create a PHP web service that returns the BMI once the height and width is provided. The following lines of code calculate the Body Mass Index.

<?php
    $h = $_REQUEST['height'];
    $height = (float) $h;
    $w = $_REQUEST['weight'];
    $weight = (float) $w;
    $hinms = $height/100;    
    $bmi = $weight/($hinms*$hinms);
        echo("Your Body Mass Index (BMI) is: ");
    echo round($bmi,2);        
??

Open your favourite text editor, copy the above lines of code into a new file and save the file as bmi.php. In real life scenario, the web service will be hosted on a server where the address could be http://myservices.com/bmi.php (the web address, that is myservices.com, could be different based on where the service is residing). For the time being, we will access the web service from our local server. If you have IIS (Internet Information Services) installed on your machine, then save this file into intetpub/www folder. If you have Apache Web Server installed on your machine, then save this file into xampp/htdocs folder. Get the IP address of your machine and if your IP address is 192.188.68.12 (just assume), then we will access the bmi.php web service as http://192.188.68.12/bmi.php. We also need to pass the height and width to this web service. We are going to use HTTP GET method and hence we will pass the values as query string along with the URL. Suppose val1 is the height and val2 is the weight (we will replace val1 and val2 with values entered by the user), then the URL will be http://192.188.68.12/bmi.php?height=val1&weight=val2. We are now going to see how to access this URL from our mobile app.

Create an App that Contacts the Server and Gets the BMI

Let’s create a mobile app for Android platform this time. Create a project named AndroidSOA on the desktop (I am not repeating the steps to create the project as you might already be comfortable with the process.)

Once the project is created on the desktop, bring the project into the Android Development Environment (Eclipse). Open the index.html file in the assets/www folder using your text editor and clean it up. You can also change the title to make it more relevant.

Next we need to have two textboxes for the user to enter his height and weight (that are the inputs of our web service). We also need a button on the click of which we will contact the server and get the BMI. So, add the following lines of code inside the <body> section of index.html file.

Add the following line inside the <body> tag.

Your Height (in centimeters):<input type="number" id="height" min="0" max="300" /><br />
        Your Weight (in kilograms):<input type="number" id="weight" min="0" max="250" /><br />
        <input type="button" id="btnBMI" value="BMI" />

Add the following lines of code inside the <head> section to check whether the device is ready. Once the device is ready, we will add the event listener to the button for its click event.

<script>
    window.onload = function()
     {
        document.addEventListener("deviceready", init, false);
     }
     function init()
     {
        document.getElementById("btnBMI").addEventListener('click', sendData, false);    
     }
</script>

Now we need to write the sendData function. Our aim is to contact the web service within the server (in our case, within the local server) from our app. We will be using a technique called AJAX (Asynchronous JavaScript and XML) to contact the web service and get the output. Many of you might have already used AJAX to contact the server asynchronously. In AJAX, we will create an XMLHttpRequest object and send the request to the server asynchronously using send method.

So, first declare an object named xmlhttp to store the XMLHttpRequest object. We have to declare this variable globally as we have to access this object from different functions. So, add the following line of code, just below the opening <script> tag.

var xmlhttp;

Next inside the sendData function, add the following line of code to create the XMLHttpRequest object.

xmlhttp = new XMLHttpRequest();

Next, we will create a call back function to get invoked when the output comes back from the server. Why are we creating a call back function? It is obvious that our app will take some time to contact the server and receive the output back from the server. So, we have to wait for the response. The XMLHttpRequest object has a property named onreadystatechange which will trigger whenever the state of the object changes. The readyState property of the XMLHttpRequest object has 5 values indicating different states. The following are the different readyState values.

readyState value State of the Object

0 Request not initialized

1 Server connection established

2 Request received

3 Processing request

4 Request finished and response is ready

The onreadystatechange will trigger whenever the value of readyState property changes. In other words, it will trigger not only when the value becomes 4, but also when the value becomes 1, 2, 3 or 4. So, within the call back function, we will check whether the value of readyState becomes 4. If the value of readyState is 4, then it means that the output from the server is ready and we can collect the output. It is also a good practice to ensure that the status of the XMLHttpRequest object is 200. The status is 200 indicates OK and the status 404 means the page is not found.

To create a callback function named processOutput, add the following line of code inside the sendData function.

xmlhttp.onreadystatechange = processOutput;

We also need to establish a connection with the server using open method. The first parameter of this method is the protocol using which we establish the connection. The values can be either GET or POST. The second parameter is the URL to which we need to establish the connection and the third parameter is whether or not we want to happen this asynchronously. If you want this to happen asynchronously, then the value should be true and otherwise false. Add the following lines of code inside the sendData method.

var ht = document.getElementById("height").value;
var wt = document.getElementById("weight").value;
url = "http://192.188.68.12/bmi.php?height=" + ht + "&weight=" + wt;
xmlhttp.open("GET", url, false);
xmlhttp.send();

Here it is assumed that IP address of your machine is http:// 192.188.68.12. You should replace this value with your actual IP address. We collect the height and weight values entered by the user into ht and wt variables respectively. We have appended the ht and wt values using + sign to make the URL in the correct format (the format is http://address.com/service.php?parameter1=value1&parameter2=value2).

Next we need to write the processOutput function. As explained before, we should check whether the readyState value is 4 and status value is 200. If both the conditions are true, then we can collect the output from the responseText property. Now we need some place to display the output. First, add the following line of code after the code for button inside the <body section>.

<div id="result"></div>

Write the processOutput fuction after the sendData function inside the <script> section.

 

function processOutput()
{
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
      {
             document.getElementById("result").innerHTML = xmlhttp.responseText;
      }
}

The innerHTML property is used to set value to an element. Now your index.html will look like this:

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <title>SOA</title>
        <script type="text/javascript" src="cordova.js"></script>
        <script>
            var xmlhttp;
            window.onload = function()
            {
                document.addEventListener('deviceready', init, false);
            }
            function init()
            {
                document.getElementById("btnBMI").addEventListener('click', sendData, false);
                xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange = processOutput;
            }
            function sendData()
            {
                var ht = document.getElementById("height").value;
                var wt = document.getElementById("weight").value;
                url = "http:// 192.188.68.12/bmi.php?height=" + ht + "&weight=" + wt;
                xmlhttp.open("GET", url, false);
                xmlhttp.send();
            }
            function processOutput()
            {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                {
                    document.getElementById("result").innerHTML = xmlhttp.responseText;
                }
            }
        </script>
    </head>
    <body>
        Your Height (in centimeters):<input type="number" id="height" min="0" max="300" /><br />
        Your Weight (in kilograms):<input type="number" id="weight" min="0" max="250" /><br />
        <input type="button" id="btnBMI" value="BMI" />
        <div id="result"></div>
    </body>
</html>

Save your index.html file and run your project from Android Development Environment. Once you open the application, you will get a screen like this:

out1.png

Enter your height and weight (make sure that you enter only numbers. Otherwise, it will give error as we have not validated the inputs). Your screen might now look like this (values could be different).

out2.png

Click the BMI button and you will get a screen like this:

out3.png

Summary

In this tutorial, we have created an app that connects to a server using AJAX and displays the output. This web service returned the result as text and hence we used responseText property of the XMLHttpRequest object. Likewise, we can get XML data from the server using responseXML property and JSON data using responseText property itself.

 

Like us on Facebook