nu.js" Simplified Technology Solutions, Inc - Social Business and Collaboration

SIMPLIFIED TECHNOLOGY SOLUTIONS, INC
Your Partner for Social Collaboration




Article
 

Web Services in BlackBerry J2ME Applications

by Edward Lineberry

12/30/2006

Introduction

The BlackBerry MDS Studio from Research in Motion provides a rich runtime and development environment for building applications and integrating web services on the BlackBerry. But the MDS environment may not be suitable for all situations. In this article, I'll show how to use web services in J2ME applications without the overhead of MDS Studio.

For an example application, I'll use a public web service from WebserviceX.NET that offers basic lnaguage translation functionality. Our input will be the language to translate from, the language to translate to, and the text to translate.

In order to focus on the details of web service implementation in J2ME, I'll skip over the basics of J2ME applications on the BlackBerry, which are covered in my first article, An Introduction to BlackBerry J2ME Applications, so please refer to that if you need a refresher.

Architecture

For this simple demonstration application, we will only create four classes: WebServiceDemo, WebServiceDemoScreen, ConnectionThread, and ResponseHandler. WebServiceDemo contains main. Just like in the DataCapture example of the first article, all it does is start up ConnectionThread and then load WebServiceDemoScreen. ResponseHandler is the SAX DefaultHandler that will parse the xml returned by our web service.

The user interface is pictured below. Two ObjectChoiceFields allow the user to select the languages, and a single input field captures the word to be translated. When the user activates the "Translate" button, an http GET connection is made to the web service, and the returned xml is parsed. In order to better illustrate the web service in action, we'll display both the raw xml, and the parsed result.

Connecting to the Web Service

In order to pass parameters to the web service, we need to pull the information from the user interface. The following code handles that task.



   private String getFieldData() {
        StringBuffer sb = new StringBuffer();
        sb.append("Translate?LanguageMode=");
        sb.append(fromLanguage.getChoice(fromLanguage.getSelectedIndex()));
        sb.append("TO");
        sb.append(toLanguage.getChoice(toLanguage.getSelectedIndex()));
        sb.append("&Text=");
        sb.append(input.getText());
        return sb.toString();
    }

The return value of that method is appended to our url string and passed to our active and waiting ConnectionThread object.


 connThread.get("http://www.webservicex.net/TranslateService.asmx/"

		  + getFieldData());

When the ConnectionThread completes the connection, the resulting xml string is displayed on screen and then parsed.


		 xmlResponse.setText( connThread.responseContent );
        parseResults( connThread.responseContent );

Here is the screen after the response has been received:

The parseResults method is responsible for displaying the single word translation taken from the xml. Again, in a real world environment, there would be no need to display the raw xml to the user. It's provided in this application in order to render the steps more transparent.

Xml Parsing

The BlackBerry API's make xml processing fairly trivial, and in the case of our simple web service, the xml returned is lends itself to an easy solution.


    private void parseResults( String xml ){
        SAXParserImpl saxparser = new SAXParserImpl();
        ResponseHandler handler = new ResponseHandler();
        ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
        try { 
            saxparser.parse( stream, handler );
        } catch ( Exception e ) {
            response.setText( "Unable to parse response.");
        }      
        response.setText( handler.response );
    }

In this method, a SAXParser is created and our DefaultHandler and String are passed into the parse method. The only catch is we have to turn our String object back into a InputStream. In most situations, the xml would never be stored as a String but parsed instead directly from the Stream.

Finally, let's take a look at the ResponseHandler class. As the parser moves through the xml, events are triggered in the ResponseHandler.


public class ResponseHandler extends DefaultHandler {
    
    public String response;
    
    private String element;
    
    public void startElement(String uri, String localName, 
		 String qName, Attributes attributes){
        		 element = localName;
    }
    
    public void characters(char[] ch, int start, int length) {
        if ( element.equals( "string" ) ){
            response = new String( ch, start, length );
        }
    }
    
} 

The startElement method is triggered at the beginning of each element in the xml. It's only purpose is to store the name of the current element in the instance valiable element. The characters method extracts the data from inside the tag and places that into the public response variable.

In the following xml example, the text "servizi" would be extracted into the response variable.



<?xml version="1.0" encoding="utf-8"?>

<string xmlns="http://www.webservicex.net">servizi</string>


Next Steps

In the example application, the input parameters for language are hard coded. If something in the web service changes, our application could break. Also, if new languages are added, our application will not be able to take advantage of that. The solution is to retrieve and parse the WSDL to extract this information. It's possible to build an entire dynamic user interface based on a web service's WSDL. For this demo application, the web sevice is trivial: two arguments in, one string returned. We can get by with a level of simplicity that would be impractical for most real world uses. More complex web services would require a more robust client application.

Resources


Simplified Technology Solutions Services

Learn how BlackBerry can empower you organization by contacting Lisa Duke at STS. Call 678 638 6688 today!



Recently Added

Notes on Linux? Read
Domino on VMware Whitepaper Read
Connections - It Just For Enterprise Any MoreRead

Recommendations