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.

Challenge: Request & Parse Data

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

Create another request with the HttpURLConnection, as practice, and use what you’ve learned so far to parse the data from JSON.

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.

To help you get a good understanding of Gson, parsing using libraries, and to repeat what you’ve learned about making requests using the HttpURLConnection, I’ve prepared a fun challenge for you!

private val networkStatusChecker by lazy {
  NetworkStatusChecker(activity?.getSystemService(ConnectivityManager::class.java))
}
networkStatusChecker.performIfConnectedToInternet {
  activity?.runOnUiThread {
    ...
  }
}
fun completeTask(taskId: String, onTaskCompleted: (Throwable?) -> Unit) { // added task ID
    Thread(Runnable {
      val connection = URL("$BASE_URL/api/note?id=$taskId").openConnection() as HttpURLConnection
  val connection = URL(
      "$BASE_URL/api/note/complete?id=$taskId"
  ).openConnection() as HttpURLConnection
Thread(Runnable {
  val connection = URL(
      "$BASE_URL/api/note/complete?id=$taskId"
  ).openConnection() as HttpURLConnection

  connection.requestMethod = "POST"
  connection.setRequestProperty("Content-Type", "application/json")
  connection.setRequestProperty("Accept", "application/json")
  connection.setRequestProperty("Authorization", App.getToken())
  connection.readTimeout = 10000
  connection.connectTimeout = 10000
  connection.doOutput = true
  connection.doInput = true

  try {
    val reader = InputStreamReader(connection.inputStream)

    reader.use { input ->
      val response = StringBuilder()
      val bufferedReader = BufferedReader(input)

      bufferedReader.useLines { lines ->
        lines.forEach {
          response.append(it.trim())
        }
      }

      onTaskCompleted(null)
    }
  } catch (error: Throwable) {
    onTaskCompleted(error)
  }

  connection.disconnect()
}).start()
val unfinishedTasks = tasksResponse.notes.filter { !it.isCompleted }

onTasksReceived(unfinishedTasks, null)

Reviews

Comments