Consume a Web Service in an Android application with C# MonoAnDroid application

Description:

In this application I will describe how to consume a web service in your MonoDroid application using VS 2010. (MonoDroid will not work in VS 2010 Express edition).

To install MonoDroid navigate to http://mono-android.net/Installation

Follow the instructions and download all the necessary files.

Figure 1.

webservice1.gif

In the Figure 1. I have created a new MonoDroid application named monoAndroidapplication.

webservice2.gif

Now Like Figure 2 go to Project -> Add Web Reference. Enter in the URL of your web service and click Add Reference I will consume a webservice (http://soatest.parasoft.com/calculator.wsdl) which will add 2 values and will display. In this webservice you can also perform division and multiplication.

Now In the Activity.cs file you have to write the code below.

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace MonoAndroidApplicationListView
{
    [Activity(Label = "MonoAndroidApplicationListView", MainLauncher = true)]
    public class Activity1 : Activity
    {
        int count = 1;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
           
// Create a new Button and set it as our view  

            //Button button = FindViewById<Button>(Resource.Id.MyButton);
            Button button = new Button(this);  
            button.Text = "Consume!";
            button.Click += button_Click;

            SetContentView(button);  

            //button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
        }
        private void button_Click(object sender, System.EventArgs e)
        {
            // Create our web service and use it to add 2 numbers  
            var ws = new Calculator();
            var result = ws.add(25, 10);

            // Show the result in a toast  
            Toast.MakeText(this, result.ToString(), ToastLength.Long).Show();
        }  

    }
}

Now in the figure below you will see the web service marked in red.

webservice3.gif

Run the Code by pressing F5 and you will see the result.

webservice4.gif

Note: Web services take time to access. Consider running them in a background thread. So be patient.


Similar Articles