Android Networking: Fundamentals

Sep 6 2022 · Kotlin 1.6, Android 12, Android Studio Chipmunk | 2021.2.1 Patch 1

Part 2: Implement Retrofit Basics

15. Add Queries to Calls

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 14. Challenge: Create Retrofit Calls Next episode: 16. Implement the Moshi Parser

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 15. Add Queries to Calls

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

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

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