web analytics
Paste your Google Webmaster Tools verification code here

Creating a Stock Pricing Application with Kotlin for Android

Hold onto your seat because there is a new programming language for Android development and it rocks compared to Java.  There also seems to be a trend that developers are moving to the new language because of its power, ease of use, and library extensions that hide much of the pain that goes along with creating apps for the Android device.  This mysterious language is called Kotlin and it was developed by Jet Brains in Cooperation with Google.  It comes preinstalled with the latest and greatest Android Studio so you can start developing with it right away.   Kotlin contains a lot of the language constructs that developers crave in a modern programming language.  One of the large pieces missing in Java is the power of a functional language.  Kotlin has all of this built in.

In this article we will introduce you to Kotlin development by creating stock listing program.  The program calls a stock service called AlphaVantage to populate a screen with current stock prices.  This example covers a few areas of Android Programming using Kotlin:  creating a ListView and populating it with an ArrayAdapter, accessing a website through a REST call, and populating the screen through an Asynchronous Task.

Creating the Project

To create a Project in Android Studio with Kotlin Support. Simply Pick File -> New -> New Project from the Android Studio Menu.  In the Project Wizard there is a checkbox for Kotlin Support.  Simply click it, and Kotlin will be available to you for programming.  The Android Studio IDE is so intelligent, is that when you add a Kotlin class to your project and paste Java code into it, it will convert it to Kotlin for you.  Kotlin is also completely compatible with running  alongside Java, so you can mix the technologies!

 

Once you pick your Basic Activity template and  generate your project, we are ready to add the ListView that will contain our stock listings.

Creating the ListView

The ListView is a cool programming control that you can use to display lists on the Android. For our list control, we want to list stocks with two columns of information:  stock symbol and stock price.  We’ll keep it simple for this example.  First we’ll add a list view to our layout in our activity.

Now we need to setup the listview in code so it can receive data.  For this we’ll use an adapter.   The initial setup of the listview and hooking it to the adapter occurs in the onCreate event handler of the main activity.

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)// set list view
setUpListView()

setupButtonToAddStock()

setSupportActionBar(toolbar)
}

 

 

The onCreate calls a custom method called setUpListView in order to hook the listview up that we just added to the layout.  SetupListView first finds the ListView by the id we added to the xml layout file.   It then uses a custom adapter we created (more on this in a second) to add in a collection of stocks and hooks it into the ListView.

fun setUpListView() {
val stocks = ArrayList<Stock>()// find the list view in the layout file
val listView = findViewById<ListView>(R.id.listView1)
// Create the adapter to convert the array to views
val adapter = StockAdapter(this, stocks)
// Attach the adapter to a ListView

listView.adapter = adapter
addStocksToWatch()

}

 

The addStocksToWatch function , will utilize our StockService to asynchronously call this service with the stocks we wish to add to the adapter. We will see the asynchronous behavior later in this article:

fun addStocksToWatch() {
val listView = findViewById<ListView>(R.id.listView1)
StockService().execute(listView.getAdapter() as StockAdapter, “IBM”)
StockService().execute(listView.getAdapter() as StockAdapter, “FB”)
StockService().execute(listView.getAdapter() as StockAdapter, “MSFT”)
}

 

The StockAdapter class

The StockAdapter class adapts the data to the ListView so it can be displayed.  It inherits from ArrayAdapter so we can use an array of Stock objects to render in the ListView.  The getView method of the custom StockAdapter is overridden so it can pick the data out of the stock collection using the Adapter’s getItem method and render the stock from two properties (symbol and price) into TextView widgets contained in the row in the ListView.

 

package com.gdx_example.jcity_000.kotlinsample

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView

class Stock
{
var symbol : String = “”
var price : Float = 0.0f

constructor(symbol1: String, price1 : Float){
symbol = symbol1
price = price1
}
}

/**
* Created by jcity_000 on 11/12/2017.
*/
class StockAdapter(context: Context, stocks: ArrayList<Stock>) : ArrayAdapter<Stock>(context, 0, stocks) {

override fun getView(position: Int, convertView1: View?, parent: ViewGroup): View {
var convertView = convertView1
// Get the data item for this position
val stock = getItem(position)
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.item_stock, parent, false)
}
// Lookup view for data population
val tvSymbol = convertView!!.findViewById<TextView>(R.id.tvSymbol)
val tvPrice = convertView!!.findViewById<TextView>(R.id.tvPrice)
// Populate the data into the template view using the data object
tvSymbol.setText(stock!!.symbol)
if (stock!!.price < 0)
tvPrice.setText(“n/a”)
else
tvPrice.setText(stock!!.price.toString())
// Return the completed view to render on screen
return convertView
}

override fun getItem(position: Int): Stock {
return super.getItem(position)
}

}

 

Getting the Stocks with the Stock Service

We need to create a stock service to allow for the population of our stocks.  Because we will be going over http, we don’t want to operate in the main UI thread while we are retrieving data, or  it could freeze up the UI’s responsiveness.  Therefore we will take advantage of one of Kotlin’s third party libraries called Anko to asynchronously retrieve the data.

