Android Webservice example

In this post, we will be discussing how to invoke web service from Android application. When web methods are invoked from inside Android application, the application gets back the data from the server in the form of XML. The response which has been received can be parsed and rendered in the application as needed.

What is the importance of using Web Service in Android applications?

If you are looking for tutorial on consuming the web service which you created using Java or Dot Net, please follow below links:

How to call Java web service in android

How to call web service in android

We are gonna use SOAP protocol to send and retrieve information in order to invoke web methods.

What is SOAP?

SOAP is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks. It relies on Extensible Markup Language (XML) for its message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer Protocol (SMTP), for message negotiation and transmission.

What are we going to develop?

We are gonna develop a simple application to demonstrate how web service is invoked using SOAP protocol in Android application. Application we develop will just convert celcius to Fahrenhiet.

As this application requires Internet connectivity to hit Web Service hosted in remote server, it would be good if Internet connectivity check is done before trying to hit Web Service.


Here are the tutorials which talk about checking Wifi/Mobile Internet:

Android Check Wi-Fi Internet Connection
Android Check Mobile Internet Connection

Quick Links

Project Structure

Layout creation:

  • Create new android project [File >> New >> Android Project] with project name WebserviceActivity
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name – ‘’
  • Click finish

Code Listings

Layout XML:

Open main.xml present under /res/layout folder and replace the XML with the below one.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:text="Celsius to Farenheit"
        android:textSize="30dp" />

        android:singleLine="true" />

        android:text="Convert to Farenheit" />

        android:text="" android:textSize="26dp"/>


Application layout will look like:

Change to graphical layout of Main.xml, the layout design should look like below:

KSOAP client library is being used in Android to make WebService calls. You can download KSOAP library from here and add it in lib folder of Android project

Create following objects under WebserviceActivity class:

	private final String NAMESPACE = "";
	private final String URL = "";
	private final String SOAP_ACTION = "";
	private final String METHOD_NAME = "CelsiusToFahrenheit";
	private String TAG = "PGGURU";
	private static String celcius;
	private static String fahren;
	Button b;
	TextView tv;
	EditText et;

