Part 2 : Calling a webservice from Android Application

——————————————————————————————————

Part 2: Calling webservice from Android App

——————————————————————————————————

Refer part 1: For Creating a WSDL service

  • Create a new android project in eclipse.

  • Select Finish.
  • We need to display 4 calculations in android application. UI is on fron end, but calculation is done in backend with the help of Web service. (Explained in part 1).
  • So we will create 4 text Inputs in main.xml

  • Finally main.xml should contain four text fields for four different calculations
  • <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:id="@+id/txtAddition" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="@string/hello" />
    <TextView android:id="@+id/txtSubraction" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="@string/hello" />
    <TextView android:id="@+id/txtMultiplication" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="@string/hello" />
    <TextView android:id="@+id/txtDivision" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="@string/hello" />
    </LinearLayout>
  • We need Ksoap Library File for android project, which can downloaded from this link.
  • Since we are trying to access the data stored on server which is equivalent to android app accessing an internet, so we have to allow our android application to access the internet.
  • we have to include “<uses-permission android:name=”android.permission.INTERNET” />” inside AndroidManifest.xml.
  • We have to include the above tag inside the tag manifest but outside the tag application.
  • Next point includes the complete Code for adding two numbers. With minute changes we can also work with multiplication, subraction and division.
  • ————————————————————————————————–
  • package org.web.frontend.calculator;
    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    public class AndroidWSDLFrontEnd extends Activity {

    private String METHOD_NAME = “sum”; // our webservice method name
    private String NAMESPACE = “http://calculator.backend.web.org&#8221;; // Here package name in webservice with reverse order.
    private String SOAP_ACTION = NAMESPACE + METHOD_NAME; // NAMESPACE + method name
    private static final String URL = “http://192.168.0.103:8080/AndroidBackend/services/Calculate?wsdl&#8221;; // you must use ipaddress here, don’t use Hostname or localhost

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView tv = (TextView) findViewById(R.id.txtAddition);
    try
    {
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty(“i”, 5);
    request.addProperty(“j”, 15);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    androidHttpTransport.call(SOAP_ACTION,envelope);
    Object result = envelope.getResponse();
    System.out.println(“Result : ” + result.toString());
    ((TextView) findViewById (R.id.txtAddition)).setText(“Addition : “+result.toString());
    } catch (Exception E) {
    E.printStackTrace();
    ((TextView) findViewById (R.id.txtAddition)).setText(“ERROR:”    + E.getClass().getName() + “:” + E.getMessage());
    }
    }
    }

  • ————————————————————————————————–
  • Imp Points to note down before You go through this code
  1. NAMESPACE = “http://calculator.backend.web.org&#8221;; We refer this name from the actual web project on backend. The name of package on backend on serverside was org.web.backend.calculator. So we need to write the reverse order of package name.
  2. URL = “http://192.168.0.103:8080/AndroidBackend/services/Calculate?wsdl&#8221;; Here Your comp Ip addr is required. Localhost wont work.
  3. Thats it, you can run the following application. Before running the app, make sure your server is running on Backend. And you will get the following screen on Emulator.

    • For multiplication, Change  METHOD_NAME = “multiply”; Simillarly “divide or subtract ” for desired operations.
    • We get 3 printout statements of “Hello World , AndroidWSDLFrontEnd” because 1 text input holds for addition, 2 text input for Subtraction, 3 text input for Multiplication, 4 text input for Division as discussed in main.xml
    • So for METHOD_NAME = “sum”; we have allocated (R.id.txtAddition);
    • Simillarly we can go for different desired operations.
  • Thats it. We have sucessfully called the wsdl file on server Side.
  • If You have any problems with the above blog, plz feel free to contact me at depo.jatin@gmail.com
  • Reference
  1. http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
  2. http://www.eclipse.org/webtools/community/tutorials/BottomUpAxis2WebService/bu_tutorial.html
  3. http://androidcommunity.com/forums/340658-post6.html

————————————————–

Jatinkumar DN Patel – Thinking High To RISE.

————————————————–

package org.web.frontend.calculator;import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidWSDLFrontEnd extends Activity {

private String METHOD_NAME = “sum”; // our webservice method name
private String NAMESPACE = “http://calculator.backend.web.org&#8221;; // Here package name in webservice with reverse order.
private String SOAP_ACTION = NAMESPACE + METHOD_NAME; // NAMESPACE + method name
private static final String URL = “http://192.168.0.103:8080/AndroidBackend/services/Calculate?wsdl&#8221;; // you must use ipaddress here, don’t use Hostname or localhost

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView tv = (TextView) findViewById(R.id.txtAddition);
try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty(“i”, 5);
request.addProperty(“j”, 15);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION,envelope);
Object result = envelope.getResponse();
System.out.println(“Result : ” + result.toString());
((TextView) findViewById (R.id.txtAddition)).setText(“Addition : “+result.toString());
} catch (Exception E) {
E.printStackTrace();
((TextView) findViewById (R.id.txtAddition)).setText(“ERROR:”    + E.getClass().getName() + “:” + E.getMessage());
}
}
}

