free geoip
44

Kotlin Image Capture Not Returning URI

When developing an Android application using Kotlin, one of the most common tasks is capturing an image with the device…

When developing an Android application using Kotlin, one of the most common tasks is capturing an image with the device camera and retrieving its URI for further use, such as displaying in an ImageView or uploading to a server. However, many developers face the issue where Kotlin image capture does not return a URI or returns null. This article will explain why this happens and provide a step-by-step guide to fixing it.

Kotlin Image Capture Not Returning URI

Understanding the Problem

In Android development, capturing an image typically involves an Intent to the system camera app. The expected behavior is that the camera returns the captured image URI to your activity. But in many cases, especially on modern Android versions, the URI may not be returned due to:

  • Incorrectly configured FileProvider
  • Using data?.data instead of the proper file URI
  • Differences in Android API levels
  • Lack of correct permissions

Let’s dive into the correct way to implement image capture in Kotlin so that you always get the correct URI.

Step 1: Add Required Permissions

First, you must declare permissions in your AndroidManifest.xml:

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

Note: Starting from Android 10 (API 29), you don’t need WRITE_EXTERNAL_STORAGE if you are using scoped storage.

Step 2: Configure FileProvider

Add a FileProvider inside your AndroidManifest.xml:

<application ... >
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
</application>

Create the file_paths.xml inside res/xml/:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path
        name="images"
        path="Pictures" />
</paths>

Step 3: Launch Camera Intent

In your Kotlin activity or fragment, prepare the file where the image will be stored and pass it to the camera app:

private val REQUEST_IMAGE_CAPTURE = 1
private var photoUri: Uri? = null

private fun openCamera() {
    val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

    val photoFile: File? = createImageFile()
    photoFile?.also {
        photoUri = FileProvider.getUriForFile(
            this,
            "${BuildConfig.APPLICATION_ID}.provider",
            it
        )
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)
    }
}

@Throws(IOException::class)
private fun createImageFile(): File {
    val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
    val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
    return File.createTempFile(
        "JPEG_${timeStamp}_", 
        ".jpg", 
        storageDir 
    )
}

Step 4: Handle the Result

Override onActivityResult to get the image URI:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
        photoUri?.let { uri ->
            imageView.setImageURI(uri)
        }
    }
}

Step 5: Common Mistakes

Here are some mistakes developers often make when image capture does not return URI:

  • Relying on data?.data → This is often null. Use the file URI from EXTRA_OUTPUT instead.
  • Not setting up FileProvider → The app will crash or return no URI.
  • Forgetting permissions → Especially on older Android versions, missing camera/storage permissions causes failure.

Comparison Table: Wrong vs Correct Implementation

Wrong ImplementationCorrect Implementation
Using data?.data from IntentUsing FileProvider.getUriForFile
No FileProvider in manifestProperly configured FileProvider
No permission handlingRequesting CAMERA permission correctly

Conclusion

If your Kotlin image capture is not returning a URI, the problem is most likely related to missing FileProvider configuration or relying on data?.data. Always prepare your own file, pass it with EXTRA_OUTPUT, and retrieve it later using the stored URI. Following this guide will ensure your app works consistently across different Android versions.

For further reading about official Android Camera documentation, you can check the official developer guide.

rysasahrial

Leave a Reply

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