Created
December 20, 2019 14:11
-
-
Save antonis/758d7de541ef32bccf03a44bc5db27a9 to your computer and use it in GitHub Desktop.
Fetches exchange rate from the European Central Bank https://exchangeratesapi.io
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import com.google.gson.Gson | |
| import com.google.gson.JsonObject | |
| enum class CurrencySymbol { | |
| EUR, CAD, HKD, ISK, PHP, DKK, HUF, CZK, AUD, RON, SEK, | |
| IDR, INR, BRL, RUB, HRK, JPY, THB, CHF, SGD, PLN, BGN, | |
| TRY, CNY, NOK, NZD, ZAR, USD, MXN, ILS, GBP, KRW, MYR | |
| } | |
| /** | |
| * Fetches exchange rate from the European Central Bank https://exchangeratesapi.io | |
| * @param base base currency | |
| * @param currency target currency | |
| * @return The exchange rate | |
| */ | |
| fun getRate(base: CurrencySymbol, currency: CurrencySymbol): Double? { | |
| return try { | |
| val url = "https://api.exchangeratesapi.io/latest?base=$base&symbols=$currency" | |
| val json = java.net.URL(url).readText() | |
| val jsonObject = Gson().fromJson<JsonObject>(json, JsonObject::class.java) | |
| jsonObject["rates"].asJsonObject[currency.name].asDouble | |
| } catch (e: Exception) { | |
| null | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment