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.

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 asp.net 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.

Subscribe and download free ebook
Email:

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 – ‘com.prgguru.android’
  • 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="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="Celsius to Farenheit"
        android:textSize="30dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:numeric="integer"
        android:singleLine="true" />

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:text="Convert to Farenheit" />

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="" android:textSize="26dp"/>

</LinearLayout>

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 = "http://www.w3schools.com/webservices/";
	private final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
	private final String SOAP_ACTION = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
	private final String METHOD_NAME = "CelsiusToFahrenheit";
	private String TAG = "PGGURU";
	private static String celcius;
	private static String fahren;
	Button b;
	TextView tv;
	EditText et;

onCreate():
Add following code snippet in the place of onCreate method.

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//Celcius Edit Control
		et = (EditText) findViewById(R.id.editText1);
		//Fahrenheit Text control
		tv = (TextView) findViewById(R.id.tv_result);
		//Button to trigger web service invocation
		b = (Button) findViewById(R.id.button1);
		//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 
					task.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> {
		@Override
		protected Void doInBackground(String... params) {
			Log.i(TAG, "doInBackground");
			getFahrenheit(celcius);
			return null;
		}

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

		@Override
		protected void onPreExecute() {
			Log.i(TAG, "onPreExecute");
			tv.setText("Calculating...");
		}

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

	}

Click here to know more about AsyncTask,

getFahrenheit()
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
		celsiusPI.setName("Celsius");
		//Set Value
		celsiusPI.setValue(celsius);
		//Set dataType
		celsiusPI.setType(double.class);
		//Add the property to request object
		request.addProperty(celsiusPI);
		//Create envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;
		//Set output SOAP object
		envelope.setOutputSoapObject(request);
		//Create HTTP call object
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

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

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

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

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

Demo

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!! :)

Feedback

If you like this post, please do click 'Appreciate Badge'

*You can "Appreciate" this post only once from this IP


Do you want to add your own tutorials here and make money out of it?

Here is the great opportunity. Check out this link.

Author: Android Guru

Share This Post On
  • 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 MainActivity.java file as below
    ——————————————————-
    private final String NAMESPACE = “http://tempuri.org/”;
    private final String URL = “http://localhost:20902/service.asmx”;
    private final String SOAP_ACTION = “http://tempuri.org/CelsiusToFahrenheit”;
    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 = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Service : System.Web.Services.WebService
    {
    public Service () {

    //Uncomment the following line if using designed components
    //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
    return “Hello World”;
    }

    [WebMethod]
    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();
    }

    [WebMethod]
    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
    ————————–

  • Shawn

    Nice job man! Really help a lot!

  • lemorlenny

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

    know how to fix it?.

    Regards.

    • lemorlenny

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

      Regards.

      • http://android.programmerguru.com Android Guru

        Cool :)

  • lemorlenny

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

    Regards.

  • baer

    Hey,
    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: http://tempuri.org/CelsiusToFahrenheit.' 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!

    Greetz

    • baer

      No moderator anymore here, is it? Too bad :(

      • http://android.programmerguru.com Android Guru

        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!

    • http://android.programmerguru.com Android Guru

      W3Schools.com is no more accepting NAMESPACE as ‘http://tempuri.org’ which caused SOAP exception in our code. I verfied the NAMESPACE and SOAP_ACTION url in http://w3schools.com and we need to use ‘http://www.w3schools.com/webservices/’ in place of ‘http://tempuri.org’ 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!

  • Rahul

    superb…I appreciate your work

  • Ahmed

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

    • http://android.programmerguru.com Android Guru

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

  • Sandip Borad

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

  • 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.

  • 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

    • http://android.programmerguru.com Android Guru

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

  • Vijay

    Nice Tutorial!

  • Vijay

    Nice Tutorial! :D

  • Vijay

    Nice Tutorial! :)

  • 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. ???

        • http://android.programmerguru.com/ Android Guru

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

          Do post the log here so that will analyze.

  • Peter

    I haven’t received the confirmation link to register.

    • http://android.programmerguru.com Android Guru

      You must have received confirmation link already. Please check.

  • Nilendra

    yes this was very easy to understand and goodone!

    • http://android.programmerguru.com Android Guru

      Thanks Tripathi.
      Please take a look at our other tutorials.

  • Kunal

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

  • Fabrizio

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

  • eman

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

    • http://android.programmerguru.com Android Guru

      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

        • http://android.programmerguru.com Android Guru

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

  • NetStarter

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

    • http://android.programmerguru.com Android Guru

      Thanks for the comment NetStarter!

  • Conan

    Thank you for this glorious tutorial

  • http://androidws.diegodemarco.com 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 http://androidws.diegodemarco.com.

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

    • http://android.programmerguru.com Android Guru

      Appreciate your work!

  • Ragesh

    Fantastic…!

    • http://android.programmerguru.com Android Guru

      Thank you!