简体   繁体   中英

Zxing QR code scanner code is not working in a fragment

I am trying to develop QR code scanner App using Zxing library in Kotlin. I am able to open the camera and scan the QR code but not getting response.

I also tried this tutorial for implementation but did not get helped.

class HomeFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val mScanner = IntentIntegrator(activity)
        mScanner.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
        mScanner.setBeepEnabled(true)
        mScanner.initiateScan()

    }
    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(activity, "Cancelled", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(activity, "Scanned: " + result.contents, Toast.LENGTH_LONG).show()
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }
}

I want to get response in a toast but when I tried to use debugger I am unable to go to onActivityResult() and the camera closes quickly.

Your fragment is not requesting the activity result. As you instantiate IntentIntegrator(activity) with the activity, it'll run activity.startActivityForResult(intent, REQUEST_CODE) . Therefore you'll not receive the result within your fragment.

If you're still using android.app.Fragment , you only have to make sure to use your fragment to instantiate IntentIntegrator(this@HomeFragment) . Like this you'll get the result within your fragment, as it'll run fragment.startActivityForResult(intent, REQUEST_CODE) internally.

If you're using the androidx.fragment.app.Fragment , you might need to copy the sources for IntentIntegrator into your app and adapt the code to use the AndroidX fragment instead of the framework type.

The issue is, the scanner is sending info to your Activity's onActivityResult method, instead of to your fragment method. So the possible solution could be that in your fragment pass "this" as context instead of passing your activity as context. Like in your fragment

 val mScanner = IntentIntegrator(this); // pass fragment context

And in fragment wherever you are initializing the scanner pass Fragment as context instead of passing activity as context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM