Backkotlin android

Real-Time Data in Android Apps Using Kotlin

02 September 2024


In this Kotlin Android tutorial, we'll explore how to fetch live currency exchange rates from an API using Kotlin. We'll utilise Retrofit for making API calls and OkHttp for handling HTTP client configurations. By the end of this guide, you'll have a Kotlin program. It will retrieve live currency data and log the result.

Downloading and working on Android Studio

Let us download and install Android Studio now.

Download Android Studio.

Go to the Android Studio download page. Click "Download Android Studio." Then, follow the prompts to download the installer.

Install Android Studio.

Open the downloaded installer file. Follow the instructions to install Android Studio. Choose the standard installation option. It includes the necessary tools, like the Android SDK and the Android Emulator.

Set up Android Studio for Kotlin development.

Start Android Studio.

Launch Android Studio after installation. You will see the "Welcome to Android Studio" screen.

Create a New Project

We need to click on "Start a new Android Studio project." Select the "Empty Activity" template and click "Next." Configure your project settings:

1) Name: Enter a name for your project.

2) Package name: Ensure it's unique.

3) Save location: Choose where to save your project.

4) Language: Select Kotlin.

5) Minimum API level: Choose the minimum Android version you want to support.

6) Click "Finish" to create your project. 

7) Configure the project

Update Dependencies

Open the build.gradle (Project: <your_project_name>) file. Ensure you have the Google and Maven Central repositories included.

Add Dependencies

Open the build—Gradle (Module: app) file. Add dependencies for HTTP requests and JSON handling. Sync your project by clicking "Sync Now" in the notification bar. Designing the User Interface.

Create UI layouts

Navigate to the res/layout folder. Open activity_main.xml. You can design your UI by dragging and dropping UI elements (e.g., EditText, Button, TextView) from the palette into the design editor.

Let's Code

Setting Up the Project

To get started, create a Kotlin project in your favorite IDE. Ensure you have the necessary dependencies for Retrofit, OkHttp, and Gson in your build.gradle file:

implementation' com.squareup.retrofit2:retrofit:2.9.0'
implementation' com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.1'

Define Data Models

We must define data models to handle the API response. They should represent the JSON response's structure. We have LiveCurrencyResponse and Quote classes. They will store the API data, allowing us to use the information in our Kotlin code.

data class LiveCurrencyResponse(val quotes: List<Quote>)
data class Quote(val ask: Double, val bid: Double, val mid: Double, val base_currency: String, val quote_currency: String)

Create the API interface.

Next, define the interface for making API calls using Retrofit. The LiveCurrencyApiService interface has a method, getLiveCurrencyData. It fetches live currency rates using an API key and a currency pair.

interface LiveCurrencyApiService {
    @GET("live")
    fun getLiveCurrencyData(@Query("api_key") apiKey: String, @Query("currency") currencyPair: String): Call<LiveCurrencyResponse>
}

Configure OkHttpClient

We'll use OkHttpClient to manage our HTTP connection. It has timeouts for connecting, writing, and reading. This setup ensures our program can handle network delays without timing out.

val client = OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .build()

Set Up Retrofit

With OkHttpClient configured, we can now set up Retrofit to make HTTP requests to the API. Retrofit simplifies HTTP requests. It uses Gson to convert JSON responses to Kotlin objects.

val retrofit = Retrofit.Builder()
    .baseUrl("https://marketdata.tradermade.com/api/v1/")
    .client(client)
    .addConverterFactory(GsonConverterFactory.create())
    .build()

Fetch Live Currency Data

Now that everything is set up, let's make the API call to fetch live currency data. We'll create an instance of LiveCurrencyApiService. Then, we'll call it and handle the response.

val liveCurrencyService = retrofit.create(LiveCurrencyApiService::class.java)
val liveCurrencyCall = liveCurrencyService.getLiveCurrencyData(apiKey, "$baseCurrency$quoteCurrency")
val liveCurrencyResponse = liveCurrencyCall.execute()

Handle the API Response

We checked if the API request was successful. If it was, we extract the quote data and print the ask, bid, and mid rates:

if (liveCurrencyResponse.isSuccessful) {
    val quote = liveCurrencyResponse.body()?.quotes?.firstOrNull()
    if (quote != null) {
        val resultText = "Ask: ${quote.ask}\nBid: ${quote.bid}\nMid: ${quote.mid}"
        println(resultText)
    } else {
        println("No quotes found.")
    }
} else {
    println("Live currency request failed with code: ${liveCurrencyResponse.code()}")
}

Clean Up Resources

After the program finishes, we clean up resources. We shut down the OkHttpClient's dispatcher and connection pool. This closes any open resources and is a good practice with network connections.

client.dispatcher.executorService.shutdown()
client.connectionPool.evictAll()

Running the Program

When you run the program, it will fetch real-time data for the specified pair. It will print the ask, bid, and mid prices. Here's an example of the expected output:

Ask: 1.1845
Bid: 1.1839
Mid: 1.1842

Note: Similarly, we can fetch forex historical data and currency conversions using the same process, changing the query.

Conclusion

This Kotlin Android tutorial showed how to set up a Kotlin project to fetch live currency exchange rates using Retrofit and OkHttp. You've learned to configure an HTTP client, make API calls, handle responses, and manage resources. Now, you can expand this base to build more complex applications involving real-time data.

If you have any questions or suggestions, feel free to reach out! Happy coding!