Consuming REST service from PhoneGap/Cordova

In the Using JPA in REST web application deployed in Jetty entry i blogged about how to build a ManageContact JPA service which will allow me to perform CRUD operations on CONTACT table using a REST service. I wanted to figure out how i can consume this service from PhoneGap/Cordova application so i built this sample application which will call http://localhost:9000/ManageContact/rest/contact rest service, read the contact list returned in XML format, parse it and display contact list to the user, you can download the sample application from here This screen shot displays the list of contacts that i got from the REST service I followed these steps to build the CordovaManageContact application
  1. I followed the instructions in Getting Started with Android to build application that points to index.html inside the application, i tried it once to make sure that it works
  2. Then i changed the index.html file for my application to look like this
    <!DOCTYPE html>
    <title>Device Properties Example</title>
    <script type="text/javascript" charset="utf-8" 
    <script src="js/jquery.js"></script>
    <script type="text/javascript" charset="utf-8">
      function onDeviceReady() {
        console.log("Entering index.html.onDeviceReady");
        console.log("Exiting index.html.onDeviceReady");
      function getContactList(){ 
        console.log("Entering getContactList()");
          url : "",
          cache: false,
          error:function (xhr, ajaxOptions, thrownError){
          success : function(xml) {
            console.log("Entering getContactList.success()");
            $(xml).find("contact").each(function() {
              var html = '<li>' + $(this).find("firstName").text() 
              + ' ' + $(this).find("lastName").text() +'</li>';
            console.log("Exiting getContactList.success()");
        console.log("Exiting getContactList()");
      <h3>Contact List</h3>
      <button id="getContactBtn">Get Contact</button>
      <ul id="contactList"></ul>
    When i click on the Get Contact button the getContactList() method gets called, it uses the jquery $.ajax() method to make a call and once the result is returned, it uses logic in the success method to parse the xml and get all the contact records and adds each one of them as list item in the contactList list. I have the REST service running on my machine along with the Android emulator which has the PhoneGap application but when i tried to access the service at http://localhost/ManageContact/rest/contact, it did not work. I tried to map the ip address to in my host file but Android did not understand that mapping either. I had to use ipconfig command to figure out the ip address of the machine and then use it.

1 comment:

Anonymous said...

Hi Sunil,

Did you manage to run this code..???
If yes, please share your changes