Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Main Activity of our Bitcoin Android App with Kotlin on the SSaurel's Blog
package com.ssaurel.bitcoinpricewatcher
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import okhttp3.*
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
// We will use the Coin Desk API to get Bitcoin price
val URL = ""
var okHttpClient: OkHttpClient = OkHttpClient()
override fun onCreate(savedInstanceState: Bundle?) {
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(, menu)
return super.onCreateOptionsMenu(menu)
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId) { -> {
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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment