E
E
Eugesha19982021-03-27 20:09:51
Android
Eugesha1998, 2021-03-27 20:09:51

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
    }
}


myResponse code:
class MyResponse {
 lateinit var users: UserResponse
}


class UserResponse {
    @SerializedName("data") lateinit var userItems: List<UserItem>
}


UserItem code:
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
){}


UserApi interface:
interface UsersApi {
    @GET("https://reqres.in/api/users?page=1" + "&format=json" + "&extras=data")
    fun fetchContents(): Call<MyResponse>
}


Gives the following error:
605f675253d0e906731216.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
koperagen, 2021-03-27
@koperagen

What do you want to achieve by making lateinit fields?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question