Add following code snippet in the place of onCreate method.

	public void onCreate(Bundle savedInstanceState) {
		//Celcius Edit Control
		et = (EditText) findViewById(;
		//Fahrenheit Text control
		tv = (TextView) findViewById(;
		//Button to trigger web service invocation
		b = (Button) findViewById(;
		//Button Click Listener
		b.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//Check if Celcius text control is not empty
				if (et.getText().length() != 0 && et.getText().toString() != "") {
					//Get the text control value
					celcius = et.getText().toString();
					//Create instance for AsyncCallWS
					AsyncCallWS task = new AsyncCallWS();
					//Call execute 
				//If text control is empty
				} else {
					tv.setText("Please enter Celcius");

Class AsyncCallWS:
Create it as inner class inside WebserviceActivity class.
This class will perform the webservice call which will be executed as separate thread. When execute method is called in onCreate method, it calls the following methods in order:

  1. onPreExecute() – Fahrenheit textview control is set with text ‘Calculation…’
  2. doInBackground() – Invoke getFahrenheit()
  3. onProgressUpdate() -Does nothing
  4. onPostExecute() – Set the Fahrenheit value in textview control
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
		protected Void doInBackground(String... params) {
			Log.i(TAG, "doInBackground");
			return null;

		protected void onPostExecute(Void result) {
			Log.i(TAG, "onPostExecute");
			tv.setText(fahren + "° F");

		protected void onPreExecute() {
			Log.i(TAG, "onPreExecute");

		protected void onProgressUpdate(Void... values) {
			Log.i(TAG, "onProgressUpdate");


Click here to know more about AsyncTask,

Create this method inside WebserviceActivity class.
Method which involves web service invocation:

	public void getFahrenheit(String celsius) {
		//Create request
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		//Property which holds input parameters
		PropertyInfo celsiusPI = new PropertyInfo();
		//Set Name
		//Set Value
		//Set dataType
		//Add the property to request object
		//Create envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
		envelope.dotNet = true;
		//Set output SOAP object
		//Create HTTP call object
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

		try {
			//Invole web service, envelope);
			//Get the response
			SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
			//Assign it to fahren static variable
			fahren = response.toString();

		} catch (Exception e) {

Internet permission
Don’t forget to add internet permission in AndroidManifest.xml:

 <uses-permission android:name="android.permission.INTERNET" />



Let us test the application:
Run click on the project >> Run as >> Android application
You could see following screens:

Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.


I hope you enjoyed the post!! 🙂

Related Articles

Author: Udhay

Share This Post On
468 ad
  • Ragesh


  • Diego De Marco

    In case you’re interested, I’ve just created an online tool to allow WSDLs to be parsed and generate the appropiate Android source code to consume its web services. It basically creates a proxy class, as well as all necessary data types (classes, enums, etc.) required for the job. It needs no externali libraries or anything. You can access it at

    Any comments and/or feedback on the tool are of course welcome.

  • Conan

    Thank you for this glorious tutorial

  • NetStarter

    Thanks for simple easy and best tutorial for using Asynch task,it helped me i appreciate it

  • eman

    when i click on button i don’t have any response !

    • It is working fine in mobile device. Please enable internet in your mobile device and do check.

      • eman

        i used it in mobile device but without any response and i’m sure i have internet

        • It’s working fine for others too. Please debug the code, you can find the issue.

  • Fabrizio

    Great tutorial, but i can’t download the source code because the “register” link doesn’t work!

  • Kunal

    I am not able to register to download the src/apk

  • Nilendra

    yes this was very easy to understand and goodone!

  • Peter

    I haven’t received the confirmation link to register.

    • You must have received confirmation link already. Please check.

  • Peter

    I’m getting error:
    FATAL EXCEPTION: AsyncTask #1
    java.lang.RuntimeException: An error occured while executing doInBackground()

    Any thoughs what can be causing this?

    • Mohd Ikram

      I’ve the same problem plz help some one….. 🙁

    • Sachin Ambalkar

      Try following steps :
      Go to Properties -> Java Build Path

      Add ksoap2-android-assembly-2.6.2-jar-with-dependencies.jar as external jar

      Go to the Order and Export tab on the same popup window

      Check the box against the newly added jar

      • Sheikh

        I am getting same error. I tried this one , but did’t went through. ???

        • Can you check whether the webservice you created in local is up and running?

          Do post the log here so that will analyze.

  • Vijay

    Nice Tutorial! 🙂

  • Vijay

    Nice Tutorial! 😀

  • Vijay

    Nice Tutorial!

  • Sharan

    Good tutorial Android Guru!!!! Cheers

    I have registered to obtain the source code. But the activation link is not yet sent to my mail id.Please help me with this

    • Your account has been activated! Please login with your email ID.

  • Jack

    Great tutorial. I’m looking for the example of how to get data (kept in xml format) from a remote site using android application.

    I saw some stuff over the web, but not working.

  • Sandip Borad

    very nice tutorial. I have lots of understanding and clear all doubt about web services. Thank you .

  • Ahmed

    I have downloaded the apk and run it but it gives me the result like this “null F? “

    • Please check whether you enabled internet in your mobile as application involves http calls which happens over internet.

  • Rahul

    superb…I appreciate your work

  • baer

    everything nice, but it just won’t work.

    Like Ahmed, SEPTEMBER 24, 2013, I only get “Null F” back. And this comes due an exception in line 27 (of your code above) in the getFahrenheit method:
    SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

    Code lands in catch block and the Exception (SoapFault) shows:
    SoapFault - faultcode: 'soap:Client' faultstring: 'Server did not recognize the value of HTTP Header SOAPAction:' faultactor: 'null' detail: org.kxml2.kdom.Node@4054e640

    What could I do??
    Please answer me on my email address, I would appreciate it very much! Nice Tutorial, keep up the good work!


    • baer

      No moderator anymore here, is it? Too bad 🙁

      • Hey I was bit held up with my office work so couldn’t find solution for this issue. Spent some time today and resolved the issue.
        Take a look at updated post!

    • is no more accepting NAMESPACE as ‘’ which caused SOAP exception in our code. I verfied the NAMESPACE and SOAP_ACTION url in and we need to use ‘’ in place of ‘’ in our code.

      I updated the post and code as well, download latest code to take a look at the changes I did.

      Thanks for letting me know!

      • baer

        This did the trick 🙂
        Thank you!

  • lemorlenny

    Nice tutorial, the apk work nicely but the source have the ‘classic’ unresolved R. error. You know how to fix it?.


  • lemorlenny

    Nice tutorial, the apk work nicely but the source crash on
    “SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);”

    know how to fix it?.


    • lemorlenny

      I Moved the ksoap2 lib in the /libs folder and its work!.


  • Shawn

    Nice job man! Really help a lot!

  • Arvind Kumar

    Thanks alot of this wonderful tutorial.

    I was able to connect my Samsung android tablet 4.1.2 client to W3Schools webservice.

    But when i replace W3Schools WebService with custom one hosted on my localhost I get NULL return for CelsiusToFahrenheit.

    I am using ADT eclipse for Android project

    and Visual Studio 2012 for my webservice in C#

    I changed the file as below
    private final String NAMESPACE = “”;
    private final String URL = “http://localhost:20902/service.asmx”;
    private final String SOAP_ACTION = “”;
    private final String METHOD_NAME = “CelsiusToFahrenheit”;

    And my WebService code for Service.cs
    using System;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;

    [WebService(Namespace = “”)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Service : System.Web.Services.WebService
    public Service () {

    //Uncomment the following line if using designed components

    public string HelloWorld() {
    return “Hello World”;

    public string FahrenheitToCelsius(string Fahrenheit)
    object fahr = null;
    fahr = Fahrenheit.Replace(“,”, “.”).Trim(‘ ‘);
    if (fahr == “”)
    return “Error”;
    int returnVal = ((((Convert.ToInt32(fahr)) – 32) / 9) * 5);
    return returnVal.ToString();

    public string CelsiusToFahrenheit(string Celsius)
    object cel = null;
    cel = Celsius.Replace(“,”, “.”).Trim(‘ ‘);
    if (cel == “”)
    return “Error”;
    int returnVal = ((((Convert.ToInt32(cel)) * 9) / 5) + 32);
    return returnVal.ToString();

    AND service.asmx

  • Vrajesh Sukhadiya

    Thank you for post its really helpful for Beginner for web service….

  • Nirmal Garg

    Hi. Nice tutorial.
    I have a question here, if i download this file and install it in my android phone, will it work?

  • Ridz

    Hello thank you for the code. But it is not giving me the value. instead it gives me error. what could be wrong? I am screwed here with the webservices. Need help. plz reply soon

    • Hi
      Try once after you enable internet.But it works perfectly in my device. Please see the attached screenprint.

      • Loki Vuitton

        Hello Guru, I have same error. It not giving a value (return “error…”) I installed in my real device, and it not working

    • Hi
      Try once after you enable internet.But it works perfectly in my device. Please see the attached screenprint.

      • Loki Vuitton

        Hello Guru, I have same error. It not giving a value (return “error…”) I installed in my real device, and it not working

  • kláda

    thanks, work.
    But this line is needed > envelope.dotNet = true;
    Without it i get error. But how i know if service is in dotNET or JAVA ?
    When i try JAVA server i dont use envelope.Java = true; because it doesnt exist.

    Is SoapSerializationEnvelope envelope pre-programmed for Java? 🙂 thx for answer

  • Hendrik Steinhorst

    thank you, works great!

  • DrTJ

    Thanks so much!

  • Prince Gohel

    Thank You …Great EXAMPLE ! love this

  • Sergio Pereyra Ortega

    Nice example but i want to know something about the webservice that webservice has its own webservice client or you create it in android studio

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest