How to call asp.net web service in android

It was bit difficult to find out a good tutorial on how to call ASP .Net web service from inside Android application so I just decided to write one.

In this post, we are going to discuss about calling a web service from inside an Android application that has been developed using ASP .Net technology.

Before we start with developing application, create a simple web service and deploy it in IIS server (server installed in your local machine or hosted server).

Do follow below links to create and deploy web service using ASP .Net in IIS server:

How-to-create-webservice-in-asp-net-using-csharp
How-to-deploy-asp-dot-net-webservice-in-iis

Quick Links

Project Structure

Layout creation:

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

Points to note:

  1. Connect your mobile and your local machine (where IIS installed) to same WiFi internet connection so that application which we are developing can access WebService installed in the local IIS server.
  2. Make sure you turned off Firewall in your local machine since FireWall will not allow the local machine to accept Http calls from other machines or servers

[pgsubscribe]

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

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


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="Call .Net Webservice"
        android:textSize="30dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:singleLine="true" 
        android:hint="Enter you name"/>

    <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="Invoke .Net WS" />

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

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_gravity="center_horizontal"
        android:visibility="invisible"
        />

</LinearLayout>

Application layout will look like:

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

Create a new class called ‘WebService’ which is going to have basic webservice configuration and web method invocations:

package com.prgguru.example;

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;

public class WebService {
	//Namespace of the Webservice - It is http://tempuri.org for .NET webservice
	private static String NAMESPACE = "http://tempuri.org/";
	//Webservice URL - It is asmx file location hosted in the server in case of .Net
        //Change the IP address to your machine IP address	
	private static String URL = "http://192.168.2.3/HelloWorldWebService/Service.asmx";
	//SOAP Action URI again http://tempuri.org
	private static String SOAP_ACTION = "http://tempuri.org/";

	public static String invokeHelloWorldWS(String name, String webMethName) {
		String resTxt = null;
		// Create request
		SoapObject request = new SoapObject(NAMESPACE, webMethName);
		// Property which holds input parameters
		PropertyInfo sayHelloPI = new PropertyInfo();
		// Set Name
		sayHelloPI.setName("Name");
		// Set Value
		sayHelloPI.setValue(name);
		// Set dataType
		sayHelloPI.setType(String.class);
		// Add the property to request object
		request.addProperty(sayHelloPI);
		// Create envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		//Set envelope as dotNet
		envelope.dotNet = true;
		// Set output SOAP object
		envelope.setOutputSoapObject(request);
		// Create HTTP call object
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

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

		} catch (Exception e) {
			//Print error
			e.printStackTrace();
			//Assign error message to resTxt
			resTxt = "Error occured";
		} 
		//Return resTxt to calling object
		return resTxt;
	}
}

Create following objects under DotNetWSActivity class:

	Button b;
	TextView tv;
	EditText et;
	ProgressBar pg;
	String editText;
	String displayText;

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

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Name Text control
        et = (EditText) findViewById(R.id.editText1);
        //Display Text control
        tv = (TextView) findViewById(R.id.tv_result);
        //Button to trigger web service invocation
        b = (Button) findViewById(R.id.button1);
        //Display progress bar until web service invocation completes
        pg = (ProgressBar) findViewById(R.id.progressBar1);
        //Button Click Listener
        b.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Check if Name text control is not empty
                if (et.getText().length() != 0 && et.getText().toString() != "") {
                    //Get the text control value
                	editText = 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 name");
                }
            }
        });
    }

Class AsyncCallWS:
Create it as inner class inside DotNetWSActivity.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() – Make ProgressBar visible
  2. doInBackground() – Invoke invokeHelloWorldWS by passing text and webmethod name
  3. onProgressUpdate() -Does nothing
  4. onPostExecute() – Make ProgressBar invisible and set the webservice response text in TextView
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
		@Override
		protected Void doInBackground(String... params) {
                        //Invoke webservice
			displayText = WebService.invokeHelloWorldWS(editText,"sayHello");
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			//Set response
			tv.setText(displayText);
                        //Make ProgressBar invisible
			pg.setVisibility(View.INVISIBLE);
		}

		@Override
		protected void onPreExecute() {
                        //Make ProgressBar invisible
			pg.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}

	}

Click here to know more about AsyncTask,

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]

If you feel the tutorial is helpful, please share your feedback below.

[pgfeedback]
[pgwriteforus]

Related Articles

Author: Android Guru

