I am new to the Kotlin langue and have tried to learn from various YouTube tutorials and other articles online. I took what I learned from a video and followed the steps to create a straightforward currency converter using a free API currency rate. The following is the function for getting the result of the currency rate.
private fun getApiResult(){
var baseCurrency = "EUR"
var convertedToCurrency = "USD"
var conversionRate = 0f
if(et_firstConversion != null && et_firstConversion.text.isNotEmpty() && et_firstConversion.text.isNotBlank()){
val API = "http://data.fixer.io/api/latest?access_key=a22e608d4311d9ade9221a2abadb111e&symbols=$convertedToCurrency,AUD,CAD,PLN,MXN&format=1"
if(baseCurrency == convertedToCurrency){
Toast.makeText(applicationContext,"Cannot convert the same currency", Toast.LENGTH_SHORT).show()
} else {
GlobalScope.launch(Dispatchers.IO){
try {
val apiResult = URL(API).readText()
val jsonObject = JSONObject(apiResult)
conversionRate = jsonObject.getJSONObject("rates").getString(convertedToCurrency).toFloat()
Log.d("Main", "$conversionRate")
Log.d("Main", apiResult)
withContext(Dispatchers.Main){
val text = ((et_firstConversion.text.toString().toFloat()) * conversionRate).toString()
et_secondConversion?.setText(text)
}
} catch (e:Exception){
Log.e("Main", "$e")
}
}
}
}
}
The problem is that the Exception gets triggered and says the following: cleartext http traffic is not permitted
In the Manifest.xml, I have set the following:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
The free API is very restricted toward free users and does not allow for Https
. I am also not sure if the coding(the way it is implemented) is doing what I am trying to achieve in the right way. Any suggestions/improvements to the code are appreciated.
Android 5.0 API 21