Kotlin, onActivityResult is deprecated scanning QR code, any ideas

Viewed 1110

"onActivityResult" is deprecated I don't know how to replace with "StartActivityForResult" any ideas please help, This is my code:

my code works fine but showme warning about deprecated method

this is my function QrScan code:

    private fun scanQRCode() {
    val integrator = IntentIntegrator(this).apply {
        captureActivity = CaptureActivity::class.java
        setOrientationLocked(false)
        setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
        setPrompt("Scanning Code")
    }
    integrator.initiateScan()
}

then

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
    if (result != null) {
        if (result.contents == null) Toast.makeText(this, "Operación Cancelada", Toast.LENGTH_LONG).show()
        else {
            resultado = result.contents.toString()
          getlist()
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data)
    }
}

I tried this new way but I can't get it works the new way in Kotlin:

var resultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
    if (result.resultCode == Activity.RESULT_OK) {
        // There are no request codes
        val data: Intent? = result.data
        doSomeOperations()
    }
}

fun openSomeActivityForResult() {
    val intent = Intent(this, SomeActivity::class.java)
    resultLauncher.launch(intent)
}
1 Answers

The initiateScan() method calls another method called createScanIntent() which returns the intent necessary for the resultLauncher to work. This way:

private fun scanQRCode() {
    val integrator = IntentIntegrator(this).apply {
        captureActivity = CaptureActivity::class.java
        setOrientationLocked(false)
        setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
        setPrompt("Scanning Code")
    }
    resultLauncher.launch(integrator.createScanIntent())
}

Replacing integrator.initiateScan() with resultLauncher.launch (integrator.createScanIntent()) accesses the result of resultLauncher

Related