DEV Community

Discussion on: Kotlin and retrofit network calls

Collapse
 
turicahoria profile image
TuricaHoria

I have a problem , I cannot get onto onResponse , I only get onFailure. This is my code:

object RetrofitClientInstance {

private val BASE_URL = "https://wger.de/api/v2/"

private val httpClient = OkHttpClient.Builder()

private val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build()

fun<T> buildService (service : Class <T>) : T {
    return  retrofit.create(service)
}
Enter fullscreen mode Exit fullscreen mode

}

interface APIServices {

@GET("exercise")
fun getAllExercises(): Call<MutableList<Exercise>>
Enter fullscreen mode Exit fullscreen mode

}

class ExerciseFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_exercises, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

    val request = RetrofitClientInstance.buildService(APIServices::class.java)

    val call = request.getAllExercises()
    call.enqueue(object : Callback<MutableList<Exercise>>
        {
            override fun onFailure(call: Call<MutableList<Exercise>>, t: Throwable) {
                Toast.makeText(context,"Couldn't fetch the exercises" , Toast.LENGTH_SHORT).show()
            }

            override fun onResponse(call: Call<MutableList<Exercise>>, response: Response<MutableList<Exercise>>) {

                if (response.isSuccessful)
                {
                    rv_exercices.apply {
                        setHasFixedSize(true)
                        layoutManager = LinearLayoutManager(context)
                        adapter = ExercisesAdapter(response.body()!!.toMutableList())
                    }
                }
            }
        }
    )
}
Enter fullscreen mode Exit fullscreen mode

}

Collapse
 
paulodhiambo profile image
Odhiambo Paul

in your code response.body()!! Should return a MutableList
Just pass response.body()!! to your recyclerview adapter instead of response.body()!!.toMutableList()