I try to make a recycler view with the name and picture of the pokemon, but it doesn't work, I don't understand why, the requests are not done because the pokemon list is never filled. I make a loop for calls because what I want is the name and picture of the pokemon, because when I ask for a list of pokemon objects only bring the name and the url of the complete object and is the best way that has occurred to me, I would appreciate if you can give me a hand, thank you very much.
This is the code of my mainActivity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initRecycler()
obtenerPokemons()
}
private fun initRecycler(){
pokemonAdapter = PokemonAdapter(pokemons)
linearLayoutManager = LinearLayoutManager(this)
binding.recyclerpokemon.apply {
setHasFixedSize(true)
layoutManager = linearLayoutManager
adapter = pokemonAdapter
}
}
private fun obtenerPokemons() {
for (i in 1..30) {
searchByName(i)
}
pokemonAdapter.setPokemons(pokemons)
}
private fun getRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://pokeapi.co/api/v2/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
private fun searchByName(query:Int){
CoroutineScope(Dispatchers.IO).launch {
val call = getRetrofit().create(PokemonService::class.java).getPokemon("pokemon/$query")
val pokemonsResp = call.body()
runOnUiThread {
if(call.isSuccessful) {
pokemons.add(pokemonsResp)
}else{
Toast.makeText(this@MainActivity, "No encuentro eso", Toast.LENGTH_SHORT).show()
}
}
}
}
}
This is the pokemon object code:
data class Pokemon (
@SerializedName("id" ) var id : Int,
@SerializedName("name" ) var name : String,
@SerializedName("sprites" ) var sprites : Sprites,
)
data class Sprites (
@SerializedName("back_default" ) var backDefault : String,
@SerializedName("front_default" ) var frontDefault : String,
)
And this is the code of my service:
interface PokemonService {
@GET
suspend fun getPokemon(@Url url:String) : Response<Pokemon?>
}