• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Can't get ImageCapture use case working for CameraX in Android Studio

hrcd

Lurker
Aug 20, 2023
1
0
Hello. All I'm trying to do is have a simple preview and image capture working. However, I keep getting an error stating this...
"androidx.camera.core.ImageCaptureException: Not bound to a valid Camera"

I've been trying to get chatGPT to help figure it out but none of it's suggestions seem to fix the error. Anyone out there with some experience on this know what could be causing this? I'll post all the code for this activity below.

For reference, this is an Android Studio project using Kotlin.

Code:
class DetectorActivity : AppCompatActivity() {
private var cameraExecutor: ExecutorService = Executors.newSingleThreadExecutor()
private lateinit var cameraView: PreviewView
private val imageCapture = ImageCapture.Builder().build()

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

cameraView = findViewById(R.id.CameraView)
val captureButton = findViewById<ImageView>(R.id.CameraButton)

startCamera()

captureButton.setOnClickListener {
val imageFile = File(externalMediaDirs.first(), "${System.currentTimeMillis()}.jpg")
val outputFileOptions = ImageCapture.OutputFileOptions.Builder(imageFile).build()

imageCapture.takePicture(outputFileOptions, cameraExecutor,
object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
// Image saved successfully
Log.d("DetectorActivity", "$imageFile saved!")
}

override fun onError(exception: ImageCaptureException) {
Log.e("DetectorActivity", "Image capture error: ${exception.message}", exception)
}
})
}
}

private fun startCamera() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)

cameraProviderFuture.addListener({
val cameraProvider = cameraProviderFuture.get()

val preview = Preview.Builder()
.build()
.also {
it.setSurfaceProvider(cameraView.surfaceProvider)
}

val imageCapture = ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.build()

val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

try {
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)
} catch (exc: Exception) {
// Handle exception
}
}, ContextCompat.getMainExecutor(this))
}

override fun onDestroy() {
super.onDestroy()
cameraExecutor.shutdown()
    }
}
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones