0
0
Android Kotlinmobile~20 mins

Why network calls fetch remote data in Android Kotlin - Build It to Prove It

Choose your learning style9 modes available
Build: Remote Data Fetch Screen
This screen fetches and shows data from the internet using a network call.
Target UI
-------------------------
| Remote Data Fetch      |
|-----------------------|
| [Fetch Data Button]    |
|                       |
| Data will appear here. |
|                       |
-------------------------
Add a button labeled 'Fetch Data'.
When tapped, it makes a network call to get remote data.
Show a loading indicator while fetching.
Display the fetched data as text below the button.
Handle errors by showing an error message.
Starter Code
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      MaterialTheme {
        // TODO: Add your UI here
      }
    }
  }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      MaterialTheme {
        val scope = rememberCoroutineScope()
        var isLoading by remember { mutableStateOf(false) }
        var data by remember { mutableStateOf("") }
        var error by remember { mutableStateOf("") }

        Column(modifier = Modifier.padding(16.dp)) {
          Button(onClick = {
            isLoading = true
            data = ""
            error = ""
            scope.launch {
              try {
                // Simulate network delay
                delay(2000)
                // Simulate fetched data
                data = "Hello from the internet!"
              } catch (e: Exception) {
                error = "Failed to fetch data"
              } finally {
                isLoading = false
              }
            }
          }) {
            Text("Fetch Data")
          }

          if (isLoading) {
            CircularProgressIndicator(modifier = Modifier.padding(top = 16.dp))
          } else if (data.isNotEmpty()) {
            Text(text = data, modifier = Modifier.padding(top = 16.dp))
          } else if (error.isNotEmpty()) {
            Text(text = error, modifier = Modifier.padding(top = 16.dp))
          }
        }
      }
    }
  }
}

This app screen uses a button to start a network call simulation. When the button is tapped, it shows a loading spinner. After a delay (simulating network time), it displays the fetched data text. If an error occurs, it shows an error message instead. We use Kotlin coroutines to run the network call asynchronously so the UI stays responsive. The UI updates reactively based on state variables for loading, data, and error.

Final Result
Completed Screen
-------------------------
| Remote Data Fetch      |
|-----------------------|
| [Fetch Data Button]    |
|                       |
| Loading spinner here   |
|                       |
-------------------------

After loading:
-------------------------
| Remote Data Fetch      |
|-----------------------|
| [Fetch Data Button]    |
|                       |
| Hello from the internet!|
|                       |
-------------------------
User taps 'Fetch Data' button.
Loading spinner appears below the button.
After 2 seconds, loading spinner disappears.
Fetched text 'Hello from the internet!' appears below the button.
If network fails, an error message appears instead.
Stretch Goal
Add a retry button that appears only when there is an error, allowing the user to try fetching data again.
💡 Hint
Show a Button with label 'Retry' below the error message. On tap, repeat the fetch logic.