Click here to Skip to main content
15,072,933 members
Articles / Mobile Apps / Xamarin
Posted 22 Aug 2013


31 bookmarked

MonoAndroid: Using dotnet webservice (ASMX)

Rate me:
Please Sign up or sign in to vote.
4.90/5 (10 votes)
21 Nov 2013CPOL5 min read
Using ASMX webservices in your mobile application.


Here, Once again I am back with another article in my series of MonoAndroid, for previous article refers at bottom portion. In this article I am going to demonstrate using ASMX Web Service (Non-WCF) in Mobile App.

Web services are becoming integrated part of mobile and web applications. Mono Android support almost all type of Web Services like Restful, WCF and normal SOAP based web services. In this article I am going to create dotnet based web service and consuming same in my mobile application.

In this article I will create Software Developer Hierarchy app. In this we will create dotnet web service, where we provide web method which will send the list of software person with their designations and show them on our android mobile ListView.

Step By Step we move forward

  1. Create Android application by selecting New ->Solutions and provide its name “MonoWebService

    Image 1
    Figure 1: Creating Android Project!
  3. Now by default, when you create project in the android, it contain a button. So application flow would be on click of button, we will invoke web service and fill the ListView with the retrieved data.

    So Button text contains “Hello World” and when we check button properties, it will show its referring to string resource, Means button label is coming from string table. 

    Image 2

    Now to change text on the button, you have to modify strings.xml under Resources\values. Just look for name “hello” and change the name to “Retrieve Data from Web service”. See i marked line in bold.

    <?xml version="1.0" encoding="utf-8"?>
    	<string name="hello">Retrieve Data from Web service</string>
    	<string name="app_name">MonoWebService</string>

  4. Now add the ListView in the MainActivity file, after adding that, UI code looks something like this :-
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android=""
            android:text="@string/hello" />
            android:id="@+id/Main_ListView" />
  5. Now time if for you to create web service in visual studio 2010. Now open the “Create New Project”, change .Net framework 3.5 to make ASP.NET Web Service Application project available for selection.

     Image 3

    Now create the project by name “MonoAndroidWebService“ 

  6. Now change the name of default Service1 to MonoDataService and delete anything else there. Now add GetWebServiceMonoDatas() method which returns hardcoded list of WebServiceMonoData

     public class MonoDataService : System.Web.Services.WebService
      public List<WebServiceMonoData> GetWebServiceMonoDatas()
          var lstFragmentDemo = new List<WebServiceMonoData>
              new WebServiceMonoData()
                      Name = "Alok Gupta",
                      Desigination = "Snr Software Engineer"
              new WebServiceMonoData()
                      Name = "Jasdeep Singh",
                      Desigination = "Snr Auditor (Information)"
              new WebServiceMonoData()
                      Name = "Ashish Srivastava",
                      Desigination = "Software Test Engineer"
              new WebServiceMonoData()
                      Name = "Hariharan Ramchandran",
                      Desigination = "Product Architect"
          return lstFragmentDemo;

    Now following is the code of WebServiceMonoData class

    public class WebServiceMonoData
        public string Name { get; set; }
        public string Desigination { get; set; }

    Since we are sending our class using services over http, we need to make our class Serializable. Build and compile webservice, so that it would be available for creating web reference.

  7. Now In your mobile application, right click on the Project->Add-> Add Web Reference, see I marked that in following screenshot

    Image 4 

    Change web service URL to your local service address which is “http://localhost:61847/MonoDataService.asmx” in my case. Select framework .Net 2.0 web services and provide reference as “MonoDataService

    Image 5 

  8. Now add following code in MainActivity file, I will explain the further down
    public class MainActivity : Activity
      protected override void OnCreate (Bundle bundle)
         base.OnCreate (bundle);
         // Set our view from the "main" layout resource
         SetContentView (Resource.Layout.Main);
         Button button = FindViewById<Button> (Resource.Id.myButton);			
         button.Click +=  OnWebserviceRetrievedInformation;
      void OnWebserviceRetrievedInformation (object sender, EventArgs e)
         var objMonoAndroidService = new MonoDataService.MonoDataService ();
    	 objMonoAndroidService.BeginGetWebServiceMonoDatas (WebServiceCallBack,                    objMonoAndroidService);
      void WebServiceCallBack (IAsyncResult ar)
      	var objMonoAndroidService = 
    	   ar.AsyncState as MonoDataService.MonoDataService;
    	var arrWebServiceMonoDatas =
    		objMonoAndroidService.EndGetWebServiceMonoDatas (ar);
         var lstWebServiceMonoData =
         new List<MonoWebService.MonoDataService.WebServiceMonoData>(arrWebServiceMonoDatas);
    	var mainListView = FindViewById<ListView>(Resource.Id.Main_ListView);
    	mainListView.Adapter = new ListBaseAdapter (this, lstWebServiceMonoData);
    Above we are doing following
    • On button click create the object of the MonoDataService.MonoDataService and invoke GetWebServiceMonoDatas method asynchronously.
    • In the callback function, creating the List of WebServiceMonoData from retrieved array and passing it to our custom adapter to create ListView. Here is the code of our custom BaseAadapter derived class.
    public class ListBaseAdapter: BaseAdapter<WebServiceMonoData>
      List<MonoWebService.MonoDataService.WebServiceMonoData> _lstWebServiceMonoData;
      Activity _mainActivity;
      public ListBaseAdapter (Activity mainActivity, 
           List<MonoWebService.MonoDataService.WebServiceMonoData> lstWebServiceMonoData)
     	_lstWebServiceMonoData = lstWebServiceMonoData;
    	_mainActivity = mainActivity;
     #region implemented abstract members of BaseAdapter
      public override long GetItemId (int position)
     	return position;
      public override View GetView (int position, View convertView, ViewGroup parent)
     	var item = this [position];
    	if (convertView == null)
               convertView = _mainActivity.LayoutInflater.Inflate (Android.Resource.Layout.SimpleListItem2, parent, false);
       convertView.FindViewById<TextView> (Android.Resource.Id.Text1).Text 
        = item.Name;
       convertView.FindViewById<TextView> (Android.Resource.Id.Text2).Text 
        = item.Desigination;
    	return convertView;
       public override int Count {
     	get {
            	return _lstWebServiceMonoData== null? -1: _lstWebServiceMonoData.Count;
    	#region implemented abstract members of BaseAdapter
       public override WebServiceMonoData this [int index] {
    	get {
    	 return _lstWebServiceMonoData== null? null: _lstWebServiceMonoData[index];

    You can learn more about creating custom Base Adapter here

  9. Now build and run your mobile application, you will see this ugly exception popping up :- 

    Image 6 

    Problem here is that your mobile app trying to find the Web Service in local mobile, where it’s not present as it present on the development machine. Now to access web service from your emulator you need to use magic IP address, instead of LocalHost. Now while creating web service object pass the URL like this :-

    void OnWebserviceRetrievedInformation (object sender, EventArgs e)
      var objMonoAndroidService = 
      new MonoDataService.MonoDataService ("");
      objMonoAndroidService.BeginGetWebServiceMonoDatas (WebServiceCallBack, objMonoAndroidService);
  10. Try again to build and run mobile app, you again encountered exception, this time it’s due to updating UI control from worker thread.

    Image 7 

    Now to solve this problem, move these two line under RunOnUiThread under WebServiceCallBack method like this :-

    RunOnUiThread (() => {
    	var mainListView = FindViewById<ListView> (Resource.Id.Main_ListView);
    	mainListView.Adapter = new ListBaseAdapter (this, lstWebServiceMonoData);
  11. Now Build and Run the application,
    On 4 Inch Screen On Button Click
    Image 8 Image 9

Magic IP table

This section text is taken from here, word by word.

The virtual router for each instance manages the 10.0.2/24 network address space — all addresses managed by the router are in the form of 10.0.2.<xx>, where <xx> is a number. Addresses within this space are pre-allocated by the emulator/router as follows:

Network Address Description Router/gateway address Special alias to your host loopback interface (i.e., on your development machine) First DNS server / / Optional second, third and fourth DNS server (if any) The emulated device's own network/ethernet interface  The emulated device's own loopback interface

Points of Interest

I have used MonoAndroid for C# and Xamarin Studio to build this tutorial.  Watch out, if I continue learning it, you can expect more articles coming soon. 

Though Xamarin Studio is proprietary software, however they provide free starter version to built, test and publish android application. I am using same for my learning. 

Articles in this series!

Tips/Tricks in this Series  


  • 22-Aug-2013: First Version
  • 06-Sept-2013: Updated Tips and Tricks Section 
  • 10-Oct-2013: Updated Tips and Tricks Section 
  • 04-Nov-2013: Update Article series 
  • 22-Nov-2013: Updated other article section


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
India India
He used to have biography here Smile | :) , but now he will hire someone (for free offcourse Big Grin | :-D ), Who writes his biography on his behalf Smile | :)

He is Great Fan of Mr. Johan Rosengren (his idol),Lim Bio Liong, Nishant S and DavidCrow and Believes that, he will EXCEL in his life by following there steps!!!

He started with Visual C++ then moved to C# then he become language agnostic, you give him task,tell him the language or platform, he we start immediately, if he knows the language otherwise he quickly learn it and start contributing productively

Last but not the least, For good 8 years he was Visual CPP MSMVP!

Comments and Discussions

QuestionError: 400 (Bad Request) Pin
Member 1204689111-Oct-15 13:03
MemberMember 1204689111-Oct-15 13:03 
AnswerRe: Error: 400 (Bad Request) Pin
ThatsAlok11-Oct-15 20:27
MemberThatsAlok11-Oct-15 20:27 
GeneralRe: Error: 400 (Bad Request) Pin
Member 1204689113-Oct-15 1:32
MemberMember 1204689113-Oct-15 1:32 
QuestionRequest for more complex tutorials on how to connect android app to a .NET web service Pin
Member 84235817-Feb-15 22:06
MemberMember 84235817-Feb-15 22:06 
AnswerRe: Request for more complex tutorials on how to connect android app to a .NET web service Pin
ThatsAlok16-Mar-15 2:53
MemberThatsAlok16-Mar-15 2:53 
Questionhow to recive data using webservice to andorid expandable listview Pin
beniv29-Oct-13 13:03
Memberbeniv29-Oct-13 13:03 
AnswerRe: how to recive data using webservice to andorid expandable listview Pin
ThatsAlok29-Oct-13 18:46
MemberThatsAlok29-Oct-13 18:46 
GeneralRe: how to recive data using webservice to andorid expandable listview Pin
beniv29-Oct-13 23:20
Memberbeniv29-Oct-13 23:20 
Questionplease help me Pin
bmaymen_ammo4-Sep-13 21:38
Memberbmaymen_ammo4-Sep-13 21:38 
AnswerRe: please help me Pin
ThatsAlok5-Sep-13 1:00
MemberThatsAlok5-Sep-13 1:00 
GeneralRe: please help me Pin
bmaymen_ammo8-Sep-13 1:02
Memberbmaymen_ammo8-Sep-13 1:02 
AnswerRe: please help me Pin
ThatsAlok8-Sep-13 1:58
MemberThatsAlok8-Sep-13 1:58 
BugError in running Pin
bmaymen_ammo1-Sep-13 3:37
Memberbmaymen_ammo1-Sep-13 3:37 
GeneralRe: Error in running Pin
ThatsAlok1-Sep-13 5:47
MemberThatsAlok1-Sep-13 5:47 
GeneralMessage Closed Pin
1-Sep-13 20:57
Memberbmaymen_ammo1-Sep-13 20:57 
AnswerRe: Error in running Pin
ThatsAlok1-Sep-13 22:44
MemberThatsAlok1-Sep-13 22:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.