46 thoughts on “Part 2 : Calling a webservice from Android Application

  1. could you please guide me one thing?

    i dont see request timeout here?

    so how ksoap2 manages request time out
    actually i need it if i am moving on car and INTERNET service connects and disconnects repeatedly

    so in order to avoid that situation what should i do ?
    any help would be appreciated.

    • int retry = 3;
      int count = 0;
      while (count < retry) {
      count += 1;
      try {
      make http call and check whether you are getting the result back
      } catch (Exception e) {
      if (count < retry) {
      try again, since we are inside while loop.
      } else {
      throw error message;
      }
      }
      }

  2. Hello, I tried to run your example in Android. My activity starts but I can only see black screen. I can’t realize what is the problem. I have to finish my Android application until Monday in which I connect to MySQL Database and query the existing data from it but I can’t run the examples found on the internet. Can you please, please help me? I am a little desperate… Thank you very much.

  3. Your blog was awesome… it clearly mentioned all the links and settings required for starting a web-service and using from Android App.
    To make your blog perfect- point mentined above”We need Ksoap Library File for android project…”
    1. this library must be downloaded and put under the eclipse->plugins folder.
    2. Then under the project properties, it should be added using “Add External JARs” option.

    Thanks again for the help.

  4. thank you for these informations it is so useful.

    but I got this Error :
    ERROR:org.ksoap2.SoapFault:null

    Can you Help me?

    Thanks

  5. i keep having ERROR.java.net.SocketException:The operation timed out

    it does work on the emulator but when i tried to run on my smart phone i keep getting this error, can you help me please???

    • I am sorry. I havent tries this on smartphone. But if i was at your place, i would have created a text view which would have displayed error from logcat. Are you getting , what i am trying to say ?

  6. Hey i want to do the following in android
    1) create two edittext fields and a submit button
    2) user enters the data and clicks submit…den web service should be called and data should be stored in database
    3) also if the user wants to see that data stored in database he can again use web service to retreive data and show it on phone in ListView
    How to do this ? Which software or tools to be used ? what changes regarding coding have to be done as per ur code is concerned

  7. Hello sir i m new in android developement. i m follow ur tutorial but it does not work.
    it shows force to close dialog and when i debug my application it shows Runtime Exception and NoClassFoundException. what i did wrong.plz tell me solution.Hope you will reply me .plz help.

    • Krishnaveni,
      Thanks for compliments.
      As far as your issues, what i can think of is
      1. Create a method on server side which can access db. For e.g. (You can refer my blog where i have created methods in class Calculate.java)
      2. Make sure that method is accessible via webservice with proper return type.
      3. Call that method from android.

      Hope it helps.

  8. Hello
    thinks for the tutoriel its really very good , I have the same result as you
    But I have a problem when I run the android project , this is my error message :
    the application AndroidWSDLFrontEnd (process org.web.frontend.calculator)has stopped unexepectedly. please try again

    pleassssssssssssssssssee help me

  9. hi.
    i liked your post..but i have problem implementing it..iam trying to send a base64 string(binary data) to webservice in c# and getting soapfault=null,server is receiving null evrytime….whereas iam successfull in transfering a normal string value…expt the base64 string…..can u tell me why is its so…iam struggling on this since long..please help.

    • what i can think of is serialization between two different platforms. The example which i am potraying in my blog depicts serilization between java on backend and java (android) on front end. In your case its C# on frontend. You need to look into some serilization technique, complex data type transfer etc. Hope my answer helps.

  10. Thanks a lot for the great tutorial!
    Everything worked fine until starting the Android Virtual Device Manager. After it took some time to load the AVD, I only got the message “Unfortunately, AndroidWSDLFrontEnd has stopped.”
    Has anyone encountered this problem as well?
    The AVD’s platform is 4.0.3 and the API Level 15 – as suggested in the manifest. Besides the system runs on Axis2-1.6., Tomcat 6.0.35 and JDK 1.7.0.
    Any help would be very much appreciated!

      • Yes, I am going to try that.
        Btw, the Axis version you are linking to on the first page is no longer available on Apache’s servers!?

      • And another thing: You initializing “Textview tv” but never use it. Or do I oversee something here?
        I get the feeling that the Java/Axis versions are not the cause of my problem though :(

  11. Hello AndroidKill,
    As you experienced, I also got the same error message as the application AndroidWSDLFrontEnd (process org.web.frontend.calculator)has stopped unexepectedly. please try again

    In the sebsequent post, you said it is resolved. could you please provide you fix to solve this? I am new to android development….

    @Jatin: Thank You very much for this article. If you have any idea, please suggest me

  12. we are getting always this exception what do i do

    08-28 14:43:04.031: E/AndroidRuntime(5386): java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject

  13. hello
    thank you for this work
    i need your help queecly
    i am developing web service to manage the bank
    i have tried to call when method of this service by android
    but i have a problem when I clicked on button “unfortunately web service has stopped ”
    I can’t localized the error please help
    contact me in mail

  14. hello friend
    thx for the exemple , But I have a problem when I run the android project , this is my error message :
    the application AndroidWSDLFrontEnd (process org.web.frontend.calculator)has stopped unexepectedly
    i dont know what’s the prob :( ??

  15. Greetings! This is my 1st comment here so I just wanted
    to give a quick shout out and say I genuinely enjoy reading your blog
    posts. Can you suggest any other blogs/websites/forums that deal with the same subjects?
    Thanks for your time!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s