logo
Login

Sponsored Links

Sponsored

Building Live Stock Quotes App in Android

Stock Ticker App Android

Web Services and Service Oriented Computing has revolutionized the internet in the past decade. It is quite true that without web services most Apps in the App Store will not be that interesting!!

Mobile devices have a limited processing power so it becomes necessary to let a web server do the heavy lifting when it comes to computation. So in this tutorial I am bringing you a way to use RESTful webservice in your android app and parse the XML response.

The example web service that I am using is here. This web service lets you access current price of Stock based on its trading symbol.

Step 1: Know Thy Web Service

Before calling any web service you must know how to call it and what you will get in response. This web service is a RESTful service so calling it is easy using a GET request.

  1. GET /stockquote.asmx/GetQuote?symbol=string HTTP/1.1
  2.  
  3. Host: www.webservicex.net

The request requires a paramete that is the symbol for example AAPL is the stock ticker symbol for Apple Inc. and MSFT is for Microsoft. When we send a request like the following through a browser:

www.webservicex.net/stockquote.asmx/GetQuote?symbol=AAPL

will have the following output:

  1. <string>
  2. <StockQuotes>
  3. <Stock>
  4. <Symbol>AAPL</Symbol>
  5. <Last>500.00</Last><Date>1/18/2013</Date><Time>4:00pm</Time>
  6. <Change>-2.68</Change><Open>498.00</Open><High>502.22</High>
  7. <Low>496.40</Low><Volume>16898180</Volume><MktCap>470.3B</MktCap>
  8. <PreviousClose>502.68</PreviousClose>
  9. <PercentageChange>-0.53%</PercentageChange><AnnRange>419.55 - 705.07</AnnRange>
  10. <Earns>44.15</Earns><P-E>11.39</P-E><Name>Apple Inc.</Name>
  11. </Stock>
  12. </StockQuotes>
  13. </string>

Step 2-Create thy app!!

project create
Just open eclipse and follow the wizard!!

Step 3- The Manifest

We are accessing external web service so of course we have to add support for using the internet in the app. This means changing our manifest and adding the following line to the manifest inside the manifest tag:

  1.  <uses-permission android:name="android.permission.INTERNET" />

Without this permission the app will not be able to contact the web service

Step 4-Creating the view

In the view we need three things:

  1. An EditText control to enter ticker symbol
  2. A button to perform the task
  3. A text view to display the stock symbol value

The view xml will look like this

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.    xmlns:tools="http://schemas.android.com/tools"
  3.    android:layout_width="match_parent"
  4.    android:layout_height="match_parent"
  5.    tools:context=".ChooseSymbolActivity" >
  6.  
  7.     <TextView
  8.        android:id="@+id/textView1"
  9.        android:layout_width="wrap_content"
  10.        android:layout_height="wrap_content"
  11.        android:layout_alignBottom="@+id/editText1"
  12.        android:layout_alignParentLeft="true"
  13.        android:layout_alignTop="@+id/editText1"
  14.        android:text="Enter Ticker Symbol" />
  15.  
  16.     <EditText
  17.        android:id="@+id/editText1"
  18.        android:layout_width="match_parent"
  19.        android:layout_height="wrap_content"
  20.        android:layout_alignParentTop="true"
  21.        android:layout_marginTop="36dp"
  22.        android:layout_toRightOf="@+id/textView1"
  23.        android:ems="10" >
  24.  
  25.         <requestFocus />
  26.     </EditText>
  27.  
  28.     <Button
  29.        android:id="@+id/button1"
  30.        android:layout_width="wrap_content"
  31.        android:layout_height="wrap_content"
  32.        android:layout_below="@+id/textView1"
  33.        android:layout_centerHorizontal="true"
  34.        android:layout_marginTop="36dp"
  35.        android:text="@string/butText" />
  36.  
  37.     <TextView
  38.        android:id="@+id/textView2"
  39.        android:layout_width="wrap_content"
  40.        android:layout_height="wrap_content"
  41.        android:layout_below="@+id/button1"
  42.        android:layout_centerHorizontal="true"
  43.        android:layout_marginTop="53dp"
  44.        android:text="@string/soon" />
  45.  
  46. </RelativeLayout>

And the view itself looks like this

screen preview

Step 5-Calling Web Service

