Bird
Raised Fist0
Android Kotlinmobile~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. Why do mobile apps use network calls to fetch data from the internet?
easy
A. To get the most up-to-date information that changes frequently
B. To save battery by avoiding local storage
C. To make the app run faster without internet
D. To store data permanently on the device

Solution

  1. Step 1: Understand the purpose of network calls

    Network calls are used to get fresh data from the internet, especially when data changes often.
  2. Step 2: Compare options with this purpose

    Only To get the most up-to-date information that changes frequently matches this reason; others are incorrect because network calls do not save battery or store data locally.
  3. Final Answer:

    To get the most up-to-date information that changes frequently -> Option A
  4. Quick Check:

    Network calls fetch fresh data = A [OK]
Hint: Network calls get fresh data from internet, not local storage [OK]
Common Mistakes:
  • Thinking network calls save battery
  • Assuming network calls store data locally
  • Believing network calls make app work offline
2. Which Kotlin code snippet correctly starts a network call on a background thread?
easy
A. fetchDataFromNetwork()
B. Thread.sleep(1000); fetchDataFromNetwork()
C. runOnUiThread { fetchDataFromNetwork() }
D. GlobalScope.launch { fetchDataFromNetwork() }

Solution

  1. Step 1: Identify correct background thread usage in Kotlin

    Using GlobalScope.launch starts a coroutine on a background thread for network calls.
  2. Step 2: Check other options for thread usage

    fetchDataFromNetwork() runs on main thread, runOnUiThread { fetchDataFromNetwork() } forces main thread, Thread.sleep(1000); fetchDataFromNetwork() just delays but runs on main thread.
  3. Final Answer:

    GlobalScope.launch { fetchDataFromNetwork() } -> Option D
  4. Quick Check:

    Background thread with coroutine = B [OK]
Hint: Use coroutines (launch) for background network calls in Kotlin [OK]
Common Mistakes:
  • Calling network on main thread causing app freeze
  • Using runOnUiThread for network calls
  • Using Thread.sleep to delay network calls
3. What will this Kotlin code print if the network call returns "Hello" asynchronously?
GlobalScope.launch {
  val result = fetchDataFromNetwork()
  println(result)
}
println("Done")
medium
A. Hello\nDone
B. Done\nHello
C. HelloHello
D. DoneDone

Solution

  1. Step 1: Understand coroutine asynchronous behavior

    The println("Done") runs immediately on main thread before coroutine finishes.
  2. Step 2: Determine print order

    Coroutine prints "Hello" after network call completes, so output is "Done" then "Hello".
  3. Final Answer:

    Done\nHello -> Option B
  4. Quick Check:

    Async coroutine prints after main thread = A [OK]
Hint: Main thread prints first, coroutine prints after network call [OK]
Common Mistakes:
  • Assuming coroutine blocks main thread
  • Expecting prints in code order
  • Ignoring asynchronous nature of network calls
4. Identify the error in this Kotlin code that fetches data from network:
fun fetch() {
  val data = fetchDataFromNetwork()
  println(data)
}

fun fetchDataFromNetwork(): String {
  Thread.sleep(2000)
  return "Data"
}
medium
A. Thread.sleep is not allowed in Kotlin
B. fetchDataFromNetwork() returns wrong data type
C. Network call is blocking main thread causing app freeze
D. println cannot print strings

Solution

  1. Step 1: Analyze fetchDataFromNetwork() behavior

    Thread.sleep(2000) blocks the thread it runs on, here main thread, freezing UI.
  2. Step 2: Understand impact on app

    Blocking main thread causes app to freeze, so network calls must run on background thread.
  3. Final Answer:

    Network call is blocking main thread causing app freeze -> Option C
  4. Quick Check:

    Blocking main thread with sleep = C [OK]
Hint: Never block main thread with network calls or sleep [OK]
Common Mistakes:
  • Ignoring UI freeze caused by blocking calls
  • Thinking Thread.sleep is forbidden syntax
  • Assuming println cannot print strings
5. You want to fetch a large list of user data from a server that updates every minute. Which approach is best to keep your Android app smooth and up-to-date?
hard
A. Use background network calls with caching and refresh every minute
B. Fetch data on main thread every time user opens screen
C. Avoid network calls and use static data bundled in app
D. Fetch data once at app start and store locally forever

Solution

  1. Step 1: Consider data freshness and app performance

    Data updates every minute, so app needs fresh data regularly without freezing UI.
  2. Step 2: Evaluate options for smoothness and freshness

    Use background network calls with caching and refresh every minute uses background calls with caching and periodic refresh, balancing smooth UI and fresh data.
  3. Final Answer:

    Use background network calls with caching and refresh every minute -> Option A
  4. Quick Check:

    Background fetch + caching = D [OK]
Hint: Combine background fetch with caching for smooth, fresh data [OK]
Common Mistakes:
  • Fetching on main thread causing freezes
  • Not refreshing data causing stale info
  • Using static data ignoring updates
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard