1

I am struggling with this issue hours a go I am trying to call the API using retrofit using this code

interface HTTPService {

    @GET("/v1/breeds")
    suspend fun getbreeds():BreedList

}

class Retrofitclass {

    companion object{
        val BaseURL = "https://docs.thedogapi.com"
            fun getRetroInstance(): Retrofit {
                val gson = GsonBuilder()
                    .setLenient()
                    .create()

                return Retrofit.Builder()
                    .baseUrl(BaseURL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build()

            }
    }
}

In view Model:

  fun makeApiCall(){

        viewModelScope.launch(Dispatchers.IO){
       //  try {
                val retroinstance = Retrofitclass.getRetroInstance().create(HTTPService::class.java)
                val response = retroinstance.getbreeds()
            print("responce"+ response  )
                selectdatalist.postValue(response)
          // }  catch (e: Exception) {
            // print("error"+e.printStackTrace())
      // }
        }
    }

Any help or suggestion I tried to add these codes in build.gradle but nothing works for me:

compile 'com.squareup.retrofit2:retrofit:2.0.0-SNAPSHOT'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
    compile 'com.squareup.okhttp3:okhttp:3.0.1'

1 Answers1

0

The retrofit working for means of the Callback

class Retrofitclass {

companion object{
    val BaseURL = "https://docs.thedogapi.com"
    fun getRetroInstance(): Retrofit {
        val gson = GsonBuilder()
            .setLenient()
            .create()

        return Retrofit.Builder()
            .baseUrl(BaseURL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()

    }
}

}

interface HTTPService {

/**
*DataClass your class the of data what represent of data request of Api
/*
@GET("/v1/breeds")
suspend fun getbreeds(): Call<DataClass>

}

fun getApiBreeds {
   val retrofitClient = Retrofitclass.getRetrofit(PATH)
   val endPoint = retrofitClient.create(HTTPService::class.java)
   val callback = endPoint.getbreeds()

callback.enqueue(object : Callback<DataClass> {
    override fun onResponse(
        call: Call<DataClass>,
        response: Response<DataClass>
    ) {
        if (response.isSuccessful) {
            Log.d("Response", response.body().toString())
        }
    }

    override fun onFailure(call: Call<DataClass>, t: Throwable) {
        t.printStackTrace()
    }

})

}

//example DataClass

data class Breeds( var title: String, val state: String, ){}

dependencies

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

In ViewModel :

fun makeApiCall(){

    viewModelScope.launch(Dispatchers.IO){
        getApiBreeds()
}
jeremex
  • 66
  • 4