free geoip
28

Kotlin App Crashes After Granting Permission

When building Android apps using Kotlin, handling permissions is a critical part of the development process, especially from Android 6.0…

When building Android apps using Kotlin, handling permissions is a critical part of the development process, especially from Android 6.0 (Marshmallow) and above. A common issue that developers face is that the Kotlin app crashes after granting permission—particularly runtime permissions like camera access, storage, location, or microphone.

Kotlin App Crashes After Granting Permission

In this guide, we’ll break down why this happens, how to reproduce the issue, and how to fix it using a practical example with Kotlin and Android Studio.

Common Scenario

Let’s say you’re requesting camera permission. You’ve added the correct permission in the AndroidManifest.xml and you’ve implemented a permission request dialog. Once the user grants the permission, the app crashes unexpectedly. Here’s why that might happen:

Why Does the Kotlin App Crash After Granting Permission?

  1. Null or Late Initialization
    After permission is granted, you might be calling a method or initializing a component (e.g., Camera or LocationManager) that is not ready yet.
  2. Activity or Fragment Restart
    Granting permission may recreate your activity, and some variables or views might be null during onResume() or onActivityResult().
  3. Code Execution Timing
    Some developers execute permission-dependent logic immediately after onRequestPermissionsResult, before the system has fully applied the permission.
  4. Not Checking Permission Again
    Some devices or OS versions may require rechecking the permission before using the related feature.

Real-World Example: Camera Permission Crash

Let’s walk through a complete example and fix the crash step-by-step.

Step 1: Add Permission to AndroidManifest.xml

<uses-permission android:name="android.permission.CAMERA" />

Step 2: Request Permission in Kotlin

private val CAMERA_PERMISSION_CODE = 100

private fun checkCameraPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
        != PackageManager.PERMISSION_GRANTED
    ) {
        ActivityCompat.requestPermissions(this,
            arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_CODE)
    } else {
        openCamera()
    }
}

Step 3: Handle Permission Result

override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    
    if (requestCode == CAMERA_PERMISSION_CODE) {
        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // This is the critical part - wait for UI to be ready
            Handler(Looper.getMainLooper()).post {
                openCamera()
            }
        } else {
            Toast.makeText(this, "Camera Permission Denied", Toast.LENGTH_SHORT).show()
        }
    }
}

Step 4: Open Camera Function

private fun openCamera() {
    Toast.makeText(this, "Camera opened successfully", Toast.LENGTH_SHORT).show()
    // You can initiate CameraX, or camera intent here
}

Simulate the Crash

You can simulate the crash by calling openCamera() directly after the permission result without checking the UI state. For example:

Best Practices to Avoid Crash After Granting Permission

  • Always check if the activity is still valid before accessing UI or system services.
  • Use Handler or lifecycleScope to delay execution slightly.
  • Re-check permission before using sensitive features.
  • Keep view initialization logic in onCreate or onResume rather than in the permission callback.

Alternative with Kotlin Coroutines (Using lifecycleScope)

lifecycleScope.launch {
    delay(200)
    openCamera()
}

This ensures the camera-opening function is not executed immediately after granting permission.

Bonus: Handle Multiple Permissions Safely

private val permissions = arrayOf(
    Manifest.permission.CAMERA,
    Manifest.permission.READ_EXTERNAL_STORAGE
)

private fun requestMultiplePermissions() {
    val missingPermissions = permissions.filter {
        ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
    }
    if (missingPermissions.isNotEmpty()) {
        ActivityCompat.requestPermissions(this, missingPermissions.toTypedArray(), 101)
    } else {
        startCameraWithStorageAccess()
    }
}

Summary Table

ProblemCauseSolution
App crashes after permissionActivity not ready / null viewsUse delay/Handler/lifecycleScope
NullPointerException on ViewView was not initialized after recreateInitialize view properly
Camera not opening after permissionCalling before permission appliedRecheck permission post result

Conclusion

If your Kotlin app crashes right after granting permission, chances are it’s a timing issue or a misplaced logic block. Always ensure that any functionality relying on permissions is executed after the system and UI are completely ready.

By following these patterns and using Kotlin features like Handler, lifecycleScope, and proper null-safety checks, you can ensure a stable and crash-free experience for your users.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *