Qr Code Reader And Qr Code Generator for Android

In the first place QR code (abbreviated from Quick Response Code) is the trademark for a type of matrix barcode (or two-dimensional barcode). Not to mention it’s first designed for the automotive industry in Japan. On the other hand a barcode is a machine-readable optical label that contains information about the item to which it is attached. In fact a QR code uses four standardized encoding modes (numeric, alphanumeric, byte/binary, and kanji) .To efficiently store data,extensions may also be used.
As a matter of fact the QR code system became popular outside the automotive industry. Due to its fast readability and greater storage capacity compared to standard UPC barcodes. Furthermore applications include product tracking, item identification, time tracking, document management, and general marketing.
However a QR code consists of black squares arranged in a square grid on a white background.
Which can be read by an imaging device such as a camera. And processed using Reed–Solomon error correction until the image can be appropriately interpreted. The required datum is then extracted from patterns that are present in both horizontal and vertical components of the image. Finally the source of this information Wikipedia.
Explanation
However this tutorial is for reading and generating Qr code using zxing with simple step by step processes. ZXing (“zebra crossing”) is an open-source, multi-format 1D/2D barcode image processing library implemented in Java with ports to other languages. Its focus is on using the built-in camera on mobile phones to scan and decode barcodes on the device, without communicating with a server, though the library also supports use on a server. Similarly Qr code used in payment applications like paytm also in xender for connecting. Additionally BBM. This tutorial is divided in to three parts to explain.
- Activity for Navigation (MainActivity).
- Qr Code Generator Activity.
- Qr Code Reader Activity.
1- Activity for Navigation (MainActivity)
MainActiviy is only for navigation purpose. Then add the required library’s (dependencies ). com.google.zxing:core
is for QR Code generating and me.dm7.barcodescanner:zxing
is for QR Code scanner.
dependencies { compile 'com.google.zxing:core:3.3.0' compile 'me.dm7.barcodescanner:zxing:1.9' }
In addition to dependencies permissions required are.
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Navigation activity contain only two methods readQr for reader and generateQr for generator activity. Similarly click is handled by onClick inside xml.
MainActivity.java
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void readQr(View view){ Intent intent=new Intent(MainActivity.this,QrRead.class); startActivity(intent); } public void generateQr(View view){ Intent intent=new Intent(MainActivity.this,QrGenerate.class); startActivity(intent); } }
Finally xml file for Navigation activity. However android:onClick="generateQr"
and android:onClick="readQr"
are for methods generateQr(View view)
and readQr(View view) accordingly
.
activity_main.xml
?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.logicchip.blog_8_qrcode.MainActivity"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_centerHorizontal="true"> <Button android:text="Generate Qr Code" android:drawableRight="@drawable/ic_action_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="generateQr" android:id="@+id/button3" /> <Button android:text="Read Qr Code" android:drawableRight="@drawable/ic_action_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:onClick="readQr" android:id="@+id/button4" /> </LinearLayout> </RelativeLayout>
2- Qr Code Generator Activity
First and foremost Generation of qr code using zxing take place here. However qrGenerator
method contains basic properties for the qr code like height width character encoding etc. Another method createQRCode is where encoding take-place, and bitmetrix is converted to bitmap. Then this bitmap is displayed inside the imageview.
QrGenerate.java
public class QrGenerate extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_qr_generate); } public void qrGenerator(View v){ try { //setting size of qr code WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); Point point = new Point(); display.getSize(point); int width = point.x; int height = point.y; int smallestDimension = width < height ? width : height; EditText qrInput = (EditText) findViewById(R.id.qrInput); String qrCodeData = qrInput.getText().toString(); //setting parameters for qr code String charset = "UTF-8"; // or "ISO-8859-1" Map<EncodeHintType, ErrorCorrectionLevel> hintMap =new HashMap<EncodeHintType, ErrorCorrectionLevel>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); createQRCode(qrCodeData, charset, hintMap, smallestDimension, smallestDimension); } catch (Exception ex) { Log.e("QrGenerate",ex.getMessage()); } } public void createQRCode(String qrCodeData,String charset, Map hintMap, int qrCodeheight, int qrCodewidth){ try { //generating qr code in bitmatrix type BitMatrix matrix = new MultiFormatWriter().encode(new String(qrCodeData.getBytes(charset), charset), BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap); //converting bitmatrix to bitmap int width = matrix.getWidth(); int height = matrix.getHeight(); int[] pixels = new int[width * height]; // All are 0, or black, by default for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = matrix.get(x, y) ? BLACK : WHITE; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); //setting bitmap to image view ImageView myImage = (ImageView) findViewById(R.id.imageView1); myImage.setImageBitmap(bitmap); }catch (Exception er){ Log.e("QrGenerate",er.getMessage()); } } }
Also Ui for Qr Generator is given below.
activity_qr_generate.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_qr_generate" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.logicchip.blog_8_qrcode.QrGenerate"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:hint="Text here...." android:id="@+id/qrInput" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10"> <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Generate QR Code" android:onClick="qrGenerator"/> <ImageView android:layout_gravity="center_horizontal" android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </RelativeLayout>
3- Qr Code Reader Activity
Reader class extents Activity
and implements ZXingScannerView.ResultHandler
. In other words me.dm7.barcodescanner.zxing
is used. In detail it’s an Android library projects that provides easy to use and extensible Barcode Scanner views based on ZXing and ZBar. QrReader.java is an activity but don’t have an xml. As a result ZXingScannerView act as the ui, providing the Camera preview. We have to include the activity file for reader class in the manifest file otherwise it will result in crashing.
QrReader.java
import android.app.Activity; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.util.Log; import com.google.zxing.Result; import me.dm7.barcodescanner.zxing.ZXingScannerView; /** * Created by akhil on 28-12-16. */ public class QrReader extends Activity implements ZXingScannerView.ResultHandler { private ZXingScannerView mScannerView; String TAG="QRREADER"; @Override public void onCreate(Bundle state) { super.onCreate(state); mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view setContentView(mScannerView); // Set the scanner view as the content view } @Override public void onResume() { super.onResume(); mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results. mScannerView.startCamera(); // Start camera on resume } @Override public void onPause() { super.onPause(); mScannerView.stopCamera(); // Stop camera on pause } @Override public void handleResult(Result rawResult) { // Do something with the result here Log.v(TAG, rawResult.getText()); // Prints scan results Log.v(TAG, rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.) // call the alert dialog Alert(rawResult); } public void Alert(Result rawResult){ AlertDialog.Builder builder = new AlertDialog.Builder(QrRead.this); builder.setTitle("Qr scan result"); builder.setMessage("Result :"+rawResult.getText()+"\nType :"+rawResult.getBarcodeFormat().toString()) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // back to previous activity finish(); } }) .setNegativeButton("Scan Again", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog // If you would like to resume scanning, call this method below: mScannerView.resumeCameraPreview(QrRead.this); } }); // Create the AlertDialog object and return it builder.create().show(); } }
Manifest for the application.
The application require permission for camera and storage. Some times the storage permission is not required because the file is never actually saved.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.logicchip.blog_8_qrcode"> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".QrRead"></activity> <activity android:name=".QrGenerate" android:label="@string/qr_generate"></activity> </application> </manifest>
If you have any questions or queries drop it in the comments below.Download Source code here