Sunday, March 27, 2022

jetpack compose - Get text from url

MainActivity.kt

package com.cfsuman.composenetwork

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.cfsuman.composenetwork.ui.theme.ComposeNetworkTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.Exception
import java.net.URL

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeNetworkTheme {
                Scaffold(
                    topBar = {
                        TopAppBar(
                            title= { Text("Compose - Get Text From URL")}
                        )
                    },
                    content = { MainContent()}
                )
            }
        }
    }
}


@Composable
fun MainContent() {
    val scope = rememberCoroutineScope()
    var txt by remember { mutableStateOf("")}
    val scrollState = rememberScrollState()

    var progressVisibility by remember {
        mutableStateOf(false)
    }

    Column(
        modifier = Modifier.fillMaxSize().padding(24.dp)
    ) {
        Row(
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Button(onClick = {
                txt = ""
                progressVisibility = true

                scope.launch(Dispatchers.IO) {
                    txt = try {
                        URL("https://google.com").readText()
                    }catch (e:Exception){
                        e.message.toString()
                    }

                    withContext(Dispatchers.Main){
                        progressVisibility = false
                    }
                }
            }) {
                Text(text = "Read Text From URL")
            }

            AnimatedVisibility(visible = progressVisibility) {
                CircularProgressIndicator()
            }
        }

        Column(
            Modifier.fillMaxSize().weight(1F)
                .verticalScroll(scrollState)
        ) {
            Text(text = txt)
        }
    }
}