Answer the question
In order to leave comments, you need to log in
Android Kotlin getting json via Retrofit2?
Hello everyone, I ran into this problem: I have a url where a json object with users is stored and I need to get them out of there, but I get an empty response, which causes errors that the fields are not initialized.
Service code:
private const val TAG = "UserFetchr"
class UserFetchr {
private val usersApi: UsersApi
init {
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://reqres.in/")
.addConverterFactory(GsonConverterFactory.create())
.build()
usersApi = retrofit.create(UsersApi::class.java)
}
fun fetchContents(): LiveData<List<UserItem>> {
val responseLiveData: MutableLiveData<List<UserItem>> = MutableLiveData()
val usersRequest: Call<MyResponse> = usersApi.fetchContents()
usersRequest.enqueue(object : Callback<MyResponse> {
override fun onFailure(call: Call<MyResponse>, t: Throwable) {
Log.e(TAG, "Failde to fetch users", t)
t.printStackTrace()
}
override fun onResponse(call: Call<MyResponse>,
response: Response<MyResponse>) {
Log.d(TAG, "Response received!")
val myResponse: MyResponse? = response.body()
Log.d(TAG, "${response}")
val userResponse: UserResponse? = myResponse?.users
var userItems: List<UserItem> = userResponse?.userItems
?: mutableListOf()
userItems = userItems.filterNot {
it.urlImage.isBlank()
}
responseLiveData.value = userItems
}
})
return responseLiveData
}
}
class MyResponse {
lateinit var users: UserResponse
}
class UserResponse {
@SerializedName("data") lateinit var userItems: List<UserItem>
}
data class UserItem(
@SerializedName("id") var id: Int,
@SerializedName("avatar") var urlImage: String,
@SerializedName("first_name") var firstName: String,
@SerializedName("last_name") var lastName: String,
@SerializedName("email") var email: String
){}
interface UsersApi {
@GET("https://reqres.in/api/users?page=1" + "&format=json" + "&extras=data")
fun fetchContents(): Call<MyResponse>
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question