Search code examples
androidgsonretrofit2

Response from retrofit is null when Spring Boot server has fulfilled the request


I have the following code for my retrofit code:

SwapItApi.kt

interface SwapItApi {
    @Headers("Content-Type: application/json")
    @POST("customer/add")
    fun addCustomer(@Body customerData: Customer): Call<Customer>
}

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

    private val retrofit = Retrofit.Builder()
        .baseUrl("http://192.168.4.29:8102/api/")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build()

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

SwapItApiService.kt

class SwapItApiService {
    fun addUser(customerData: Customer, onResult: (Customer?) -> Unit) {
        val retrofit = ServiceBuilder.buildService(SwapItApi::class.java)

        retrofit.addCustomer(customerData).enqueue(
            object: Callback<Customer> {
                override fun onFailure(call: Call<Customer>, t: Throwable) {
                    onResult(null)
                }

                override fun onResponse(call: Call<Customer>, response: Response<Customer>) {
                    val customer = response.body()

                    onResult(response.body())
                }
            }
        )
    }
}

RegistrationContent.kt

...
private fun addCustomer(customerData: Customer, scope: CoroutineScope, snackbarHostState: SnackbarHostState) {
    val apiService = SwapItApiService()

    var convertedDOB = ""

    convertedDOB += customerData.dob!!.substring(4, 8)
    convertedDOB += "-"
    convertedDOB += customerData.dob!!.substring(2, 4)
    convertedDOB += "-"
    convertedDOB += customerData.dob!!.substring(0, 2)



    val customer = Customer(
        id = null,
        username = customerData.username,
        password = customerData.password,
        dob = convertedDOB,
        firstName = customerData.firstName,
        lastName = customerData.lastName,
        isActive = null,
    )

    apiService.addUser(customer) {
        if(it?.id != null) {
            scope.launch {
                snackbarHostState.showSnackbar("ID: ${it.id}, Username: ${it.username}")
            }
        }
        else {
            scope.launch {
                snackbarHostState.showSnackbar("Error registering new customer.")
            }
        }
    }
}
...

So when I call RegistrationContent.addCustomer(...), it calls SwapItApiService.addCustomer(...) which returns successfully and when looking at my database table, the entry I've sent has been created, however, RegistrationContent.addCustomer(...)'s snackbar displays "Error registering new customer".

After breakpointing, I found that it?.id is null. So my code does not seem to be waiting.

I'm new to this so I'm unsure what to do in order to get this to work properly.


Solution

  • So after quite a bit of tinkering (and I mean a lot), it turns out that I as

    As side note: Gson mainly targets Java programs. It might work fine for Kotlin in most cases, but for some situations it does not work very well, e.g. null-safety, see for example this issue. Maybe consider using a JSON library with explicit Kotlin support instead. – Marcono1234

    Had stated, I needed to change over to Jackson. I then realised that in my Customer class, I was not using @JsonProperty on the relevant entries... Oh and I also needed to add a @JsonIgnoreProperties(ignoreUnknown = true) with my response from the server and with some buts within Customer after adding them, it now works as expected.