In order to retrieve stocks, we used a free stock service called AlphaVantage.  You’ll need to sign up in order to get an API key to utilize the service, but once you have the key, calling the API is fairly straightforward and it returns JSON which we can parse to get our stock  price.

The query in our stock service looks something like this (replace {myapikey} with your key after signing up for the service).

val url = “https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=%s&apikey={myapikey}”.format(symbol)

 

The data returned for this query looks something like this in JSON:

{    “Meta Data”: {        “1. Information”: “Daily Prices (open, high, low, close) and Volumes”,        “2. Symbol”: “MSFT”,        “3. Last Refreshed”: “2017-11-15”,        “4. Output Size”: “Compact”,        “5. Time Zone”: “US/Eastern”    },    “Time Series (Daily)”: {        “2017-11-15”: {            “1. open”: “83.4700”,            “2. high”: “83.6900”,            “3. low”: “82.6900”,            “4. close”: “82.9800”,            “5. volume”: “19337313”        },        “2017-11-14”: {            “1. open”: “83.5000”,            “2. high”: “84.1000”,            “3. low”: “82.9800”,            “4. close”: “84.0500”,            “5. volume”: “18604034”        },        “2017-11-13”: {            “1. open”: “83.6600”,            “2. high”: “83.9400”,            “3. low”: “83.4600”,            “4. close”: “83.9300”,            “5. volume”: “14080820”        },…

 

We will use the service to only pull out the closing price from the JSON object for our example.

Coding the Stock Service

We want the StockService to do three things for us

  1. Call the URL above to request the MSFT price data on a different thread than the UI thread
  2. Get the response on the same thread and parse out the price from the close
  3. Return to the UI thread and add the stock data to the StockAdapter

Fortunately all this is very easy with Kotlin and the Anko extension libraries.  Here is the main code to accomplish the three steps listed above:

package com.gdx_example.jcity_000.kotlinsample

import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import org.json.JSONObject
import java.net.URL
import java.text.SimpleDateFormat
import java.util.*

/**
* Created by jcity_000 on 11/14/2017.
*/
class StockService { fun execute(stocks: StockAdapter, symbol: String) {
val url = “https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=%s&apikey=IZ2R2PH0XZ2WPHC2”.format(symbol)

doAsync {      // send the URL request and read the response
val result = URL(url).readText()     //  Parse out the price from the JSON result
val price = getPrice(result)
uiThread {          //  add the resulting symbol and price of the stock to the adapter
stocks.add(Stock(symbol, price))
stocks.notifyDataSetChanged()
}
}
}

 

The Anko library has a structure with two pieces:  doAsync (where we add the code we are performing on a new thread) and uiThread where we add the code to perform code back on the UI thread once doAsync is completed.  In this example the doAsync call is used to make the httprequest and retrieve the response and the uiThread populates the adapter for the ListView.

 

The URL class allows us to construct a request from the URL and read the entire response in one simple line.  I remember this was much more difficult in the past with the Android libraries, now it’s a snap!  Next we call a custom routine we wrote to parse out the price from the JSON result.  Back on the uiThread we now have the price info we need to populate the adapter.

Parsing JSON

The getPrice function is used to parse json to get the closing price.  We take advantage of the JSONObject library to extract JSON from the response of the REST API.  It helps to understand JSON when using the JSON Object library. Primarily you need to understand json objects, json arrays, and json properties.  Below we traverse through a few JSON Objects to get to the close field that contains the price.  We need to determine the date key field from today’s date to get the price data from the current day.

fun getPrice(text : String) : Float {
if (text.trim().length == 0 || (“Invalid” in text)) return -1.0f
val message = text
val json = JSONObject(message)
val today = Date()
var DATE_FORMAT =  SimpleDateFormat(“yyyy-MM-dd”)
var dateKey = DATE_FORMAT.format(today) as String
// get price from today
val todaysStockPrices = ((json[“Time Series (Daily)”] as JSONObject)[dateKey] as JSONObject).getString(“4. close”)return todaysStockPrices.toFloat()

}

 

Conclusion

It’s not too difficult putting together a client/server android app on the phone using Kotlin.  It’s a very powerful language with advantages you find in languages such as C#, ES6 or GoLang making it a simple choice over Java.  I expect to see a lot more apps created over the coming years using the power of this language and its associated open source libraries.  If your curious about Kotlin, you can visit the official website to learn more.


Mike is a software engineer with a love for tinkering with smart phone devices. He spends a lot of time moving pictures to his SD card, because the Android keeps running out of memory. In his spare time, he travels to different parts of the world and takes one of his Android devices with him.

Share

Share This Post

Related Articles

Leave a Reply

*

© 2017 ToDroid. All rights reserved.
Disclaimer: The content on this site is copyrighted. Do not copy the content. The content on this site must not be reproduced anywhere else.