我想从Kotlin中的api加载我的文本。我没有得到错误或异常,只有我没有得到文本。
我从这个api得到的信息:https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR
然后我把我的代码推到了这个github repo上:https://github.com/robbe-delsoir/Herexamen
这是我的主要活动:
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)
}
})
}
}
这是MyData类:
data class MyData(
val BTC: Double,
val EUR: Double,
val USD: Double
)
这是我的ApiInterface:
import retrofit2.Call
import retrofit2.http.GET
interface ApiInterface {
@GET("data/price?fsym=ETH&tsyms=BTC,USD,EUR")
fun getData(): Call<MyData>
}
这是我的textview,它需要进来:
<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" />
我希望有人能帮助我!谢谢!
1条答案
按热度按时间gopyfrb31#
您需要在AndroidManifest.XML上设置互联网权限