0
0
Android Kotlinmobile~20 mins

Crashlytics in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Crashlytics Demo Screen
This screen demonstrates how to integrate Firebase Crashlytics to catch and report app crashes in an Android app using Kotlin.
Target UI
-------------------------
| Crashlytics Demo      |
|-----------------------|
| [Crash App Button]    |
|                       |
| Tap the button to     |
| cause a crash and     |
| send a report to      |
| Firebase Crashlytics. |
-------------------------
Add Firebase Crashlytics dependency and initialize it.
Create a button labeled 'Crash App Button'.
When the button is tapped, force a crash by throwing a RuntimeException.
Ensure the crash is reported to Firebase Crashlytics.
Starter Code
Android Kotlin
package com.example.crashlyticsdemo

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button

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

        val crashButton: Button = findViewById(R.id.crashButton)
        // TODO: Set click listener to cause a crash
    }
}
Task 1
Solution
Android Kotlin
package com.example.crashlyticsdemo

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button

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

        val crashButton: Button = findViewById(R.id.crashButton)
        crashButton.setOnClickListener {
            throw RuntimeException("Test Crash") // Force a crash
        }
    }
}

This code sets a click listener on the button labeled 'Crash App Button'. When tapped, it throws a RuntimeException which crashes the app. Firebase Crashlytics automatically catches this crash and sends a report to your Firebase console. Make sure Firebase Crashlytics is properly added and initialized in your project for this to work.

Final Result
Completed Screen
-------------------------
| Crashlytics Demo      |
|-----------------------|
| [Crash App Button]    |
|                       |
| Tap the button to     |
| cause a crash and     |
| send a report to      |
| Firebase Crashlytics. |
-------------------------
User taps 'Crash App Button'.
App immediately crashes with RuntimeException.
Crashlytics captures the crash and sends report to Firebase.
Stretch Goal
Add a log message to Crashlytics before crashing to provide extra context.
💡 Hint
Use FirebaseCrashlytics.getInstance().log("Your message") before throwing the exception.