Tuesday, July 21, 2020

android kotlin - Coroutines JSON from URL

MainActivity.kt

package com.example.coroutine

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.MalformedURLException
import java.net.URL


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // url to download json data
        val url:URL? = try {
            URL("https://pastebin.com/raw/2bW31yqa")
        }catch (e:MalformedURLException){
            Log.d("Exception", e.toString())
            null
        }

        // download json data and parse it and display in text view
        button.setOnClickListener {
            url?.let { textView.text = it.toString() }

            // io dispatcher for networking operation
            lifecycleScope.launch(Dispatchers.IO){
                url?.getString()?.apply {

                    // default dispatcher for json parsing, cpu intensive work
                    withContext(Dispatchers.Default){
                        val list = parseJson(this@apply)

                        // main dispatcher for interaction with ui objects
                        withContext(Dispatchers.Main){
                            textView.append("\n\nReading data from json....\n")

                            list?.forEach {
                                textView.append("\n${it.firstName}" +
                                        " ${it.lastName} ${it.age}")
                            }

                        }

                    }
                }
            }
        }

    }
}


// extension function to get string data from url
fun URL.getString(): String? {
    val stream = openStream()
    return try {
        val r = BufferedReader(InputStreamReader(stream))
        val result = StringBuilder()
        var line: String?
        while (r.readLine().also { line = it } != null) {
            result.append(line).appendln()
        }
        result.toString()
    }catch (e: IOException){
        e.toString()
    }
}


// data class to hold student instance
data class Student(
    val firstName:String,
    val lastName:String,
    val age:Int
)


// parse json data
fun parseJson(data:String):List<Student>?{
    val list = mutableListOf<Student>()

    try {
        val array = JSONObject(data).getJSONArray("students")
        for(i in 0 until array.length()){
            val obj = JSONObject(array[i].toString())
            val firstName = obj.getString("firstname")
            val lastName = obj.getString("lastname")
            val age = obj.getInt("age")
            list.add(Student(firstName,lastName,age))
        }
    }catch (e:JSONException){
        Log.d("Exception", e.toString())
    }

    return list
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#E9FFDB"
    tools:context=".MainActivity">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:backgroundTint="#4F42B5"
        android:text="Get JSON"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/textView"
        style="@style/TextAppearance.MaterialComponents.Headline6"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:padding="8dp"
        android:gravity="center_horizontal"
        android:fontFamily="sans-serif-thin"
        android:textColor="#353839"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
build.gradle (app) [code to add]

dependencies {
    // kotlin coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7'

    // life cycle
    def lifecycle_version = "2.2.0"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
}