Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Add Queries to Calls

The student materials have been reviewed and are updated as of July 2022.

Introduce the Query annotation, to send query parameters to the server. Learn about query URL segments. Implement a second call.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Up until now, you only sent data as the body parameter, when you had a whole object to send. But sometimes, you don’t need entire objects, you just need to filter or search by one or two parameters. In that case, you often use queries.

@POST("/api/note/complete")
fun completeTask(
    @Header("Authorization") token: String,
    @Query("id") noteId: String): Call<ResponseBody>

@POST("/api/note")
fun addTask(
    @Header("Authorization") token: String,
    @Body request: RequestBody): Call<ResponseBody>
class CompleteNoteResponse(val message: String?)
apiService.completeTask(App.getToken(), taskId).enqueue(object : Callback<ResponseBody> {
  override fun onFailure(call: Call<ResponseBody>, error: Throwable) {
    onTaskCompleted(error)
  }

  override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
    val jsonBody = response.body()?.string()

    if (jsonBody == null) {
      onTaskCompleted(NullPointerException("No response!"))
      return
    }

    val completeNoteResponse = gson.fromJson(jsonBody, CompleteNoteResponse::class.java)
    if (completeNoteResponse?.message == null) {
      onTaskCompleted(NullPointerException("No response!"))
    } else {
      onTaskCompleted(null)
    }
  }
})
val body = RequestBody.create(
    MediaType.parse("application/json"), gson.toJson(addTaskRequest)
)

apiService.addTask(App.getToken(), body).enqueue(object : Callback<ResponseBody> {
  override fun onFailure(call: Call<ResponseBody>, error: Throwable) {
    onTaskCreated(null, error)
  }

  override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
    val jsonBody = response.body()?.string()

    if (jsonBody == null) {
      onTaskCreated(null, NullPointerException("No response!"))
      return
    }

    val data = gson.fromJson(jsonBody, Task::class.java)

    if (data == null) {
      onTaskCreated(null, NullPointerException("No response!"))
      return
    } else {
      onTaskCreated(data, null)
    }
  }
})

Reviews

Comments