We will have to call the web service then parse the response. To do that I am creating a helper class which calls the service and returns various values. Initially I have added only basic getters and setters for the fields I want to display to my user.

  1. package com.example.tickstock;
  2.  
  3. import java.io.InputStream;
  4.  
  5. import org.apache.http.HttpEntity;
  6. import org.apache.http.HttpResponse;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.impl.client.DefaultHttpClient;
  10. import org.xmlpull.v1.XmlPullParser;
  11.  
  12. import android.util.Xml;
  13. public class StockServiceHelper {
  14.         String symbol;
  15.         double last;
  16.         String name;
  17.         java.util.Date curDate;
  18.         HttpResponse httpResponse;
  19.         //the base url of the web service
  20.         static String baseUrl="http://www.webservicex.net/stockquote.asmx/GetQuote?symbol=";
  21.  
  22.  
  23.         public StockServiceHelper(String symbol) {
  24.                 super();
  25.                 this.symbol = symbol;
  26.         }
  27.        
  28.         public String getSymbol() {
  29.                 return symbol;
  30.         }
  31.         public void setSymbol(String symbol) {
  32.                 this.symbol = symbol;
  33.         }
  34.         public double getLast() {
  35.                 return last;
  36.         }
  37.         public void setLast(double last) {
  38.                 this.last = last;
  39.         }
  40.         public String getName() {
  41.                 return name;
  42.         }
  43.         public void setName(String name) {
  44.                 this.name = name;
  45.         }
  46.         public java.util.Date getCurDate() {
  47.                 return curDate;
  48.         }
  49.         public void setCurDate(java.util.Date curDate) {
  50.                 this.curDate = curDate;
  51.         }
  52.  
  53. }

Now we need to add two functions:

  • A function to call the service itself
  • A function to parse the xml response

The first function is as follows:

  1. public void callService()
  2. {
  3.         HttpClient client=new DefaultHttpClient();
  4.                
  5.         HttpGet httpget = new HttpGet(baseUrl+symbol);
  6.         int responseCode=0;
  7.         String message;
  8.         String response;
  9.         try
  10.         {
  11.                 httpResponse = client.execute(httpget);
  12.                 responseCode = httpResponse.getStatusLine().getStatusCode();
  13.                 message = httpResponse.getStatusLine().getReasonPhrase();
  14.                 readresponse();        
  15.         }
  16.         catch (Exception e)
  17.         {
  18.                
  19.         }
  20. }

Now to parse the response the first step will be to get the inputstream of the response. Next we will parse the input stream using Android's XML Pull Parser to get values of different tags

  1. private void readresponse() {
  2.         HttpEntity entity = httpResponse.getEntity();
  3.         try {
  4.         if (entity != null) {
  5.                 InputStream instream = entity.getContent();
  6.                 // read the stream
  7.                 String innerXml = new String();
  8.                 XmlPullParser parser = Xml.newPullParser();
  9.                 // auto-detect the encoding from the stream
  10.                 parser.setInput(instream);
  11.                 int eventType = parser.getEventType();
  12.                 while (eventType != XmlPullParser.END_DOCUMENT) {
  13.                         String name = null;
  14.                         switch (eventType) {
  15.                         case XmlPullParser.START_DOCUMENT:
  16.                                 System.out.println("start document");
  17.                                 break;
  18.                         case XmlPullParser.START_TAG:
  19.                                 name = parser.getName();
  20.                                 innerXml=parser.nextText();                            
  21.                                 break;
  22.                         case XmlPullParser.END_TAG:
  23.                                 break;
  24.                         }
  25.                         eventType = parser.next();                                     
  26.                 }
  27.                 parser=Xml.newPullParser();
  28.                 parser.setInput(new StringReader(innerXml));
  29.                 System.out.println(innerXml);
  30.                 eventType=parser.getEventType();
  31.                 while (eventType != XmlPullParser.END_DOCUMENT) {
  32.                         String name = null;
  33.                         switch (eventType) {
  34.                         case XmlPullParser.START_DOCUMENT:                                     
  35.                         break;
  36.                         case XmlPullParser.START_TAG:
  37.                         name = parser.getName();
  38.                         if (name.equalsIgnoreCase("last")) {
  39.                                 this.setLast(Double.parseDouble(parser.nextText()));
  40.                         } else if (name.equalsIgnoreCase("date")) {
  41.                                 Date x = new Date(parser.nextText());
  42.                                 this.setCurDate(x);
  43.                         } else if (name.equalsIgnoreCase("name")) {
  44.                                 this.setName((parser.nextText()));
  45.                         }
  46.                         break;
  47.                         case XmlPullParser.END_TAG:                                            
  48.                         break;
  49.                 }
  50.                 eventType = parser.next();
  51.                                        
  52.         }
  53.         instream.close();
  54.         }
  55.         } catch (Exception e) {
  56.                 e.printStackTrace();
  57.         }
  58. }

