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

[pgsubscribe]

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" />

[pglinkadssmall1]

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.

[pglinkadssmall]

I hope you enjoyed the post!! 🙂
[pgfeedback]
[pgwriteforus]

Related Articles

Author: Udhay

Share This Post On
468 ad
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

Shares