Jetpack Compose: Fetching Text from URL
This code demonstrates how to retrieve text content from a URL using Jetpack Compose. It utilizes coroutines for asynchronous network operations and presents the retrieved text along with progress indication.
Breakdown:
Setup:
MainActivity
sets the content of the activity usingsetContent
.ComposeNetworkTheme
is applied for theming purposes.- A
Scaffold
provides the basic app layout with aTopAppBar
and a content area.
Main Content:
MainContent
composable defines the UI elements for user interaction and displaying content.- A
rememberCoroutineScope
is used to launch coroutines within the composable. - State variables are used to manage the displayed text (
txt
), progress visibility (progressVisibility
), and scrolling state (scrollState
).
Fetching Text:
- A
Button
triggers the text retrieval process when clicked. - Clicking the button resets the displayed text and sets the progress indicator visible.
- A coroutine launched with
Dispatchers.IO
makes the network call to the URL usingURL.readText()
. - Within the coroutine, any encountered exceptions are caught and their messages displayed instead.
- Finally, using
withContext(Dispatchers.Main)
, the progress indicator is hidden on the main thread after successful completion.
- A
Displaying Results:
- The retrieved text is stored in the
txt
state variable. - A
Column
with a weight of 1 fills the remaining space and allows scrolling usingverticalScroll
. - The final state of the
txt
variable is displayed within aText
composable. - An
AnimatedVisibility
ensures the progress indicator is only displayed while fetching the text.
- The retrieved text is stored in the
Summary:
This code offers a well-structured example of fetching text from a URL in Jetpack Compose. It effectively separates UI logic from network operations using coroutines and provides visual feedback through a progress indicator. This approach can be adapted for various network-based functionalities within your Compose applications.
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)
}
}
}
- jetpack compose ktor - How to pass parameters
- jetpack compose ktor - How to post data
- jetpack compose - Kotlinx serialization pretty print
- jetpack compose - Kotlinx serialization lenient parsing
- jetpack compose - Kotlinx serialization ignore unknown keys
- jetpack compose - Kotlinx serialization alternative json names
- jetpack compose - Kotlinx serialization handle null values
- jetpack compose - Kotlinx serialization not encode null values
- jetpack compose - Kotlinx serialization encode to string
- jetpack compose - Kotlinx serialization decode from string
- jetpack compose - Kotlinx serialization encode defaults
- jetpack compose - Kotlinx serialization allow special floating point values
- jetpack compose - Kotlinx serialization parse to json element
- jetpack compose - Kotlinx serialization build json element
- jetpack compose - Kotlinx serialization build json array