No Description

MainActivity.kt 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package com.example.trefletest
  2. import android.os.Bundle
  3. import android.widget.ImageView
  4. import android.widget.TextView
  5. import android.widget.Toast
  6. import androidx.appcompat.app.AppCompatActivity
  7. import com.example.trefletest.models.Plant
  8. import com.squareup.picasso.Picasso
  9. import okhttp3.OkHttpClient
  10. import retrofit2.Call
  11. import retrofit2.Callback
  12. import retrofit2.Response
  13. import retrofit2.Retrofit
  14. import retrofit2.converter.gson.GsonConverterFactory
  15. private const val TOKEN = "cMyugCJvk-U_xoi31FVBgoEqZiuRnDYpP8fv8Vfiejg"
  16. private const val BASE_URL = "https://trefle.io/"
  17. var slug: String = "prunella-vulgaris"
  18. object ServiceBuilder {
  19. val client = OkHttpClient.Builder().build()
  20. var retrofit: Retrofit = Retrofit.Builder()
  21. .baseUrl(BASE_URL)
  22. .addConverterFactory(GsonConverterFactory.create())
  23. .client(client)
  24. .build()
  25. fun <T> buildService(service: Class<T>): T {
  26. return retrofit.create(service)
  27. }
  28. }
  29. class MainActivity : AppCompatActivity() {
  30. override fun onCreate(savedInstanceState: Bundle?) {
  31. super.onCreate(savedInstanceState)
  32. setContentView(R.layout.activity_main)
  33. val nom_planta = findViewById(R.id.plant_name) as TextView
  34. //val uri_test = findViewById(R.id.uri) as TextView Por si acaso
  35. val nom_sci = findViewById(R.id.sci_name) as TextView
  36. val year = findViewById(R.id.year) as TextView
  37. val author = findViewById(R.id.author) as TextView
  38. val imagen_planta = findViewById(R.id.plantview) as ImageView
  39. nom_planta.text = ("Loading...")
  40. nom_sci.text = ("Loading...")
  41. year.text = ("Loading...")
  42. author.text = ("Loading...")
  43. val request = ServiceBuilder.buildService(TrefleService::class.java)
  44. val call = request.getPlants(slug, TOKEN)
  45. val uri = call.request().url.toString()
  46. //uri_test.text = (uri)
  47. call.enqueue(object : Callback<Plant> {
  48. override fun onFailure(call: Call<Plant>, t: Throwable) {
  49. Toast.makeText(this@MainActivity, t.message, Toast.LENGTH_LONG).show()
  50. }
  51. override fun onResponse(call: Call<Plant>, response: Response<Plant>) {
  52. if (response.isSuccessful) {
  53. val planta: Plant = response.body()!!
  54. nom_planta.text = planta.data.commonName.toString()
  55. nom_sci.text = planta.data.scientificName
  56. year.text = planta.data.year.toString()
  57. author.text = planta.data.author
  58. Picasso.get().load(planta.data.imageUrl).into(imagen_planta)
  59. }
  60. else{
  61. Toast.makeText(this@MainActivity, response.message(), Toast.LENGTH_LONG).show()
  62. }
  63. }
  64. })
  65. }
  66. }