Search code examples
kotlinretrofit

Retrofit response body returning null


I've been stuck with this problem for some time now, and I can't seem to find the problem especially when all I did was following a guide online.

I'm trying to make a POST request, and receive a response in exchange:

Request body:

{
    "Email":"test@gmail.com",
    "firebaseUid":"Test_UID",
    "IsBanned":1
}

Response body: `

{
    "Email": "test@gmail.com",
    "UserId": 7
}

So basically whenever I submit a request to /users/ to create an account, I get both the email and UserId returned.

data class UserLogin(
    @SerializedName("Email") val Email: String,
    @SerializedName("UserId") val UserId: Int?,
    @SerializedName("IsBanned") val IsBanned: Boolean?,
    @SerializedName("firebaseUid") val firebaseUid: String?
)



object ServiceBuilder {
        private val client = OkHttpClient.Builder().build()

        private val retrofit = Retrofit.Builder()
            .baseUrl("http://10.0.2.2/8000/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()

        fun<T> buildService(service: Class<T>): T{
            return retrofit.create(service)
        }
}

class RestApiService {
    fun addUser(userData: UserLogin, onResult: (UserLogin?) -> Unit){
        val retrofit = ServiceBuilder.buildService(RestApi::class.java)
        retrofit.addUser(userData).enqueue(
            object : Callback<UserLogin> {
                override fun onFailure(call: Call<UserLogin>, t: Throwable) {
                    Log.d("Failed retrofit",t.message.toString())
                    onResult(null)

                }
                override fun onResponse( call: Call<UserLogin>, response: Response<UserLogin>) {
                    val addedUser = response.body()
                    onResult(addedUser)

                }
            }
        )
    }

}

onFailure doesn't seem to be printing anything on the console. I'm calling the API from a button like this and both Email and UserId keep returning null for some reason:

`

val apiService = RestApiService()
val userInfo = UserLogin(UserId = null,firebaseUid = "TestTestTest", IsBanned = false, Email = "test@gmail.com");

apiService.addUser(userInfo){
    Log.d("Retrofit user added", it?.Email.toString())
}

`

I tried to:

  • Set default values for the data class members.
  • Tried to check if response is successfull, and then print the errorBody if not. That didn't help either. I'm getting unreadable errors like $1@9afe35d instead.

Everything seem to be working fine when I do requests manually with POSTMAN.


Solution

  • It turned out there was nothing with the code. I just typed the port the wrong way and used a / instead of :

       private val retrofit = Retrofit.Builder()
            .baseUrl("http://10.0.2.2:8000/") // this
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()