0
0
Android Kotlinmobile~20 mins

Error handling patterns in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Error Handling Demo
This screen demonstrates common error handling patterns in Kotlin for Android. It shows how to handle errors from a simulated network call and display messages to the user.
Target UI
-------------------------
| Error Handling Demo    |
|-----------------------|
| [Fetch Data]          |
|                       |
| Status:               |
|                       |
| Message:              |
-------------------------
Add a button labeled 'Fetch Data' that triggers a simulated network call.
Simulate success or failure randomly when fetching data.
Use try-catch to handle exceptions from the simulated call.
Display 'Status: Success' or 'Status: Error' accordingly.
Show the error message if an error occurs.
Use Kotlin's runCatching or Result type to demonstrate another error handling pattern.
Ensure UI updates happen on the main thread.
Starter Code
Android Kotlin
package com.example.errorhandlingdemo

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlin.random.Random

class MainActivity : AppCompatActivity() {
    private lateinit var statusTextView: TextView
    private lateinit var messageTextView: TextView
    private lateinit var fetchButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        statusTextView = findViewById(R.id.statusTextView)
        messageTextView = findViewById(R.id.messageTextView)
        fetchButton = findViewById(R.id.fetchButton)

        fetchButton.setOnClickListener {
            // TODO: Implement error handling when fetching data
        }
    }

    // Simulate a network call that randomly succeeds or throws an exception
    private fun fetchData(): String {
        if (Random.nextBoolean()) {
            return "Data loaded successfully"
        } else {
            throw Exception("Network error occurred")
        }
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
Android Kotlin
package com.example.errorhandlingdemo

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlin.random.Random

class MainActivity : AppCompatActivity() {
    private lateinit var statusTextView: TextView
    private lateinit var messageTextView: TextView
    private lateinit var fetchButton: Button
    private var useRunCatching = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        statusTextView = findViewById(R.id.statusTextView)
        messageTextView = findViewById(R.id.messageTextView)
        fetchButton = findViewById(R.id.fetchButton)

        fetchButton.setOnClickListener {
            if (useRunCatching) {
                fetchDataWithRunCatching()
            } else {
                fetchDataWithTryCatch()
            }
            useRunCatching = !useRunCatching
        }
    }

    private fun fetchDataWithTryCatch() {
        try {
            val data = fetchData()
            statusTextView.text = "Status: Success"
            messageTextView.text = data
        } catch (e: Exception) {
            statusTextView.text = "Status: Error"
            messageTextView.text = e.message
        }
    }

    private fun fetchDataWithRunCatching() {
        val result = runCatching { fetchData() }
        result.onSuccess { data ->
            statusTextView.text = "Status: Success"
            messageTextView.text = data
        }.onFailure { error ->
            statusTextView.text = "Status: Error"
            messageTextView.text = error.message
        }
    }

    private fun fetchData(): String {
        if (Random.nextBoolean()) {
            return "Data loaded successfully"
        } else {
            throw Exception("Network error occurred")
        }
    }
}

This solution shows two common error handling patterns in Kotlin for Android.

First, try-catch is used in fetchDataWithTryCatch() to catch exceptions from fetchData(). If successful, it updates the UI with success status and data. If an exception occurs, it shows an error status and message.

Second, runCatching is used in fetchDataWithRunCatching(). This Kotlin function wraps the call and returns a Result object. We then use onSuccess and onFailure to handle success and error cases cleanly.

The button toggles between these two methods each time it is clicked, demonstrating both patterns in one screen.

UI updates happen on the main thread because the click listener runs on the main thread by default.

Final Result
Completed Screen
-------------------------
| Error Handling Demo    |
|-----------------------|
| [Fetch Data]          |
|                       |
| Status: Success       |
|                       |
| Message:              |
| Data loaded successfully|
-------------------------
User taps 'Fetch Data' button.
App randomly succeeds or fails to fetch data.
If success, 'Status: Success' and success message appear.
If failure, 'Status: Error' and error message appear.
Each tap toggles between try-catch and runCatching error handling.
Stretch Goal
Add a toggle switch to let the user choose between try-catch and runCatching error handling methods.
💡 Hint
Use a Switch or ToggleButton widget and update the fetch method based on its state.