Share This Post On
  • inf

    very useful post bro…

  • dadung

    Hi, thank you for your tutorial.
    I have one problem when following your tutorial
    Specifically, I followed your previous tutorials to set up web service successfully.
    But when I follow your above tutorial and implement Android client, the result is always “Error occured”.
    I replace the address of web service by other address given here (http://www.codeproject.com/Articles/304302/Calling-Asp-Net-Webservice-ASMX-From-an-Android-Ap) and my client can access to this web service
    I am also turn off all fire walls in my computer.
    Could you please help me to solve this problem.
    Thank you so much!

    • Could you check your log message and let me know what error are you seeing there so that I can help you?

  • Do Loan

    I did do follow guide but I don’t load services on server. help me!

  • Amila Thennakoon

    This works for me ….. how to send double parameter insted of String parameters

    • You have to just set the Type of PropertyInfo as ‘Double.class’ in the place of ‘String.class’.

      • Amila Thennakoon

        its not work ….

        • Have you created web service and deployed it in local server?
          Please let us know at which point you are stuck so that we will try to help you.

  • thomas

    excellent article, explained well and it works

    • Thanks Thomas!

      • thomas

        I tried to display a list view based on an arraylist (populated from sql server at webservice) that gives me error at postExecute() arraylist has current values. What could be the reason? Any suggestions?

        @Override

        protected Void doInBackground(String… params) {

        //displayText = WebService.invokeHelloWorldWS(editText,”GetMenuList”);

        arraylist = WebService.invokeHelloWorldWS(editText,”GetMenuList”);

        return null;

        }

        @Override

        protected void onPostExecute(Void result) {

        //tv.setText(fahren + “° F”);

        //tv.setText(displayText);

        list.setAdapter(new ArrayAdapter(DotNetWSActivity.this,

        android.R.layout.simple_list_item_1, arraylist));

        pg.setVisibility(View.INVISIBLE);

        }

      • thomas

        please ignore the question I sent earlier, fixed it, some silly comment out was the issue, thanks

  • Arvind Kumar

    I created a webservice as per “How to create webservice in asp.net using csharp” and using Visual Studio 2012 ran it on my localhost

    then I downloaded the source code for “How to call asp.net web service in android”, and imported it in eclipse ADT IDE

    after making changes in WebService.java for ipaddress. I ran it.

    The screen to “Call .Net Webservice” showed up but when I entered a name and clicked button “Invoke .Net WS” it showed “Error Occured”

    I am unable to figure out what is the issue. Can someone suggest me?

    PS: I am using Samsung 4.1.2 Galaxy Tablet.

    • Please see logcat for what error or exception has occurred.

      Do post the error message so that I can help you out.

  • saan

    i try your code but i have error when run your code.

    • Hi Saan,

      Can you please post the error message you are getting here so that will take a look at it and help you out?

  • js

    HELP!!!
    hey,its a very helpful article

    But i am getting “Error occured” evrytime

    and Log =

    05-10 16:49:49.200: E/SpannableStringBuilder(32668): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

    05-10 16:49:49.210: E/SpannableStringBuilder(32668): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

    05-10 16:49:49.741: D/GestureDetector(32668): [Surface Touch Event] mSweepDown False, mLRSDCnt : -1 mTouchCnt : 4 mFalseSizeCnt:0

    05-10 16:50:03.754: W/System.err(32668): org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope (position:START_TAG @2:44 in java.io.InputStreamReader@4266c088)

    05-10 16:50:03.764: W/System.err(32668): at org.kxml2.io.KXmlParser.require(KXmlParser.java:2046)

    05-10 16:50:03.764: W/System.err(32668): at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:127)

    05-10 16:50:03.764: W/System.err(32668): at org.ksoap2.transport.Transport.parseResponse(Transport.java:63)

    05-10 16:50:03.764: W/System.err(32668): at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:100)

    05-10 16:50:03.764: W/System.err(32668): at com.example.webservice.WebService.invokeHelloWorldWS(WebService.java:41)

    05-10 16:50:03.764: W/System.err(32668): at com.example.webservice.Main$AsyncCallWS.doInBackground(Main.java:54)

    05-10 16:50:03.764: W/System.err(32668): at com.example.webservice.Main$AsyncCallWS.doInBackground(Main.java:1)

    05-10 16:50:03.764: W/System.err(32668): at android.os.AsyncTask$2.call(AsyncTask.java:287)

    05-10 16:50:03.764: W/System.err(32668): at java.util.concurrent.FutureTask.run(FutureTask.java:234)

    05-10 16:50:03.764: W/System.err(32668): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)

    05-10 16:50:03.764: W/System.err(32668): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)

    05-10 16:50:03.764: W/System.err(32668): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)

    05-10 16:50:03.764: W/System.err(32668): at java.lang.Thread.run(Thread.java:856)

  • Try to use native Android keyboard to enter values to your Application. The error is more of related to the keyboard you are using.

    Take a look at this discussion:

    http://stackoverflow.com/questions/13670374/android-span-exclusive-exclusive-spans-cannot-have-a-zero-length

  • Maicol

    Excellent article, I need a tuto please… about how to connect android with oracle using soap.. I am new in WS.. please help me… And Guru your tutorials are the best in the internet… if somebody know help me please.. my e-mail is mamc92@hotmail.com.. please @programmerguru:disqus

  • Thanks for your feedback. Please follow this link http://programmerguru.com/android-tutorial/category/web-service/ for Webservice tutorials.

  • Kim

    I followed your tutorial but I get error when casting envelope.getResponse() to SoapPrimitive
    Error: “.

    java.lang.ClassCastException: org.ksoap2.serialization.SoapObject cannot be cast to org.ksoap2.serialization.SoapPrimitive”

  • Hemal

    Hello Android Guru: Thanks for such wonderful tutorial. For me earlier I tried static String URL with “localhost” that was causing problem but after I put my ip. It worked and changed

    sayHelloPI.setName(“Name”);

    to

    sayHelloPI.setName(“name”);

    And it showed desired result.

    Thank you.

  • Cool :)

    • Ive done this change but in vain
      Its giving only Hello without the provided name

  • ARSALAN

    unfortunately app has stoped

  • Did you create ASP Dot Net webservice? Make sure it is up and running fine so that Application can invoke it.

    Go through the logcat log message to fix the issue.

  • ARSALAN

    all the things looking fine but the result is not showing

  • Boris Soto

    Very useful, thanks master

  • Make sure your device and server are connected to same WiFi connection.

  • prachi mittal

    thanku for the useful tutorial.

    but everytime i m getting ‘Error Occured’

    logcat:

    java.net.ConnectException: failed to connect to /192.168.1.34 (port 50681): connect failed: ETIMEDOUT (Connection timed out)

  • prachi mittal

    thanku for the useful tutorial.

    but everytime i m getting ‘Error Occured’

    logcat:

    java.net.ConnectException: failed to connect to /192.168.1.34 (port 50681): connect failed: ETIMEDOUT (Connection timed out)

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