Now all that remains is to call this helper when we need it in our activity

Step 6-Add thy Event Handler

Let us now add an event handler for out button in our activity and call the service. To add an event handler we have to first edit the button in the xml layout and add event listener like this:

  1.  <Button
  2.        android:id="@+id/button1"
  3.        android:layout_width="wrap_content"
  4.        android:layout_height="wrap_content"
  5.        android:layout_below="@+id/textView1"
  6.        android:layout_centerHorizontal="true"
  7.        android:layout_marginTop="36dp"
  8.        android:text="@string/butText"
  9.        android:onClick="onBtnClicked" />

Calling the web service requires access to the internet and that means we have to do this in an AsyncTask. So let us add the sync class as an inner class to our activity

  1. private class ContactWebservice extends AsyncTask<StockServiceHelper, Void, String> {
  2.  
  3.         @Override
  4.         protected String doInBackground(StockServiceHelper... params) {
  5.                 params[0].callService();
  6.                 return "Price for "+params[0].getName()+" is "+params[0].getLast();
  7.         }
  8.  
  9.         @Override
  10.         protected void onPostExecute(String result) {
  11.                 TextView txt = (TextView) findViewById(R.id.textView2);
  12.                 txt.setText(result);
  13.                        
  14.         }
  15.  
  16.         @Override
  17.         protected void onPreExecute() {
  18.         }
  19.  
  20.         @Override
  21.         protected void onProgressUpdate(Void... values) {
  22.         }
  23. }

Now we need to implement this particular event handler in our activity class called ChooseSymbolActivity. The handler will first check if the EditText we created contains a symbol or not before calling the AsyncTask we created

  1. public void onBtnClicked(View v) {
  2.         if (v.getId() == R.id.button1) {
  3.                 // handling the click now
  4.                 EditText sym = (EditText) findViewById(R.id.editText1);
  5.                 TextView tv = (TextView) findViewById(R.id.textView2);
  6.                 if (sym.getText().toString().equalsIgnoreCase("")) {
  7.                         tv.setText("Enter Symbol!!");
  8.                 } else {
  9.                         symbol = sym.getText().toString();
  10.                         helper = new StockServiceHelper(symbol);
  11.                         new ContactWebservice().execute(helper);
  12.                 }
  13.  
  14.         }
  15. }

And here is the final Output!!!

The complete Source code for the app is attached to the post.

AttachmentSize
StockTicker.zip957.58 KB
Like Developerfeed? Follows us via: RSS Feed Follow me on Twitter! Follow me on Facebook! Follow me on Youtube!

Socialize & Share Now :

Subscribe to DeveloperFeedDid you like this article? Did it Help you Solve your Problem? You can get the all the latest articles published at DeveloperFeed in your email inbox by entering your email address below. Your address will only be used for mailing you the articles, and each one will include a link so you can unsubscribe at any time.

Enter your email address:

cute puppy wallpapers download's picture
 #

Hello it's me, I am also visiting this website regularly, this website is in fact nice and the visitors are genuinely sharing fastidious thoughts.

 
Pwal's picture
 #

Thanks for this great tutorial, it helps a lot.

 
mvohra's picture
 #

The updated project has been added to post, please download it. The earlier one was failing with a NPE, that has been fixed. Thank You for your feedback.

 
JS's picture
 #

Great tutorial, it really helped me getting started with Webservices in Android. Thanks!

 
Anonymous's picture
 #

Hi, 

First of all a big thank you to the developer for sharing knowlwdge. Whenever, i try to run the application on Platform 16, the layout page comes up and when i search for the Stock Quote, say for example "MSFT", i always get the error as "Application has stopped working." Please help me out in this problem.

 

Subscribe & Follow

RSS Feed Follow me on Twitter! Follow me on Facebook! Follow me on Youtube!
Feed via Email:

Sponsored Links

Facebook

Sponsored Apps

Job Change Alert for Linkedin


Contact2CRM for Salesforce


Advertise on DeveloperFeed

About

Manpreet is an Architect & Software developer currently focusing on developing mobile apps on the iOS (iPhone/iPad) Platform. He’s the founder of a small iPhone development studio
called Livrona.

Subscribe to Developer Feed iPhone Blog

Tags

Who's online

There are currently 0 users and 6 guests online.