Thursday, March 31, 2011

Android meets EJB server

In this post I’ll try to explain how to communicate between an Android client and an EJB-service-based server.
The application I’m working on is a simple whiteboard, which allows a group of users to draw basic shapes on a canvas.

My mission today is enabling my client to read a simple string from the server. In the next post I’ll explain how to pass serialized objects.



For application server I’m using JBoss. IDE: IntelliJ 10.
In the server I wrote a simple “Hello World” EJB:
1: import javax.ejb.Stateless;
2: import javax.jws.WebMethod;
3: import javax.jws.WebService;
4: 
5: @WebService(targetNamespace = "HelloWorld")
6: @Stateless(name = "HelloWorldEJB")
7: public class HelloWorldBean
8: {
9:     @WebMethod
10:     public String sayHello()
11:     {
12:         return "Saying hello from EJB!";
13:     }
14: }

Notice that I could omit targetNamespace, if I put my EJB in a package.

I exposed the EJB as Web Service using Apache Axis platform. (Right click menu – WebServices):

ללא שם

In http://localhost:8080/jbossws/services I could see the details of my exposed service. Click on Endpoint Address takes me to the service’s WSDL.

In my Android client I added to the end of AndroidManifest.xml the following line after the application tag:
1: <uses-permission android:name="android.permission.INTERNET"></uses-permission>

In the activity I added the following code, simply handling the Web Service call:
1: private static final String SOAP_ACTION = "sayHello";
2: private static final String METHOD_NAME = "sayHello";
3: private static final String NAMESPACE = "HelloWorld";
4: private static final String URL = "http://10.0.2.2:8080/EJBproject_ejb_exploded/HelloWorldBean";
5: 
6: public myServiceCall()
7: {
8:     try
9:     {
10:         SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);    
11:         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
12:         envelope.setOutputSoapObject(request);
13:         HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
14:         androidHttpTransport.call(SOAP_ACTION, envelope);
15:         resultText = envelope.getResponse().toString();
16:     } 
17:     catch(Exception e) 
18:     {
19:         e.printStackTrace();
20:     }
21: }

Notice that I used 10.0.2.2 as server name for my localhost.

As explained here, the Android emulator sets up its own virtual network in which the special address 10.0.2.2 refers to the loopback adapter on your development machine. Consequently, if the server is running on your PC, then you'll want to use 10.0.2.2 as the target host address in your client.



So this is a very simple android client-server example, next time it’ll get more interesting.. (;

No comments:

Post a Comment