How to create a Numbers Fact app with Kotlin and NumbersAPI

Ismail Nurudeen
May 8, 2019 · 4 min read

In this article we would be building a simple fun and educational app that allows you get interesting facts about different numbers,dates and years.

The process is pretty easy as NumbersAPI has already done the heavy lifting by providing us with all the facts we need,all we have to do is query the NumbersAPI and display the result in our app… sounds interesting right?

lets get started!

Here’s a demo of what we would be building…

“Numbers have life; they’re not just symbols on paper.” — Shakuntala Devi

We would be using Kotlin for the purpose of this tutorial because it’s simple and straight forward to use (You can use Java if you like).

You would need a little knowledge about making HTTP requests in android because that’s basically what we would be doing (But don’t worry,you can easily follow along).

Open up Android studio,create a new project and call it whatever you like, I would be naming mine NumbersFact (remember to add Kotlin support).

Let’s create our layout which is made up of an EditText to enter our number,a Button to make the request,a TextView to display our result and lastly a progress bar.

Go to the activity_main.xml layout and type out the following lines of code. (You’re free to CTRL + C and CTRL + V )

Now let’s connect our layout to our activity.

But first,let’s talk about the numbers API.
The numbers API enables us to make request for different types of number facts, e.g Trivia,Dates,Years and Math facts.
By default it returns a Trivia fact.

To request for fact about a number,we simply write the numbers API endpoint and attach the number to it.
i.e http://numbersapi.com/47
It would return a fact about the number 47 in plain text but we can add ?json parameter at the end to get our result in JSON format

i.e http://numbersapi.com/47?json

For the sake of this tutorial,we would be working with plain text…
You can explore numbersapi.com for more options.

Open up MainActivity.java,create a companion object to hold our API endpoint (equivalent to a Static in Java)

companion object{
val endpoint=”http://numbersapi.com/"
}

Now,let’s create our makeQuery method.

fun makeQuery(num: String): String {
var queryResult: String
try {
val url = URL(“$endpoint$num”)
val urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = “GET”
urlConnection.readTimeout = 10000
urlConnection.connectTimeout = 15000
urlConnection.connect()
if (urlConnection.responseCode == 200) {
val inputStream = urlConnection.inputStream
val isr = InputStreamReader(inputStream, Charsets.UTF_8)
val scanner = Scanner(isr)
val sb = StringBuilder()
while (scanner.hasNext()) {
sb.append(scanner.nextLine())
}
queryResult = sb.toString()
inputStream.close()
} else {
queryResult = “No result found!”
Log.i(“RESPONSE_CODE”, “URL:${url.path} CODE:${urlConnection.responseCode}”)
}
} catch (e: Exception) {
queryResult = “No result found!… Try again”
//To display a toast on the main thread
runOnUiThread { Toast.makeText(this@MainActivity, e.localizedMessage, Toast.LENGTH_LONG).show() }
}
return queryResult
}

The above method basically takes in the number we want to query as parameter then makes the query and returns the result if available or returns *No result found*.

Since Android doesn’t allow network calls on the main or UI thread,we would create a class that extends AsyncTask to make the network call in background thread.

Let’s call it QueryTask,it would be an inner class of the MainActivity.

private inner class QueryTask(val resultTv: TextView, val pb: ProgressBar) : AsyncTask<String, Void, String>() {
override fun onPreExecute() {
super.onPreExecute()
resultTv.visibility = View.GONE
pb.visibility = View.VISIBLE
}
override fun doInBackground(vararg params: String): String {
return makeQuery(params[0])
}
override fun onPostExecute(result: String) {
super.onPostExecute(result)
resultTv.text = result
resultTv.visibility = View.VISIBLE
pb.visibility = View.GONE
}
}

It takes a TextView and ProgressBar as constructor parameter.
We query the API in doInBackground method and display our result in the onPostExecute method.

Next,When user clicks on the get fact button, we have to get a number from the user and pass it to the makeQuery method through the AsyncTask we created.

Go to your onCreate method and add the following code.

get_fact_btn.setOnClickListener {
val qt = QueryTask(result_tv, progress_bar)
val factNum = fact_num_input.text.toString()
if (factNum.isNotEmpty()) {
qt.execute(factNum)
} else {
Toast.makeText(this@MainActivity, “Enter a number…”,Toast.LENGTH_SHORT).show()
}
}

The above code retrieves input from our fact_num_input EditText,checks if it’s not empty and starts the asyntask when the get_fact_btn is clicked.

Now your MainActivity.java should look like this…

Don’t forget to add internet permission to your AndroidManifest.xml file.

<uses-permission android:name=”android.permission.INTERNET”/>

Run the app to verify that it works.

And there you have it! your own Numbers Fact App.
Of Course you can do so much more with the Numbers API.
To see the Numbers API in full use,you can check out my Numbers Fact app on Play Store.

Get the complete code for this tutorial here on Github
If you encounter any problem, let me know in the comments section below.

Follow me on Twitter @Teenmutantcoder and Facebook ismailnurudeen01

Thanks!

Ismail Nurudeen

Written by

Triple ‘A’ Developer (Android | Artificial Intelligence | Augmented Reality). Ex. Android Dev @hotelsng | Developer 🥑 @devloopng | Under 20 🔥

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade