I'm trying to get two values from cameraX and ML Kit using the barcode scanner (rawValue and format) but I can't stop the scan and insert data into room when the first one is detected. My code inserts in room as many elements as many barcodes are detected in the process (the same barcode many times)
This is my addOnSuccessListener in the processImageProxy function:
scanner.process(inputImage).addOnSuccessListener { barcodeList ->
processBarcode(barcodeList)
}
And this is my actual method to keep data:
private fun processBarcode(barcodeList: List<Barcode>) {
if (barcodeList.isNotEmpty()) {
with (barcodeList.first()) {
activityCameraScannerViewModel.rawValue = this.rawValue.toString()
activityCameraScannerViewModel.format = this.format.toString()
activityCameraScannerViewModel.setNewCard()
val intent = Intent(applicationContext, MainActivity::class.java)
intent.putExtra("rawValue", this.rawValue.toString())
intent.putExtra("format", this.format.toString())
startActivity(intent)
}
}
}
The actual result of code is a lot of inserts (random number of them). I would appreciate any help. If anybody need more code I will edit the question. Thanks.
Simply resolution:
Pass scanner as parameter of processBarcode function and call
scanner.close()
Complete code:
private fun processBarcode(barcodeList: List<Barcode>, scanner: BarcodeScanner) {
if (barcodeList.isNotEmpty()) {
with (barcodeList.first()) {
val rawValue = this.rawValue.toString()
val format = this.format.toString()
activityCameraScannerViewModel.rawValue = rawValue
activityCameraScannerViewModel.format = format
activityCameraScannerViewModel.setNewCard()
val intent = Intent(applicationContext, MainActivity::class.java)
startActivity(intent)
scanner.close()
}
}
}