Search code examples
androidcallbackandroid-camerax

OnImageCapturedListener of CameraX gives an error


I am testing the new CameraX API and I have the following line of code:

imageCapture.takePicture(executor, object:ImageCapture.OnImageCapturedListener{
    // do some work when image is captured 
})

But the argument object:ImageCapture.OnImageCapturedListener is underlined with red. Android Studio is telling me: "This type has a constructor and thus must be initialized here"

Note: The code above is called inside a click listener of a Button.

Below you can see the other listener of ImageCapture class which is OnImageSavedListener. With this interface I have no errors.

findViewById<ImageButton>(R.id.capture_button).setOnClickListener {
            val file = File(externalMediaDirs.first(),
                "${System.currentTimeMillis()}.jpg")

            imageCapture.takePicture(file, executor,
                object : ImageCapture.OnImageSavedListener {

                    override fun onError(
                        imageCaptureError: ImageCapture.ImageCaptureError,
                        message: String,
                        exc: Throwable?
                    ) {
                        val msg = "Photo capture failed: $message"
                        Log.e("CameraXApp", msg, exc)
                        viewFinder.post {
                            Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                        }
                    }

                    override fun onImageSaved(file: File) {
                        val msg = "Photo capture succeeded: ${file.absolutePath}"
                        Log.d("CameraXApp", msg)
                        viewFinder.post {
                            Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                        }

                        var bitmap:Bitmap = viewFinder.bitmap
                        runOnUiThread { imageView.setImageBitmap(bitmap) }
                    }
                })

I have no problem with this but when I use OnImageCapturedListener and replace the onImageSaved callback with the onCaptureSuccess callback then I get an error as described above


Solution

  • Try out this code.

    imageCapture.takePicture(executor,object :ImageCapture.OnImageCapturedListener(){
                override fun onCaptureSuccess(image: ImageProxy?, rotationDegrees: Int) {
                    super.onCaptureSuccess(image, rotationDegrees)  
    
                    // capture image 
    
                    }
                 override fun onError(
                    imageCaptureError: ImageCapture.ImageCaptureError,
                    message: String,
                    cause: Throwable?) {
                    super.onError(imageCaptureError, message, cause)
                    // error in capturing
                }
    
            })