Android Networking: Fundamentals

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

Part 1: Learn About HTTP & Threading

08. Challenge: Request & Parse Data

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: 07. Parse JSON Data Next episode: 09. Conclusion

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: 08. Challenge: Request & Parse Data

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

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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)