Android Lists IV: Accessing and Consuming a SOAP Web Service I

Continued from: Android Lists: ListActivity and ListView III – Basic Layout and Formatting

It’s about time that we get some real data in our application instead of a boring, static set of data.  There are two different types of web services: SOAP (Simple* Object Access Protocol) and REST (Representational State Transfer) (* The simplicity of SOAP is left open for interpretation :)).

Web Service Types

SOAP services typically have a defined contract associated with all data structures, service methods, and more.  This contract is written in WSDL (Web Services Description Language) and published for consumers who use the web service.  Also, these types of services heavily use XML for data requests and responses.

REST services are more ad-hoc than SOAP services since they don’t use WSDL and they rely on pre-established standards (ex. XML and HTTP).  These types of services are free to return data in any format and communication between them is more “lightweight”.

Consuming a SOAP service on Android

In this post, I decided to go with consuming a SOAP web service for our Stock Viewer application.  The particular service that I’ll be consuming is located here.  On Android, consuming a SOAP web service is more difficult (as opposed to consuming a RESTful web service), since it does not include any libraries to communicate with SOAP web services.

Not to fear though, there is a library called kSOAP2 that will fill this gap quite nicely.  You can download the latest version of this library here (Right click on “View Raw File” and “Save Link As…”).  Save this file along with the project source (I typically create a “lib” folder that is on the same level as the “src” folder).  The library can be added as a reference to the project by right clicking the project, selecting “Build Path”, then “Add External Archives…”.

Using kSOAP2

I’ll start off by making a new StockQuoteFetcher class that will be the main point for all web service interaction with my application.

Let’s start by defining some properties of the web service in the StockQuoteFetcher class.  These are all taken from the web service, linked above.

package com.austinrasmussen.stockviewer;

public class StockQuoteFetcher {
	private final String NAMESPACE = "http://www.webserviceX.NET/";
	private final String METHOD_NAME = "GetQuote";
	private final String SOAP_ACTION = "http://www.webserviceX.NET/GetQuote";
	private final String URL = "http://www.webservicex.net/stockquote.asmx";

}

In the constructor,  I’m going to accomplish three things.  First, I’m going to create a SoapObject, which is basically a reference to a SOAP method name and namespace.  Second, I’m going to create a PropertyInfo object, which is the container for the parameters being passed to the web service (i.e. the stock ticker symbols).  Third, I’m going to create a SoapSerializationEnvelope, which “envelopes” the request and the property.

private final SoapSerializationEnvelope envelope;

public StockQuoteFetcher(String quotes)
{
	SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

	PropertyInfo quotesProperty = new PropertyInfo();
	quotesProperty.setName("symbol");
	quotesProperty.setValue(quotes);
	quotesProperty.setType(String.class);
	request.addProperty(quotesProperty);

	envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	envelope.dotNet = true;
	envelope.setOutputSoapObject(request);
}

The dotNet property of the envelope is set to true because the web service being called was created using .NET.

Now, all of the request objects are constructed, all that is left to do is establish a connection to the web service and send the request.  The following Fetch method will do just that.

	public List<StockQuote> Fetch()
	public String Fetch()
	{
		String result = "";
		HttpTransportSE httpRequest = new HttpTransportSE(URL);

		try
        {
			httpRequest.call(SOAP_ACTION, envelope);
			SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
            result =  response.toString();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
		return result;
	}

Notice that I left a commented out alternative method signature for the Fetch method.  For now, we’ll just return the raw XML from the web service back to the application to make sure everything looks good.  But wait… if we fire up the application now, we get shot down with a “Permission Denied” error.

Requesting Application Permissions

Open up the AndroidManifest.xml file and click the “Permissions” tab.  Click “Add”, then “Uses Permission”, and then “OK”.

For the Name, select android.permission.INTERNET and save the manifest file.  Congratulations, you have now given the application permission to connect to the Internet.

Connecting the StockQuoteFetcher to the application

To make sure that the StockQuoteFetcher is fetching the appropriate data from the web service, I’ll add a new StockQuote to the StockList activity that will display the returned XML from the web service.

package com.austinrasmussen.stockviewer;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.Toast;

public class StockList extends ListActivity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        List<StockQuote> stocks = new ArrayList<StockQuote>();
        stocks.add(new StockQuote("MSFT", 24.78));
        stocks.add(new StockQuote("ORCL", 34.02));
        stocks.add(new StockQuote("AMZN", 180.13));
        stocks.add(new StockQuote("ERTS", 19.73));

        StockQuoteFetcher sqf = new StockQuoteFetcher(stocks.get(0).getTickerSymbol());
        String xmlResult = sqf.Fetch();
        stocks.add(new StockQuote(xmlResult, 0.0));

        setListAdapter(new StockQuoteAdapter(this, stocks));
    }
}


Now, this looks absolutely appalling; however, we can be sure that we are pulling back data from the web service now since we can see it on the screen.  In the next part, I’ll explain how to parse the incoming XML data into StockQuote objects, so that the display looks much nicer.

Tags: , ,

This entry was posted on Sunday, April 17th, 2011 at 6:09 pm and is filed under Android. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

9 Responses to “Android Lists IV: Accessing and Consuming a SOAP Web Service I”

smitha s prakash March 30th, 2012 at 5:21 am

Thanks for sharing. it really helped me a lot 🙂

Pinky May 2nd, 2012 at 2:10 am

Hi, I have tried the above code but I cannot find the code for StockQuote class thats y I am getting error in StockList class .. Plz help

Austin Rasmussen May 2nd, 2012 at 6:30 am

Hi there Pinky,

You can look at the second article of this series (http://android.vexedlogic.com/2011/04/02/android-lists-listactivity-and-listview-ii-%E2%80%93-custom-adapter-and-list-item-view/) and that has the code for the StockQuote class you’re looking for.

Hope this helps!

Sherlin May 10th, 2012 at 8:52 am

Thanks a lot for sharing this code.It is really very helpful.I am trying to display the details like marketCapitals,volume,name etc. in next screen on click of list.
Any help would be highly appreciated.

Yoseph B. July 26th, 2012 at 9:22 am

Thank you very much, this is an excellent tutorial

Prasad September 3rd, 2012 at 5:11 pm

Nice post, really liked it.

girdhari October 29th, 2012 at 5:38 am

Nice tutorial

Peter Bosavage December 3rd, 2012 at 9:23 am

how do read the ksoap2 parameters on the (non-.net) server side?

-Thanks

Manish March 6th, 2013 at 7:34 am

Thanks alot. using this tutorial, first time i am able to do handson on a web service…

Leave a Reply

You must be logged in to post a comment.