Jetpack compose: How to get text from URL

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:

  1. Setup:

    • MainActivity sets the content of the activity using setContent.
    • ComposeNetworkTheme is applied for theming purposes.
    • A Scaffold provides the basic app layout with a TopAppBar and a content area.
  2. 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).
  3. 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 using URL.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.
  4. 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 using verticalScroll.
    • The final state of the txt variable is displayed within a Text composable.
    • An AnimatedVisibility ensures the progress indicator is only displayed while fetching the text.

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)
        }
    }
}
More android jetpack compose tutorials