Kotlin no text from api
I wanted to load my text from an api in kotlin. I get no errors or exeptions only i get no text.
I got the info from this api: https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR
and i pushed my code to this github repo: https://github.com/robbe-delsoir/Herexamen
This is my MainActivity:
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.StringBuilder
const val Base_Url = "https://min-api.cryptocompare.com/"
class MainActivity : AppCompatActivity() {
private lateinit var txtId: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getMyData();
val secondActButton = findViewById<Button>(R.id.buttonAbout)
secondActButton.setOnClickListener{
val intent = Intent(this, activity_about::class.java)
startActivity(intent)
}
txtId = findViewById(R.id.txtId)
}
private fun getMyData() {
val retrofitBuilder = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Base_Url)
.build()
.create(ApiInterface::class.java)
val retrofitData = retrofitBuilder.getData()
retrofitData.enqueue(object : Callback<MyData?> {
override fun onResponse(call: Call<MyData?>, response: Response<MyData?>) {
val responseBody = response.body()
val myStringBuilder = StringBuilder()
if (responseBody != null) {
myStringBuilder.append(responseBody.BTC)
}
txtId.text = myStringBuilder
}
override fun onFailure(call: Call<MyData?>, t: Throwable) {
Log.d("MainActivity", "onFailure: "+t.message)
}
})
}
}
This is the MyData class:
data class MyData(
val BTC: Double,
val EUR: Double,
val USD: Double
)
This is my ApiInterface:
import retrofit2.Call
import retrofit2.http.GET
interface ApiInterface {
@GET("data/price?fsym=ETH&tsyms=BTC,USD,EUR")
fun getData(): Call<MyData>
}
Ànd this is my textview where it needs to come in:
<TextView
android:id="@+id/txtId"
android:text="Hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="212dp"
android:layout_marginTop="314dp"
android:layout_marginEnd="167dp"
android:layout_marginBottom="398dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
I hope someone could help me! Thanks!
you need to set Internet Permission on AndroidManifest.XML
<uses-permission android:name="android.permission.INTERNET" />