Build a Kotlin currency converter using exchange rate APIs
An Android currency converter turns changing exchange rates into immediate estimates for shopping, travel, and budgeting. A rates API supplies current currency pairs, but the app must also handle delayed updates, missing codes, and failed requests without showing a misleading result.
Australian users often work from AUD, whether comparing a Sydney flight with a Melbourne hotel or seeing local Woolworths or Coles prices in dollars. Default to the Australian dollar and show amounts in dollars. Separate the market rate from card charges, since an Australian bank may add a foreign transaction fee or apply a different rate at checkout.
The project uses Kotlin, Android Studio, MVVM, Retrofit, and Moshi in a repository-and-ViewModel design. It covers endpoint selection, JSON models, currency controls, calculation logic, timestamp handling, and offline fallback for beginners and experienced developers.
Plan the API and app architecture
Start with the rate provider’s JSON contract, not the screen layout. Responses usually contain a base currency, a map of target currency codes to numeric rates, and an update timestamp. Request AUD as the base, then read the required target code from that map. Document optional fields and unknown values because providers may use integers, decimal strings, or nulls.
Choose a source that matches the promise made by the interface. A central-bank reference feed is useful for daily estimates, while a commercial feed may support near real-time quotes. The target rate must refer to the same timestamp as the base rate. Record the provider name so a USD rate remains meaningful when its source and refresh time are known.
Keep Android-specific concerns out of the networking layer. A repository can expose supported currencies, rates, and freshness metadata. The ViewModel requests that data and exposes loading, success, and failure states to the activity or Compose screen. This separation makes conversion rules testable and lets a cached response replace a failed network response.
Configure Retrofit and JSON parsing
Add compatible Retrofit, Moshi, and OkHttp dependencies through the project’s version catalog, then create a data class matching the provider’s fields. Enable Moshi code generation with KSP or kapt. A typical response model might look like this:
@JsonClass(generateAdapter = true)
data class RatesResponse(
@Json(name = "base_code") val baseCode: String,
@Json(name = "conversion_rates") val rates: Map<String, Double>,
@Json(name = "time_last_update_unix") val updatedAt: Long
)
interface RatesApi {
@GET("latest")
suspend fun latest(
@Query("base") base: String
): RatesResponse
}
Adjust the annotations to the selected API while keeping the Kotlin property names readable. Add the INTERNET permission, use an HTTPS base URL, and create Retrofit with a Moshi converter. Keep the API key in local.properties for local experiments or behind a backend proxy for production, and never commit it to source control.
When a rates portal is also published through WordPress, repeated API calls can be reduced with a caching proxy; this reverse proxy caching guide shows the Nginx and Varnish arrangement. The Android client should still use a stable JSON endpoint rather than parsing WordPress markup.
Compare exchange rate data sources
Rate feeds are not interchangeable. A benchmark rate may suit personal budgeting, while a consumer application may need more currencies or faster updates. Compare update schedules, currency coverage, subscription requirements, request quotas, and commercial-use terms before choosing an endpoint.
| Rate source | Typical freshness | Access model | Best fit |
|---|---|---|---|
| Central-bank reference feed | Business-day updates | Often keyless; limited historical depth | Personal budgets and educational demos |
| Hosted free-tier API | Hourly or daily, depending on plan | Account, API key, and request quota | General consumer converters |
| Commercial market feed | Minute-level to streaming | Paid subscription and usage terms | Travel, finance, and live comparisons |
| Payment-network quote | Set near authorisation time | Requires issuer or network access | Reconciling completed transactions |
For an Australian audience, verify that AUD is a supported base and that USD, EUR, GBP, JPY, and NZD appear in the response. A keyless demonstration endpoint may suit a tutorial, but a published application needs predictable limits and an upgrade path. Present the feed as a market estimate rather than a guarantee of the rate an Australian card issuer will apply.
Build the conversion interface
Use an amount field, two currency selectors, a convert action, a result label, and a freshness message. An XML layout with AutoCompleteTextView works well for a traditional Android project, while a Compose dropdown offers the same flow in a modern interface. The conversion logic should remain independent of the UI toolkit.
Amount and currency controls
- Set the amount field to a decimal keyboard and keep raw input separate from formatted output.
- Populate both selectors from the supported currency list, with AUD selected initially.
- Allow currencies to be swapped without reloading unchanged rate data.
- Reject blank, negative, or non-finite values before making a conversion request.
Result and status details
- Format the converted value with an Australian locale and the appropriate currency symbol.
- Show the rate, provider, and update time in
Australia/Sydneytime, labelled AEST or AEDT. - Label results as market estimates rather than guaranteed card settlement amounts.
- Distinguish invalid codes, offline mode, expired data, and server errors.
When a response states that one AUD buys a quantity of the target currency, multiply the entered amount by that rate. Convert in the opposite direction by dividing by the rate, and return the original amount when both codes match. Use BigDecimal for arithmetic and round only for display, because repeatedly rounding a stored rate can produce visible errors.
The ViewModel should own the latest response and expose immutable screen state. Launch the repository call from viewModelScope, move blocking work to an appropriate background dispatcher, and cancel obsolete work when the base currency changes. This avoids duplicate requests during screen rotation and keeps the interface free from networking details.
Add caching, tests, and error handling
Treat each failure mode separately. A 401 usually indicates an invalid key, 429 means the request quota was exceeded, and a timeout or failed DNS lookup calls for a cached fallback. Malformed JSON may indicate a provider schema change, so a parsing failure should not replace a valid result with an empty screen. Give the user a specific recovery action instead of a generic failure message.
Cache the last successful rate payload with its timestamp in Room or DataStore. Set a sensible freshness window: a day-old reference rate can help with budgeting, but it should not appear as a live quote while the network is unavailable. WorkManager can schedule background refreshes, and the interface can show the older cached result until newer data arrives.
Test the conversion with MockWebServer, including AUD-to-USD, USD-to-AUD, identical currencies, an unknown code, a null rate, and a server error. Unit tests should cover rate direction, rounding, and stale-data decisions, while an instrumented test can confirm that results survive screen rotation. Before release, monitor endpoint reliability and schema changes, respect attribution requirements, and document that card issuer fees may differ from the displayed estimate.