
Chock Norris Facts Android App on Kotlin
- Transfer
Facts about Chuck Norris is an internet phenomenon with humorous “facts” about martial arts master and actor Chuck Norris. “Facts” are jokes about Norris’s stamina, his masculinity and alpha male status.
In this tutorial, we will create our own Android application with facts about Chuck Norris using Kotlin. As an IDE we will use Android Studio. In this example, you can learn how to perform network requests on Kotlin and how to use the OkHttp 3 library.
The facts will be obtained from a database of facts about Chuck Norris, which offers a simple API for obtaining random facts.
Add dependency for OkHttp
To make network calls, we will use the OkHttp library. So, we need to add the OkHttp 3.10 dependency to our file build.gradle
:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.ssaurel.chucknorrisfacts"
minSdkVersion 15
targetSdkVersion 27
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:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
}
Customize Android Manifest
Also, to make network calls, we need to add permission INTERNET
to the manifest of our application:
User Interface Creation
The next step is to create the user interface of our application. We will use ConstraintLayout as the root component of layout.
At the top of our user interface will be ImageView
with the face of Chuck Norris:
Then we add TextView
in which we will display the fact of Chuck Norris. To TextView
determine the dependence, which has it a little lower ImageView
. After that, add a button that will allow users to download a new fact, requesting it from the database. Finally, add ProgressBar
which will be centered on the screen.
As a result, we get the following layout for our user interface:
API Testing
Before writing the code in, MainActivity
we test the response returned by the database API. We will contact the following address: https://api.icndb.com/jokes/random .
This web service randomly returns a new fact about Chuck Norris on every call. By entering the URL into a web browser, you will get the following result:
So, we will need to parse the JSON response to get to the joke property , which contains the fact we need.
Writing Kotlin Code for MainActivity
Now it's time to write code for MainActivity
. We define a variable in which we store the API endpoint URL that we are going to call. Then we instantiate the object OkHttpClient
.
In the method, onCreate
MainActivity
we just need to set OnClickListener
a button that allows users to download new facts about Chuck Norris.
Access to the API is performed in a special method loadRandomFact
. We display ProgressBar
immediately before accessing the network. Then we create an object Request
with the endpoint URL in the parameter.
After that, we call the method newCall
on OkHttpClient
, passing it Request
as a parameter. To process the response, we call the method enqueue
with an instance Callback
in the parameter.
In the method, onResponse
we get the answer and then create JSONObject
. The final step is to get the joke property of the value object . After that, we can display the fact of Chuck Norrim in TextView
by encapsulating everything in a block runOnUiThread
to ensure that the user interface is updated in the user interface thread.
As a result, we get the following code for MainActivity
our Android application:
package com.ssaurel.chucknorrisfacts
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Html
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import org.json.JSONObject
import java.io.IOException
class MainActivity : AppCompatActivity() {
val URL = "https://api.icndb.com/jokes/random"
var okHttpClient: OkHttpClient = OkHttpClient()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
nextBtn.setOnClickListener {
loadRandomFact()
}
}
private fun loadRandomFact() {
runOnUiThread {
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()
val txt = (JSONObject(json).getJSONObject("value").get("joke")).toString()
runOnUiThread {
progressBar.visibility = View.GONE
factTv.text = Html.fromHtml(txt)
}
}
})
}
}
Launch the application
The best part of the lesson. When you start the application, you will get the following result: