0

i am making my first app using kotlin and while i was making it i approached the problem of the camera app not opening when i click on a button. i have no idea what im doing wrong. I get the error camera keeps stopping

import android.app.Activity
import android.content.ClipData
import android.content.Intent
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast


private const val REQUEST_CODE = 42
class MainActivity : AppCompatActivity() {

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

    val takePicBtn = findViewById<Button>(R.id.takePicBtn) as Button

        takePicBtn.setOnClickListener{
            val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

           if(takePictureIntent.resolveActivity(this.packageManager)!= null) {
               startActivityForResult(takePictureIntent, REQUEST_CODE)
           } else{
               Toast.makeText(this , "Unable to open camera", Toast.LENGTH_SHORT).show()
           }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?){

        val imagePic = findViewById<ImageView>(R.id.image) as ImageView
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK){
            val takenImage = data?.extras?.get("data") as Bitmap
            imagePic.setImageBitmap(takenImage)
        }else{
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

}

1 Answers1

0

Try doing it using the below code. And i am assuming you have added permissions as well.

takePicBtn.setOnClickListener{

    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

        var photoFile: File? = null
        try {
            photoFile =
                createImageFile(context!!)
        } catch (ex: IOException) {
            ex.printStackTrace()
        }

        if (photoFile != null) {
            photoURI = context?.let { photoURIFile(it, photoFile) }

            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
            startActivityForResult(
                cameraIntent,
                REQUEST_CODE
            )
        }
}

If you still face any issue feel free to ask

Hascher
  • 486
  • 1
  • 3
  • 12