Create a Bitcoin Watcher Android App with Kotlin

We continue our learning of Kotlin to develop Android applications. Today we will see how to make HTTP requests with Kotlin. For this, we will develop an application to know the price of Bitcoin in real-time.

Note that you can discover this tutorial in a video on YouTube:


Adding dependencies

To make HTTP requests in our application, we will use the OkHttp library provided by Square Up. For that, we add the OkHttp dependency in our buid.gradle file which will be have the following form:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.ssaurel.bitcoinpricewatcher"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
}

Configuring the Android Manifest

Like we are going to make some HTTP requests, we need to add the INTERNET permission in our AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ssaurel.bitcoinpricewatcher">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Creating the User Interface

The User Interface of our Android Application made with Kotlin will be quite simple. An ImageView to display a logo, a TextView to display the price of the Bitcoin in US Dollars and Euros and also a ProgressBar which will be displayed during the HTTP request to get the Bitcoin price.

We use the ConstraintLayout to place easily these views with the Design view on Android Studio. It gives us the following code for our activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ssaurel.bitcoinpricewatcher.MainActivity">
<ImageView
android:id="@+id/bitcoinLogo"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/bitcoin_kotlin_android" />
<TextView
android:id="@+id/bitcoinValues"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="60dp"
android:text="Click to load"
android:textSize="25sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/bitcoinLogo" />
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Creating a load entry on the menu

To let the users to load the price of the Bitcoin, we are going to use a dedicated entry in the menu of our application. We add it in the res/menu/main.xml file like that:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/load"
android:title="Load"
app:showAsAction="always" />
</menu>
view raw main.xml hosted with ❤ by GitHub

Writing the Kotlin code of the Main Activity

Now, it’s time to write the Kotlin code of the Main Activity. To get the Bitcoin price in real time, we are going to use the Coin Desk API which the end point is there: https://api.coindesk.com/v1/bpi/currentprice.json .

You can make a simple call to this end point on a browser for example. You should obtain the following result:

In the JSON response, you can see we will need first to get the bpi object of the main object. Then, we will to get the USD and the EUR objects. Finally, we will read the rate property of these two objects.

For that, we will create a Request object with the URL of the Coin Desk end point in parameter. Then, we will pass this Request object in parameter of the newCall method of our OkHttpClient instance. We will enqueue the call and the result will be obtained in a Callback object.

In this Callback object, we will obtain the JSON data got in the onResponse method. In this method, we will have to convert the data read to String to keep only the integer part of the rates.

Finally, we need to display the rates got from the Coin Desk API. For that, we need to execute our code in the UI Thread. So, we use a runOnUiThread call which is shortcuted in Kotlin. It will give us the following for the MainActivity:

package com.ssaurel.bitcoinpricewatcher
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import org.json.JSONObject
import java.io.IOException
class MainActivity : AppCompatActivity() {
// We will use the Coin Desk API to get Bitcoin price
val URL = "https://api.coindesk.com/v1/bpi/currentprice.json"
var okHttpClient: OkHttpClient = OkHttpClient()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId) {
R.id.load -> {
loadBitcoinPrice()
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun loadBitcoinPrice() {
progressBar.visibility = View.VISIBLE
val request: Request = Request.Builder().url(URL).build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException?) { }
override fun onResponse(call: Call?, response: Response?) {
val json = response?.body()?.string()
// we get the json response returned by the Coin Desk API
// make this call on a browser for example to watch the properties
// here we get USD and EUR rates properties
// we split the value got just to keep the integer part of the values
val usdRate = (JSONObject(json).getJSONObject("bpi").getJSONObject("USD")["rate"] as String).split(".")[0]
val eurRate = (JSONObject(json).getJSONObject("bpi").getJSONObject("EUR")["rate"] as String).split(".")[0]
runOnUiThread {
progressBar.visibility = View.GONE
bitcoinValues.text = "$$usdRate\n\n$eurRate€"
}
}
})
}
}

Testing our Bitcoin Price Android App

Now, it’s time to try our Bitcoin Price Android App made with Kotlin. By launching the application, you should have the following screen:

Our Android App at start

Click on the load entry in the Action Bar and the Bitcoin prices should be loaded. You should enjoy the following display:

Bitcoin prices displayed

Great!

That’s all for that tutorial. To discover more Android tutorials, don’t hesitate to subscribe on the SSaurel’s Channel:

https://www.youtube.com/channel/UCXoh49OXVg1UGjgWX1JRvlw

You can also visit SSaurel’s Blog if you want to discover more tutorials on Android and Java development: https://www.ssaurel.com/blog

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *