Forum Xamarin.Android

Web service creation and consumption in an Android app

astahirastahir USMember ✭✭

Hello everyone,

I am very new to mobile development and currently needs to develop an app in Android using Xamarin.Android. I have worked in ASP.NET for some time now.

Okay now to the question: I have created a MySQL database and also the prototype of the Android app. Now I need to create web service to make the two communicate. Can any of you guide me / share a tutorial / code example / article that tells how to create as well as consume web services? I don't have a preference regarding the type of web service used (REST / XML / JSON). The only aim is to be able to create web service that can let me fetch and save data on the database from my app.

Thanks,
Ahmed

Best Answers

Answers

  • rmaciasrmacias USBeta, University ✭✭✭✭✭

    If your very familiar with ASP.Net mvc, the I'd recommend building a restful service using ASP.NET Web API. Very slick and easy to use. You can call it from your Android app the same way as any other .NET project.

    http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

  • astahirastahir USMember ✭✭

    Thanks Ruben for your response but I am afraid I haven't worked on MVC. Anyway, I created a JSON WCF REST service and now I will start looking for a tutorial / article that helps me consume the service in my Xamarin.Android app.

    Can you help me there?

  • astahirastahir USMember ✭✭

    Hello everyone,

    I have been trying to consume a web service throughout the day today but in vain! I have written a WCF REST JSON web service but couldn't consumer it. Then I wrote a simple .NET ASMX web service and tried to consume it as well but to no avail. Can you share a link of a tutorial / article / video that gives a step-by-step guide to consume a web service in Xamarin.Android app?

    Any help in this regard will be highly appreciated.

    Thanks,
    Ahmed

  • astahirastahir USMember ✭✭

    Thanks Sami but can you direct me to some place where I can use the built-in things rather than adding new framework?

    Ruben, this was the first link that I went through but unfortunately it didn't help me achieve the required task. So basically I am still in the middle of nowhere!

  • rmaciasrmacias USBeta, University ✭✭✭✭✭

    So, you have not given any type of information (error logs, stack trace, code, things that you have tried, etc). All you have said is "it doesn't work". Post exactly the problems you are having with as much detail as you can and you'll likely get the response you're looking for.

  • astahirastahir USMember ✭✭

    I agree Ruben, you are right. Let me go into detail.

    Lets talk about the "3. Consuming SOAP Services" section of the link that you shared. I have a very simple web service running at http://localhost:27417/MathService.asmx. Here is its code:

        public class MathService : System.Web.Services.WebService
        {
    
            [WebMethod]
            public int Add(int a, int b)
            {
                return (a + b);
            }
    
            [WebMethod]
            public System.Single Subtract(System.Single A, System.Single B)
            {
                return (A - B);
            }
    
            [WebMethod]
            public System.Single Multiply(System.Single A, System.Single B)
            {
                return A * B;
            }
    
            [WebMethod]
            public System.Single Divide(System.Single A, System.Single B)
            {
                if (B == 0)
                    return -1;
                return Convert.ToSingle(A / B);
            }
    
            [WebMethod]
            public TestClass TestingObj(Int32 id, String name)
            {
                TestClass ret = new TestClass() { ID = id, Name = name, flag = true };
                return ret;
            }
        }
    

    Now I also have an Android app that I have in Xamarin Studio and I want to consume this web service in that app. The next step I do is I add the web reference (see the attached image).

    This brings me to the "3.2 Invoking SOAP Services" section and this is where I am totally lost! It simply gives me two lines of code but I neither seem to have _Service nor PopulateResults(). Can you take me ahead from here?

    Thanks.

  • astahirastahir USMember ✭✭

    Can anybody please help me out here?

  • softlionsoftlion FRBeta ✭✭✭

    You can not "add web reference". It generates code which include an unavailable NET library.
    You must write your own HTTP query code as usual.

  • astahirastahir USMember ✭✭

    Do you mean that to consume a SOAP Service I have to follow different steps than the ones I have mentioned above? If yes, can you guide me how to do that?

    Thanks.

  • astahirastahir USMember ✭✭

    Okay guys, I tried another thing. I used this article from MSDN to get the JSON string from my WCF service. It works flawlessly in a simple ASP.NET application but when I try to run the same code in my Xamarin.Android application, I get an error at the line

    WebResponse response = request.GetResponse ();

    It says 'System.Net.WebException has been thrown. Error: ConnectFailure (The requested address is not valid in this context)'

    Here is the Stack Trace:

    System.Net.WebException: Error: ConnectFailure (The requested address is not valid in this context) ---> System.Exception: The requested address is not valid in this context
    
      at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x00000] in <filename unknown>:0
    
      at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x00000] in <filename unknown>:0
    
      --- End of inner exception stack trace ---
    
      at at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult) <IL 0x00064, 0x002d0>
    
      at at System.Net.HttpWebRequest.GetResponse () <IL 0x00010, 0x000d3>
    
      at HelloAndroid.Activity1.OnCreate (Android.OS.Bundle) [0x00033] in e:\Work\Xamarin\Android\Self\HelloAndroid\HelloAndroid\MainActivity.cs:67
    
      at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (intptr,intptr,intptr) [0x00010] in /Users/builder/data/lanes/monodroid-lion-bs1/95789e18/source/monodroid/src/Mono.Android/platforms/android-8/src/generated/Android.App.Activity.cs:1490
    
      at at (wrapper dynamic-method) object.3fab4791-7710-4ea9-bbe9-fca452cfc284 (intptr,intptr,intptr) <IL 0x00017, 0x00043>
    
      at 
    

    Please let me know what could be the problem here.

    Thanks.

  • PiyushBhatt.5672PiyushBhatt.5672 USUniversity ✭✭

    Ahmed,

    Not sure if you got passed this as this is old thread. But I was trying this today and here is how it works:

    • On an Android Project (or whichever you have) in Xamarin Studio, you right click and select Add Web Reference
    • Type in your service Url
    • Make sure you update the Namespace to what you want
    • Hit OK - (I guess you did this so far)
    • Now, go to project directory and you will see Service References folder
    • under that you will see the namespace you had chosen for web-service
    • inside there should be Reference.cs file open that to see what is inside
    • this is all just for you to know the background - it should have the namespace and the service client class
    • go back to your code class - and type using .
    • create instance of the service class by - ServiceClassName _Service = new ServiceClassName()
    • and you can call _Service.GetMyResults();
    • while compiling it may give error for RuntTime.Serialization - add that reference manually

    By the way, I am trying out SOAP rightnow and hoping it works similarly for REST as well for you.

  • astahirastahir USMember ✭✭

    Piyush,

    Thank you very much for coming to my help as this still stands unresolved! Unfortunately, I am still getting an exception after following the steps mentioned by you. As soon as I call the required method, I get the following exception:

    System.Net.WebException: Error: ConnectFailure (The requested address is not valid in this context) ---> System.Exception: The requested address is not valid in this context
    
      at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x00000] in <filename unknown>:0
    
      at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x00000] in <filename unknown>:0
    
      --- End of inner exception stack trace ---
    
      at System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0
    
      at System.Net.HttpWebRequest.GetRequestStream () [0x00000] in <filename unknown>:0
    
      at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke (System.String method_name, System.Object[] parameters) [0x00000] in <filename unknown>:0
    

    This is my simple code after adding the reference just like you mentioned and I am not getting any compilation errors:

    MathService myService = new MathService();
    
    int sum = myService.Add(5,6);
    

    Thanks and hoping to finally resolve this issue with your help.

  • elsanto079elsanto079 USMember ✭✭

    hi, im new with xamarin, im having an error: "System.Web.Services.Protocols.SoapException:" with WCF when execute from the emulator (i change the ip to 10.0.2.2 and the namespace reference from http://tempuri.org to the ip)
    i make a breakpoint an here is where it fails:

    /// <remarks/>
            [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://10.0.2.2/WcfServiceLibrary1/Service1/GetData", RequestNamespace = "http://10.0.2.2", ResponseNamespace = "http://10.0.2.2", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
            [return: System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
            public string GetData(int value, [System.Xml.Serialization.XmlIgnoreAttribute()] bool valueSpecified) {
                object[] results = this.Invoke("GetData", new object[] {
                            value,
                            valueSpecified});
                return ((string)(results[0]));
            }
    
  • astahirastahir USMember ✭✭

    Ruben mate, where had you hidden this vital piece of information! Though it is very trivial but I was overlooking this point. I was running the app on the connected device and the web service was on my local machine and as you said "localhost" is not valid for an Android device.

    As a result I asked for a relevant hosting from client and that's when Sami jumped in to make things even easier for me. The address 10.0.2.2 finally worked for me on the emulator but I cannot make it run on the device. Sami, I tried giving my machine's address 192.168.0.17 instead of 10.0.2.2 but I get Request Timed Out error.

    Anyway, thanks a lot mates. I have finally managed to move things forward.

    Ahmed

  • astahirastahir USMember ✭✭

    @elsanto079, I am sorry I won't be able to help you here as I don't know what's going on. As per my last post, I did get my thing working and I have a WCF service as well. Perhaps somebody else can help you.

    Thanks,
    Ahmed

  • MShoaibWaheedMShoaibWaheed USMember

    Dear Tahir,

    Did you get any solution? Actually, I'm also new and want to implement same thing. How I have to achieve. Kindly, guide me with sample of code.

    Thanks in advance.

  • astahirastahir USMember ✭✭

    Shoaib, first of all sorry for the late response. Well as I wrote in one of my previous messages that I have managed to make it work on an emulator with the help of Ruben and Sami but not on actual device. What's the exact problem that you are facing?

    I suggest that you write a simple web service and a simple client to consume it. Make this work first, to make sure that the communication is happening. You can later fill it in with details.

    Thanks.

  • AtulBabbarAtulBabbar USMember

    Dear Ahmed

    Can you please help me in the same by guiding step by step..
    I am also getting the same error...unable to connect android with web service...
    i am working on localmachine....and emulator i also on local machine(from tools menu)
    please help

  • JeswinRajJeswinRaj USMember
    edited September 2014

    Hi,

    Am also trying to consume Web Service in my app, it is working fine in an emulator. But not in my device. I have generated an apk file and installed in my device(NEXUS 4, ST23i), web service cannot be called.
    Note that Service URL is given as static IP
    It would be much greatful if anyone help me to find the way to consume web service from my own device.

    Thanks in advance.

  • astahirastahir USMember ✭✭

    Hi,

    I think if you go through all the comments above, they should guide you towards the resolution of the issue. However, two immediate things come to my mind:

    1. Try opening the web service URL in your device's web browser and see if it opens correctly or not.

    2. Make sure that you have added INTERNET permission for your app in AndroidManifest.

    Thanks

  • ChrisAikenChrisAiken USMember, University

    hi i'm currently having this challenge, i have added my asmx web service to my android app and it generate a reference.cs code please how can i call the webservice from xamarin. here is my web service

    [WebMethod] public string insertData(string title, string coment) { string Message;

    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("INSERT INTO Header (title, coment)
    VALUES (@title, @coment)", con);

    cmd.Parameters.Add("@title", SqlDbType.NVarChar, 50).Value = title;
    cmd.Parameters.Add("@coment", SqlDbType.NVarChar, 50).Value = coment;

    con.Open();
    int result = cmd.ExecuteNonQuery();
    if (result == 1)
    {
    Message = " Details inserted successfully";
    }
    else
    {
    Message =" Details not inserted successfully";
    }
    con.Close();
    return Message;
    }

  • rebecca.2565rebecca.2565 USMember

    very helpful

  • samratmitrasamratmitra USMember

    Why we are not getting response from loaclhost i.e. 10.0.2.2...? Getting error Connect failure ...

    InnerException {System.Net.Sockets.SocketException: Connection timed out at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x000f7] in :0 at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x0019b] in :0 } System.Net.Sockets.SocketException

  • EidandEidand GBMember, University ✭✭✭

    hopefully this will help you, I know a lot of people have difficulties working with rest services. So maybe this article will help a little bit :

    http://eidand.com/2015/07/25/xamarin-rest-services-pcl/

    Piece of advice, before trying anything make sure your service actually works.

    I use Fiddler and Postman ( both free ) to test all my endpoints, be it GET or POST. Once you are sure your service works then try the code in the article. It will show how to build a service wrapper which works cross platform from a PCL.

  • samratmitrasamratmitra USMember

    Dear Eidand

    I have checked your link. 2 3 things are not clear to me...

    1. Create the solution and the PCL project--- It it Xamarin Studio or in VS 2010 ?
    2. How to create the service wrapper?

    Don't have much idea about xamarin.... So if you guide me that will be very helpful for me...

  • EidandEidand GBMember, University ✭✭✭

    both, doesn't matter where you create it, it's the same thing and the same type

  • MartinFoltynMartinFoltyn USMember

    @rmacias said:
    What the exception means is that your webservice can not be reached. How are you running your app? On a device or on an emulator? Where is your webservice? On your local machine, on an actual server?

    Think about where your app is running from and where your webservice is, and how to get a connection between the two. Example if you're connecting to "http://localhost/MyWebService" and running your app is running on a device, then of course it's going to fail. That's because "localhost" is not a valid url from an android device.

    How is it possible that on iOS, localhost works fine and connects perectly to correct site (laptop's site?)

  • rmaciasrmacias USBeta, University ✭✭✭✭✭
    edited August 2016

    How is it possible that on iOS, localhost works fine and connects perectly to correct site (laptop's site?)

    @MartinFoltyn

    Because the iOS Simulator is a simulator and the Android Emulator is an Emulator. The iOS Simulator is not an isolated entity. It uses the resources of your Mac. So it uses the same CPU, same RAM, same file system, same network resources, etc, all without restriction. So if you have a 16 GB MacBook Pro, the Simulator will utilize as much RAM as Mac OS X will allow it. Even though iPhone devices may be restricted to 1 GB or 2 GB of RAM. Same for the CPU. Your iOS app on the Simulator will utilize the full power of your host CPU, even though an iDevice CPU is less powerful. On the networking side, it uses the same network resources.

    The Android Emulator is an isolated entity. It's basically a virtual machine that runs isolated from the host Mac/PC. So there are limits to how much CPU it can use, limits to how much RAM it can use, has its own isolated file system (that mimics the Android file system), and uses it's own network resources. Since the emulator is isolated, it knows nothing about your host PC/Mac. From the Emulator, localhost (127.0.01) will route to itself (your webservice is not running in the emulator, it's running on the host). You'll have to use 10.0.2.2, which the emulator will route your host PC/Mac.

Sign In or Register to comment.