Thursday, April 5, 2012

Android Web Service Access Tutorial

Updated tutorial for new versions >> http://codeoncloud.blogspot.com/2013/06/android-java-soap-web-service-access.html

In this tutorial I'm going to demonstrate how we can access a java web service in Android application using ksoap2 library. This Android application also passes parameters to the web service.

First we have to create a web service & deploy it on Tomcat server.
Here is the sample code of java web service  I'm going to access.

package com.testprops.ws;

public class TestPropts {
 public String testMyProps(String fname,String lname){
  return "First Name : "+fname+" Last Name : "+lname;
 }
}

Android application will pass parameters for fname & lname variables.
To create web service refer my these tutorials.
1. Create java web service in Eclipse using Axis2 (Part 01) 
2. Create java web service in Eclipse using Axis2 (Part 02) 

Following is the code for the Android application which invoke the web service. You have to use ksoap2 (You can download ksoap2 from here:::http://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2) library for this implementation. Read my comments carefully

package com.sendproperties.ws;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;

import android.widget.TextView;

public class SendValuesActivity extends Activity {
    private final String NAMESPACE = "http://ws.testprops.com";
    private final String URL = "http://175.157.143.117:8085/TestProperties/services/TestPropts?wsdl";
    private final String SOAP_ACTION = "http://ws.testprops.com/testMyProps";
    private final String METHOD_NAME = "testMyProps";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
        
        String firstName = "Android";
        String lastName = "Program";
        
      //Pass value for fname variable of the web service
        PropertyInfo fnameProp =new PropertyInfo();
        fnameProp.setName("fname");//Define the variable name in the web service method
        fnameProp.setValue(firstName);//Define value for fname variable
        fnameProp.setType(String.class);//Define the type of the variable
        request.addProperty(fnameProp);//Pass properties to the variable
     
      //Pass value for lname variable of the web service
        PropertyInfo lnameProp =new PropertyInfo();
        lnameProp.setName("lname");
        lnameProp.setValue(lastName);
        lnameProp.setType(String.class);
        request.addProperty(lnameProp);
        
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        
        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
           
     
            TextView tv = new TextView(this);
            tv.setText(response.toString());
            setContentView(tv);
  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 }

You can find complete information about the implementation of Android application from these two posts.
1. Create java web service in Eclipse using Axis2 (Part 01) 
2. Create java web service in Eclipse using Axis2 (Part 02) 


Change these things in your Android program according to your web service

NAMESPACE
in line 15 is targetNamespace in the WSDL.

URL in line 16 The URL of WSDL file. In my case it is " http://175.157.143.117:8085/TestProperties/services/TestPropts?wsdl"
blue colored is the ip of the server replace it with your ip & red colored is the port number.

SOAP_ACTION in line 17 is "NAMESPACE/METHOD_NAME"

METHOD_NAME
in line 18 is WSDL operation. You can find something like <wsdl:operation name="............."> in your WSDL.



Make appropriate changes according to your WSDL. Open your WSDL using Firefox or Chrome. Then you can easily find those values from the WSDL.
We have to add internet permission to the Android Manifest. After adding permission your Manifest should like follows.



    
    
            
                

                
            
        
    



Here is the final result



You can download sample projects:
Click here to download web service project
Click here to download Android project

If you find this post helpful don't forget to leave a comment. your comments encourage me to write!

49 comments:

  1. that was realy help full ,thanks man..

    ReplyDelete
  2. I am using 2.2 version so i did not start a new thread. I some how fail to run a webservice though i gave the name space , method , url correct. I get this strangeorg.xmlpull.v1.XmlPullParserException: attr value delimiter missing! (position:START_TAG . Please help

    ReplyDelete
    Replies
    1. If you can mail your project. I'll check... my gmail id is priyankarahac
      I think it is better if you first try for this :::::http://javatutorialspoint.blogspot.com/2012/02/android-web-service-access-using-ksoap2.html

      Delete
    2. I solved this problem just removing "?wsdl" from URL.

      Delete
    3. kya jhant Code hai,Its Have sm problm
      The Source code never excute

      Delete
    4. How i should use flag counter in my drupal based web site..
      Like you used in this page..
      Please Revert me on gaurank24@yahoo.com

      Thanks In Advance

      Delete
    5. Plz tell me how i should flag counter on my drupal based web site
      my id is gaurank24@yahoo.com

      Thanks In Advance

      Delete
  3. how to send values to mysqldatabase using userinterface textbox in android.

    ReplyDelete
    Replies
    1. Check my new post http://codeoncloud.blogspot.com/2012/07/android-mysql-client-part-2.html

      Delete
  4. how to store valuse in mysql database using UserInterface TextBox in android(ksoap2)

    ReplyDelete
    Replies
    1. This post will help you
      http://codeoncloud.blogspot.com/2012/07/android-mysql-client-part-2.html

      Delete
  5. how to store values in MySql database using UserInterface TextBox in Android(ksoap2)

    ReplyDelete
    Replies
    1. Check this post http://codeoncloud.blogspot.com/2012/07/android-mysql-client-part-2.html

      Delete
  6. Hey I know this is off topic but I was wondering if
    you knew of any widgets I could add to my blog that automatically tweet my newest
    twitter updates. I've been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.
    Here is my web site :: Likejor

    ReplyDelete
  7. I absolutely love your blog and find most of your post's to be exactly what I'm looking for.
    Can you offer guest writers to write content
    for you personally? I wouldn't mind composing a post or elaborating on a few of the subjects you write in relation to here. Again, awesome site!
    My web-site : Gazebos For Sale

    ReplyDelete
  8. Your contents are more then sufficient for me.
    super one click root

    ReplyDelete
  9. For me nothing works, just like 99,9% of examples for android on internet...

    ReplyDelete
  10. Does not work for me.

    ReplyDelete
  11. I am very thankful to all your team for sharing such inspirational information.
    one click root software

    ReplyDelete
  12. I hv created webwervice usind CXF framework, wat shud i do to access the same webservice in android?

    ReplyDelete
  13. Hi guys, this tutorials also help using webservices android

    http://www.mobengineers.com/2012/11/xml-parsing.html

    ReplyDelete
  14. I have run ur project but some errors in org.ksoap2 import statement wt can I do for tat?

    ReplyDelete
    Replies
    1. Go to Project properties and select java build path of the imported project to the Eclipse work space, then select add external jars tab and remove already imported ksoap jar and re-import ksoap from your computer hard disk.

      Delete
    2. thanks for the help. Now in emulator unfortunately sendvalues has stopped error message coming what can I do now?
      thanks in advance...

      Delete
    3. i had the same error if you got a solution please tel me about it

      Delete
  15. Initially set the web service server.
    I run the test properties->Run on server>http://localhost:8081/TestProperties/
    was loaded in the Axis 2 home in that welcome message came.
    Then run the send values activity project as Android Application.
    In the emulator unfortunately sendvalue has stopped message coming what is the reason for that? please help me......

    ReplyDelete
  16. HI I WANT TO CAL WEBSERVICES IN MY LISTVIEW PROJECT ..FOLOWING IS THE CODE ..BUT WEN I RUN IT ..ITS CALLING WEBSERVICES BUT NOT IN THE RITE MANNER..HERE IS THE CODE PLEASE HELP ME..


    package fin.al;

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapPrimitive;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;



    public class FinalwebservicesActivity extends Activity {

    // private static final String NAMESPACE = "com.service.ServiceImpl";
    // private static final String URL =
    // "http://192.168.202.124:9000/AndroidWS/wsdl/ServiceImpl.wsdl";
    // private static final String SOAP_ACTION = "ServiceImpl";
    // private static final String METHOD_NAME = "message";
    private static String SOAP_ACTION = "http://tempuri.org/GetAllContinentals";
    // private static String SOAP_ACTION2 =
    // "http://tempuri.org/GetCountryByContinentals";
    private static String NAMESPACE = "http://tempuri.org/";
    private static String METHOD_NAME = "GetAllContinentals";
    // private static String METHOD_NAME2 = "GetCountryByContinentals";
    private static String URL = "http://38.99.250.24/trackmyvisit/AndroidService.asmx";
    static String ContitnentalsID, ContinentalsName;
    static String errorCode = "", errorDescription = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
    SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try {
    androidHttpTransport.call(SOAP_ACTION, envelope);
    SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

    TextView tv = new TextView(this);
    tv.setText(response.toString());
    setContentView(tv);

    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

    ReplyDelete
  17. hi sir,with the help of ur code i was able to connect and call web services ..but the way its showing is not coreect...please help me..i want the continents to come in a list view..


    package fin.al;

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapPrimitive;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;



    public class FinalwebservicesActivity extends Activity {

    // private static final String NAMESPACE = "com.service.ServiceImpl";
    // private static final String URL =
    // "http://192.168.202.124:9000/AndroidWS/wsdl/ServiceImpl.wsdl";
    // private static final String SOAP_ACTION = "ServiceImpl";
    // private static final String METHOD_NAME = "message";
    private static String SOAP_ACTION = "http://tempuri.org/GetAllContinentals";
    // private static String SOAP_ACTION2 =
    // "http://tempuri.org/GetCountryByContinentals";
    private static String NAMESPACE = "http://tempuri.org/";
    private static String METHOD_NAME = "GetAllContinentals";
    // private static String METHOD_NAME2 = "GetCountryByContinentals";
    private static String URL = "http://38.99.250.24/trackmyvisit/AndroidService.asmx";
    static String ContitnentalsID, ContinentalsName;
    static String errorCode = "", errorDescription = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
    SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try {
    androidHttpTransport.call(SOAP_ACTION, envelope);
    SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

    TextView tv = new TextView(this);
    tv.setText(response.toString());
    setContentView(tv);

    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

    ReplyDelete
  18. also on the click of any of the continents the following countries should come in listview..please help me..i have tried a lot..cz of lack of guidence i am not bale to perform..

    ReplyDelete
  19. Cvp reponse exacte pour cette application:
    comment en peut fait communication entre l'application Android et base des données avec q'uelle technologie ( avec http ou quoi d'autre...) en pluse lorsque telephonne ne contient pas connexion internet comment en peut fait la communication
    Rq:je préféré un aidée qui accumule tout le personne (avec telphone qui contient connexion ou nn ) cvp reponse exacte

    ReplyDelete
  20. Cvp reponse exacte pour cette application:
    comment en peut fait communication entre l'application Android et base des données avec q'uelle technologie ( avec http ou quoi d'autre...) en pluse lorsque telephonne ne contient pas connexion internet comment en peut fait la communication
    Rq:je préféré un aidée qui accumule tout le personne (avec telphone qui contient connexion ou nn ) cvp reponse exacte

    ReplyDelete
  21. How to download the lib file,in your source file,library is not there,

    ReplyDelete
    Replies
    1. You can download ksoap2 from here
      http://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2

      Delete
  22. In your source file,there is no lib file,how to get that libray file

    ReplyDelete
  23. Lib file.. yeah its there .. k soap..

    ReplyDelete
  24. Lib file.. yeah its there .. k soap..

    ReplyDelete
  25. I am facing an error:
    android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d09c70 that was originally bound here


    how to solve it.......

    ReplyDelete
  26. hi......here i am posting my code emulator is unable to connect to the webservice but my web service is working fine i checked with the client code.

    ReplyDelete
  27. hi....chathura,
    my emulator is unable to connect to the webservicce but my webservice is working fine.here i am posting my code..........
    package com.example.webapp;

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapPrimitive;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;

    import android.app.Activity;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;

    public class MainActivity extends Activity {
    private static final String SOAP_ACTION = "http://ws.android.org/sayHello";
    private static final String METHOD_NAME = "sayHello";
    private static final String NAMESPACE = "http://ws.android.org/";
    private static final String URL = "http://localhost:8080/android/services/Printmsg?wsdl";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.setThreadPolicy(policy);

    Button submit = (Button) findViewById(R.id.Submit);
    submit.setOnClickListener(new OnClickListener()
    {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    serviceAction();
    }



    });

    }
    private void serviceAction()
    {
    TextView result = null;
    Thread networkThread = new Thread() {
    @Override
    public void run() {
    try {
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);

    HttpTransportSE ht = new HttpTransportSE(URL);
    ht.call(SOAP_ACTION, envelope);
    final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
    final String str = response.toString();

    runOnUiThread (new Runnable(){
    public void run() {
    TextView result;
    result = (TextView)findViewById(R.id.textView1);//Text view id is textView1
    result.setText(str);
    }
    });
    }
    catch (Exception e) {
    e.printStackTrace();
    }
    }
    };
    networkThread.start();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

    }

    ReplyDelete
  28. Hi Chathura,
    I want to upload web service and database to Server run online,
    how can I do this ? Thanks...

    ReplyDelete
  29. I want to upload web service and database to Server run online,
    how can I do this ? Thanks...

    ReplyDelete
  30. Hai i want to get data from webserver database using my android application how to do it this action please help me...

    ReplyDelete
  31. Hi, Designing websites is the primary task which every web owner will be looking for Web Design Cochin into as their primary step to web success.Thanks...........

    ReplyDelete
  32. You did really job on your blog,i love your blog style,and how you make your point on this article ,cool.
    aviator sunglasses

    ReplyDelete
  33. Thanks for the nice and interesting Tut.

    Can you post another Tut for the SOAP which has the default authentication.

    Means in order to call a even method user has to pass the Credential.
    Thanks again.

    ReplyDelete
  34. Thanks for such a clear and helpful tutorial. I implemented a web service and accessed it successfully from an android application.But when i tried accessing another web service from the same android application, the following error occurs.

    [ERROR] The endpoint reference (EPR) for the Operation not found is http://10.0.2.2:8080/Plaza2/services/AvrPlazaImplementation and the WSA Action = http://plazaimplementation.Avrimplementation.org/saveFeedback. If this EPR was previously reachable, please contact the server administrator.

    I checked the url of wsdl in browser and it worked fine.
    Thanks in advance

    ReplyDelete
  35. Why I am getting failed to connect to /10.0.0.2 (PORT 8080) after 20000ms error.
    My web service is in my local host and I am running my android program on emulator.
    My program is bit different and it is passing two integers to add them at the server.

    ReplyDelete