Wednesday, June 15, 2016

Integrating QR/Bar code Scanner to Android Application

Greetings of the Day!!!

While we were working on a project to develop an android app, we had a requirement to integrate a QR or bar code reader with this app.  I was wondering how to do it.  Barcode or QR Code scanning is a pretty complex and non-trivial task in itself, it could be overwhelming sometimes with android programming. 
But while browsing I saw  an open source project ZXing (pronounced Zebra-crossing). That solves all the problem. We can use it's frame work to read and retrieve the barcode or qr code. It's pretty simple using Zxing. Zxing has all the components and an android app to read the data. All we have to do is to send an intent to this app and receive the scanned results that you may use in your app. 

As Zxing is an open source and Apache licensed, we can use it freely.  This article talks about how to integrate this zxing barcode scanner with our android app. 

1. In your Android application, create a directory as "zxing" as shown below and place these two files inside this directory:
     a. IntentIntegrator.java 
Or You can download these files Here. And Your source code hierarchy should look as below:



2. Start an intent in that part of your code where you would like to initiate the barcode scanning. I start it on click on Scan button as shown in the below code

btnScan.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(shop_list.this);
scanIntegrator.initiateScan();
Log.d("marutsoft Scan", "Inside scanner");

}
});


3. All that remains now is to handle the result of this activity in your onActivityResult() handler. This is how I did it in my code:

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
Log.d("marutsoft Scan Content",scanContent);
Log.d("marutsoft Scan format", scanFormat);
Toast toast = Toast.makeText(getApplicationContext(),
scanFormat, Toast.LENGTH_LONG);
toast.show();
Toast toast1 = Toast.makeText(getApplicationContext(),
scanContent, Toast.LENGTH_LONG);
toast1.show();

}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_LONG);
toast.show();
}
}

That`s all! The above code not only returns the barcode scanning result to your app, but even prompts the user to install a barcode scanner app in case one isn't there. This is the easiest and recommended way of integrating barcode scanning in your android app.


No comments: