Retrofit2 returns a null response body with GET

Viewed 47

I am using Retrofit2 to make a GET to github api but response.body() returns empty. I actually check the endpoints on Postman and it returns a body. I don't know what I am doing wrong that is causing this. I have included in the posts below my interface, viewmodel and my layout.

API interface

const val BASE_URL = "https://api.github.com/"
private val retrofit =
Retrofit.Builder().addConverterFactory(ScalarsConverterFactory.create()).baseUrl(
    BASE_URL
).build()

object GithubUserApi {
val retrofitService: GithubApiService by lazy {
    retrofit.create(GithubApiService::class.java)
}
}

interface GithubApiService {

@GET("search/users?sort=repositories&order=desc")
fun searchUsers(
    @Query("q") query: String,
    @Query("page") page: Int,
    @Query("per_page") itemsPerPage: Int
): Call<String>
}

ViewModel

class OverviewViewModel : ViewModel() {

private val _response = MutableLiveData<String>()
val response: LiveData<String>
    get() = _response

init {
    getGithubUsers()
}

private  fun getGithubUsers() {
    GithubUserApi.retrofitService.searchUsers("location:LOCATION", 1, 50).enqueue(
        object : Callback<String> {
            override fun onFailure(call: Call<String>, t: Throwable) {
                _response.value = "Failure: " + t.message
            }

            override fun onResponse(call: Call<String>, response: Response<String>) {
                _response.value = response.body()
            }
        }
    )

}
}

layout

<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>
    <variable
        name="overviewViewModel"
        type="com.example.OverviewViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.overview.OverviewFragment">


<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{overviewViewModel.response}"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
1 Answers

Allow Data Binding to Observe LiveData with the lifecycle of the fragment/activity.

binding.lifecycleOwner = this

That is what solved the problem for me... What an oversight!

Related