Reputation: 69
My code for QR code scanning is given below:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//View objects
buttonScan = findViewById<View>(R.id.buttonScan) as Button
textViewName = findViewById<View>(R.id.textViewName) as TextView
textViewAddress = findViewById<View>(R.id.textViewAddress) as TextView
//intializing scan object
qrScan = IntentIntegrator(this)
//attaching onclick listener
buttonScan!!.setOnClickListener(this)
}
//Getting the scan results
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
if (result != null) {
//if qrcode has nothing in it
if (result.contents == null) {
Toast.makeText(this, "Result Not Found", Toast.LENGTH_LONG).show()
} else {
//if qr contains data
try {
//converting the data to json
val obj = JSONObject(result.contents)
//setting values to textviews
textViewName!!.text = obj.getString("busno")
textViewAddress!!.text = obj.getString("busname")
} catch (e: JSONException) {
e.printStackTrace()
//if control comes here
//that means the encoded format not matches
//in this case you can display whatever data is available on the qrcode
//to a toast
Toast.makeText(this, result.contents, Toast.LENGTH_LONG).show()
}
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
override fun onClick(view: View) {
//initiating the qr code scan
qrScan!!.initiateScan()
}
The QR code scanner starts after I press the button declared as buttonScan
. How do I start the QR scanner immediately after the application is opened and then display the scan details? Does it require a new activity?
I have used ZXING library for implementing the scanner.
Thank you!
Upvotes: 1
Views: 94
Reputation: 1614
With your code you can start the QR Scanner in two ways:
the first way is to initiate scan directly after this qrScan = IntentIntegrator(this)
so your onCreate
can be:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//View objects
buttonScan = findViewById<View>(R.id.buttonScan) as Button
textViewName = findViewById<View>(R.id.textViewName) as TextView
textViewAddress = findViewById<View>(R.id.textViewAddress) as TextView
//intializing scan object
qrScan = IntentIntegrator(this)
//initiate scan directly
qrScan!!.initiateScan()
//attaching onclick listener
buttonScan!!.setOnClickListener(this)
}
The second way is to trigger the click
event to the buttonScan
and it will initiatiate scan directly.
buttonScan!!.callOnClick
Upvotes: 1