Home > Blockchain >  retrofit response.body!! Kotlin android studio
retrofit response.body!! Kotlin android studio

Time:11-26

I have a problem with a retrofit with Kotlin the code is as follows:

MainActivity.kt

 val apiInterface = ApiInterface.create().getCountry()
        apiInterface.enqueue( object : Callback<List<data>>{
            override fun onResponse(call: Call<List<data>>?, response: Response<List<data>>?) {
                if(response?.body() != null){
                    val adapter = ArrayAdapter(this@MainActivity,android.R.layout.simple_spinner_item,response.body()!!)

                    binding.spCountry.adapter=adapter //spCountry is a spinner
                }
            }
            override fun onFailure(call: Call<List<data>>?, t: Throwable?) {}
        })

ApiInterface.kt

interface ApiInterface {
    @GET("/v3.1/all")
    fun getCountry() : Call<List<data>>
    companion object {
        var BASE_URL = "https://restcountries.com/v3.1/all/"
        fun create() : ApiInterface {
            val retrofit = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(BASE_URL)
                .build()
            return retrofit.create(ApiInterface::class.java)
        }
    }
}

data.kt

data class data(
    @SerializedName("name") val name: name
)
data class name(
    @SerializedName("common") val common: String
)

The result I get is this in the spinner and I just want the name of the country

enter image description here

CodePudding user response:

You can perform a simple map operation to convert your List<data> to List<String>.

val originalList: List<data> = // Response from retrofit
val newList: List<String> = originalList.map { it.name.common }

try it yourself

  • Related