Search code examples
androidimagekotlintake

How to refactor this Android TakePicture code in Kotlin?


I was following the example of 'Take Picture' from Android website (converting the code into Kotlin as I go along). It works all fine when everything is in one class. I then decided to delegate the responsibility of providing a file object and string path to another class. But my app started crashing (error report below). What do I have to learn here?

package com.dj.camera1


import android.os.Environment
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*


class UniqueName {

    companion object {
        var mCurrentPhotoPath: String = ""
    }
    @Throws(IOException::class)
    internal fun createImageFile(): File {
        // Create an image file name
        var timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        var imageFileName = "JPEG_" + timeStamp + "_"
        var storageDir:File = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
        var image = File.createTempFile(
                imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir      /* directory */
        )
        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath()
        return image
    }
}

I am getting the IOException!

(Edited the code above to reflect the change of code and change of directory to public one)

My code in mainactivity is as follows:

lateinit var photoContainer:File
                    try {
                        photoContainer = UniqueName().createImageFile()
                    } catch (c:IOException){
                        Log.d("MainActivity","PhotoContainer couldn't be initialised")
                    }

Solution

  • IOException could be because of Permission denied scenario.Please add the permission in your manifest file.

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

    And as it requires runtime user approval, you have to initiate the permission request.

    ActivityCompat.requestPermissions(mContext,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQ_CODE);