Reputation: 205
I tried to get json from the https://github.com/users. I want to show username : yehezkiell like https://github.com/yehezkiell. The retrofit showing success result, but its always return null. I'm new in this retrofit, please help
this my code
val postService = DataRepository.create()
postService.getUser("yehezkiell").enqueue(object : Callback<Users>{
override fun onFailure(call: Call<Users>?, t: Throwable?) {
Log.e("retrofitnya","gagal ${t}")
}
override fun onResponse(call: Call<Users>?, response: Response<Users>?) {
Log.e("retrofitnya","berhasil")
val data = response?.body()
Log.e("retrofitnya","berhasil ${data?.name}")
}
})
Retrofit Instance
interface RetrofitInstance {
@GET("users/{username}")
fun getUser(@Path("username") username:String ): Call<Users>
}
Data repo
object DataRepository {
fun create(): RetrofitInstance {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://github.com")
.build()
return retrofit.create(RetrofitInstance::class.java)
}
}
Users.kt
open class Users {
@SerializedName("name")
@Expose
open var name: String? = null
@SerializedName("username")
@Expose
open var username: String? = null
@SerializedName("email")
@Expose
open var email: String? = null
}
Upvotes: 1
Views: 646
Reputation: 205
I solved this by myself, actually its my silly miss understanding which is that end point is wrong.
In my wrong code
object DataRepository {
fun create(): RetrofitInstance {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://github.com")
.build()
return retrofit.create(RetrofitInstance::class.java)
}
}
That wrong end point is
https://github.com
The true one is
https://api.github.com/
Upvotes: 0
Reputation: 72
For debugging process, instead of de-serialization to Users
object immediately after response, should we do somethings like these? :
interface RetrofitInstance {
@GET("users/{username}")
fun getUser(@Path("username") username: String): Call<String>
}
override fun onResponse(call: Call<String>?, response: Response<String>?) {
val responseBody = response?.body() ?: ""
Log.e("retrofitnya","response body as string = ${responseBody}")
}
Users
after that) do manually de-serialize it.val user: Users = Gson().fromJson(responseBody, Users::class.java)
If it is not too confidential, plz give us how you declare that Users
data object like, for example, this Foo and Bar.
data class Foo(
@SerializedName("bar") val bar: Bar?
)
data class Bar(
@SerializedName("name") val name: String?
)
Upvotes: 1