Leave a rating/review
There’s not that much else to practice, as you’ve mastered nearly everything in Android networking.
So, in the final challenge of this part, you’ll implement the last request in the RemoteApi class, the request to delete a task or note! :] You also have to utilize the Result class, to have a clean way of handling the response from the server.
If you check the documentation for the request, you have to use a DELETE REST method, instead of a POST or GET like you did before.
Here’s a hint: even though this is a new REST method, the implementation in Retrofit isn’t that much different, you simply have to use a different annotation!
That’s it! Now pause the video, and solve the challenge! Then once you’re done, unpause the video, and compare the two solutions! Good luck! :]
Demo
Alright, this request is very similar to how the register or complete note requests work. Start by creating a new class called DeleteNoteResponse, in the model package:
@Serializable
class DeleteNoteResponse(val message: String)
It holds a message, which will be “Note deleted!” in case the request is successful! Then head over to the RemoteApiService.kt, and add the following API call:
@DELETE("/api/note")
fun deleteNote(@Query("id") noteId: String): Call<DeleteNoteResponse>
It’s similar to how the complete task request works, as it’s just a different REST method, to explicitly state that this is a delete call.
REST methods should describe their requests, so using DELETE here instead of a POST, which would also work, is more descriptive. To implement the call, go to the RemoteApi class, and fill in the function, like so:
fun deleteTask(taskId: String, onTaskDeleted: (Result<String>) -> Unit) {
apiService.deleteNote(taskId).enqueue(object : Callback<DeleteNoteResponse> {
override fun onFailure(call: Call<DeleteNoteResponse>, error: Throwable) {
onTaskDeleted(Failure(error))
}
override fun onResponse(call: Call<DeleteNoteResponse>,
response: Response<DeleteNoteResponse>) {
val completeNoteResponse = response.body()
if (completeNoteResponse?.message == null) {
onTaskDeleted(Failure(NullPointerException("No response!")))
} else {
onTaskDeleted(Success(completeNoteResponse.message))
}
}
})
}
Similar to other requests, you need to handle the failed cases and the successful case. Also notice the taskId parameter in the function signature, which you had to add.
Finally, head over to the TaskOptionsDialogFragment, wrap the call in the network check, and change the way the callbacks look, to the following:
networkStatusChecker.performIfConnectedToInternet {
remoteApi.deleteTask(taskId) { result ->
if (result is Success) {
taskOptionSelectedListener?.onTaskDeleted(taskId)
}
dismissAllowingStateLoss()
}
}
That’s all! :] Run the project and delete a note or two. Then restart the app, and check if the notes are still there!
Awesome! You now have a wholesome API, and you’re a master of all things networking! :]