Your feedback is appreciated..Send Feedback Thank You.

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. Host: www.webservicex.net

The request requires a parameter 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.     <TextView
  7.        android:id=“@+id/textView1″
  8.        android:layout_width=“wrap_content”
  9.        android:layout_height=“wrap_content”
  10.        android:layout_alignBottom=“@+id/editText1″
  11.        android:layout_alignParentLeft=“true”
  12.        android:layout_alignTop=“@+id/editText1″
  13.        android:text=“Enter Ticker Symbol” />
  14.     <EditText
  15.        android:id=“@+id/editText1″
  16.        android:layout_width=“match_parent”
  17.        android:layout_height=“wrap_content”
  18.        android:layout_alignParentTop=“true”
  19.        android:layout_marginTop=“36dp”
  20.        android:layout_toRightOf=“@+id/textView1″
  21.        android:ems=“10″ >
  22.         <requestFocus />
  23.     </EditText>
  24.     <Button
  25.        android:id=“@+id/button1″
  26.        android:layout_width=“wrap_content”
  27.        android:layout_height=“wrap_content”
  28.        android:layout_below=“@+id/textView1″
  29.        android:layout_centerHorizontal=“true”
  30.        android:layout_marginTop=“36dp”
  31.        android:text=“@string/butText” />
  32.     <TextView
  33.        android:id=“@+id/textView2″
  34.        android:layout_width=“wrap_content”
  35.        android:layout_height=“wrap_content”
  36.        android:layout_below=“@+id/button1″
  37.        android:layout_centerHorizontal=“true”
  38.        android:layout_marginTop=“53dp”
  39.        android:text=“@string/soon” />
  40. </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. import java.io.InputStream;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.client.HttpClient;
  6. import org.apache.http.client.methods.HttpGet;
  7. import org.apache.http.impl.client.DefaultHttpClient;
  8. import org.xmlpull.v1.XmlPullParser;
  9. import android.util.Xml;
  10. public class StockServiceHelper {
  11.         String symbol;
  12.         double last;
  13.         String name;
  14.         java.util.Date curDate;
  15.         HttpResponse httpResponse;
  16.         //the base url of the web service
  17.         static String baseUrl=“http://www.webservicex.net/stockquote.asmx/GetQuote?symbol=”;
  18.         public StockServiceHelper(String symbol) {
  19.                 super();
  20.                 this.symbol = symbol;
  21.         }
  22.         public String getSymbol() {
  23.                 return symbol;
  24.         }
  25.         public void setSymbol(String symbol) {
  26.                 this.symbol = symbol;
  27.         }
  28.         public double getLast() {
  29.                 return last;
  30.         }
  31.         public void setLast(double last) {
  32.                 this.last = last;
  33.         }
  34.         public String getName() {
  35.                 return name;
  36.         }
  37.         public void setName(String name) {
  38.                 this.name = name;
  39.         }
  40.         public java.util.Date getCurDate() {
  41.                 return curDate;
  42.         }
  43.         public void setCurDate(java.util.Date curDate) {
  44.                 this.curDate = curDate;
  45.         }
  46. }

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.         HttpGet httpget = new HttpGet(baseUrl+symbol);
  5.         int responseCode=0;
  6.         String message;
  7.         String response;
  8.         try
  9.         {
  10.                 httpResponse = client.execute(httpget);
  11.                 responseCode = httpResponse.getStatusLine().getStatusCode();
  12.                 message = httpResponse.getStatusLine().getReasonPhrase();
  13.                 readresponse();
  14.         }
  15.         catch (Exception e)
  16.         {
  17.         }
  18. }

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.         instream.close();
  53.         }
  54.         } catch (Exception e) {
  55.                 e.printStackTrace();
  56.         }
  57. }

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.         @Override
  3.         protected String doInBackground(StockServiceHelper… params) {
  4.                 params[0].callService();
  5.                 return “Price for “+params[0].getName()+” is “+params[0].getLast();
  6.         }
  7.         @Override
  8.         protected void onPostExecute(String result) {
  9.                 TextView txt = (TextView) findViewById(R.id.textView2);
  10.                 txt.setText(result);
  11.         }
  12.         @Override
  13.         protected void onPreExecute() {
  14.         }
  15.         @Override
  16.         protected void onProgressUpdate(Voidvalues) {
  17.         }
  18. }

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. }

And here is the final Output!!!

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

Attachment Size
StockTicker.zip 957.58 KB
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.