0% found this document useful (0 votes)
647 views9 pages

Qrcode Generator and Reader Android Example: Zxing

This document provides instructions for generating and reading QR codes in an Android app using the ZXing library. It explains how to add the ZXing dependency, set up permissions, and display a ZXingScannerView to scan QR codes. It also demonstrates how to generate QR codes by encoding custom user objects as JSON strings and setting QR code properties like error correction level. The steps shown include capturing user input, generating QR bitmaps, and decoding results on a successful scan.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
647 views9 pages

Qrcode Generator and Reader Android Example: Zxing

This document provides instructions for generating and reading QR codes in an Android app using the ZXing library. It explains how to add the ZXing dependency, set up permissions, and display a ZXingScannerView to scan QR codes. It also demonstrates how to generate QR codes by encoding custom user objects as JSON strings and setting QR code properties like error correction level. The steps shown include capturing user input, generating QR bitmaps, and decoding results on a successful scan.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

QRCODE GENERATOR AND READER ANDROID

EXAMPLE
MAY 26, 2018

Hello guy’s, today we gonna look out how to work with QRCode. Recently, I’ve been working on my

startup. My startup is based on Wallet App. So, I had to implement QRCode generator and reader on

the client side. When creating the app I had faced a lot difficulty to find the right solution. So, I thought

it might be good to write a blog about it.

So, let’s see how can we generate and read QRCode in Android app with the custom object. In this

example, we’re going to use Zxing library for reading and generating QRCode.

First, add the following dependency in your app level build.gradle file.

1. // Zxing barcode dependency


2. implementation 'me.dm7.barcodescanner:zxing:1.9.8'
Now add the following permission in Android Manifest file.
1. <uses-permission android:name="android.permission.CAMERA" />
2. <uses-permission android:name="android.hardware.camera" />
3. <uses-permission android:name="android.hardware.camera.autofocus" />
Now the setup part is done. Let’s see how can we read the QRCode.

READING QRCODE

Add the ZxingScannerView in your activity xml file.

1. <me.dm7.barcodescanner.zxing.ZXingScannerView
2. android:id="@+id/qrCodeScanner"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent">
5.
6. </me.dm7.barcodescanner.zxing.ZXingScannerView>
Now get the ZxingScannerView reference in the activity class.

1. val qrCodeScanner = findViewById<ZxingScannerView>(R.id.qrCodeScanner)


2. setScannerProperties()
setScannerProperites is my custom method. ZxingScannerView needs some basic properties before

start scanning. The following shows how to set scanner properties.

1. /**
2. * Set Qr code scanner basic properties.
3. */
4.
5. private fun setScannerProperties() {
6. qrCodeScanner.setFormats(listOf(BarcodeFormat.QR_CODE))
7. qrCodeScanner.setAutoFocus(true)
8. qrCodeScanner.setLaserColor(R.color.colorAccent)
9. qrCodeScanner.setMaskColor(R.color.colorAccent)
10. if (Build.MANUFACTURER.equals(HUAWEI, ignoreCase = true))
11. qrCodeScanner.setAspectTolerance(0.5f)
12. }

Now we need to start the scanner. It’s a good approach that we start scanner in onResume and stop the

scanner in on onPause.

The following shows to start scanner.

1. override fun onResume() {


2. super.onResume()
3. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
4. if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
5. ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA),
6. MY_CAMERA_REQUEST_CODE)
7. return
8. }
9. }
10. qrCodeScanner.startCamera()
11. qrCodeScanner.setResultHandler(this)
12. }

You see the setResultHandler is accepting the RequestHandler type interface and bypassing “this”

reference our activity needs to implement this interface.

1. override fun handleResult(p0: Result?) {


2. if (p0 != null) {
3. Toast.makeText(this,p0.text,Toast.LENGTH_LONG).show()
4. }
5. }
Now, this abstract function called every time whenever scanner successfully scanned. The scanned

result is in Result type object.

The following shows how to stop scanner in onStop or in the onPause method.

1. /**
2. * stop the qr code camera scanner when activity is in the onPause state.
3. */
4. override fun onPause() {
5. super.onPause()
6. qrCodeScanner.stopCamera()
7. }

GENERATING QRCODE

Generating a QR code is very easy. You guys must be remembered that I said, we’re going to

generate QRCode with Custom Object. By, custom object means we can store user info like name,

email,image_url etc in QRCode. So, in this example, we’re going to store user full name and age

in QRCode. So, when we scan the QRCode, we get user info in the Result object.

Now, this is another activity for generating the QR code. Below is code for the xml file.

1. <?xml version="1.0" encoding="utf-8"?>


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:background="@color/colorPrimary"
7. tools:context=".GenerateQrCodeActivity">
8.
9. <android.support.design.widget.TextInputLayout
10. android:id="@+id/fullNameLayout"
11. android:layout_width="match_parent"
12. android:layout_height="wrap_content"
13. android:layout_marginEnd="10dp"
14. android:layout_marginStart="10dp"
15. android:layout_marginTop="15dp"
16. android:theme="@style/TextLabel">
17.
18. <android.support.v7.widget.AppCompatEditText
19. android:id="@+id/fullNameEditText"
20. android:layout_width="match_parent"
21. android:layout_height="wrap_content"
22. android:drawablePadding="10dp"
23. android:hint="@string/full_name"
24. android:inputType="textCapSentences"
25. android:paddingEnd="8dp"
26. android:paddingStart="8dp"
27. android:textColor="@color/whiteColor"
28. android:textSize="15sp" />
29.
30. </android.support.design.widget.TextInputLayout>
31.
32. <android.support.design.widget.TextInputLayout
33. android:id="@+id/ageLayout"
34. android:layout_width="match_parent"
35. android:layout_height="wrap_content"
36. android:layout_below="@+id/fullNameLayout"
37. android:layout_marginEnd="10dp"
38. android:layout_marginStart="10dp"
39. android:layout_marginTop="10dp"
40. android:theme="@style/TextLabel">
41.
42. <android.support.v7.widget.AppCompatEditText
43. android:id="@+id/ageEditText"
44. android:layout_width="match_parent"
45. android:layout_height="wrap_content"
46. android:drawablePadding="10dp"
47. android:hint="@string/user_age"
48. android:inputType="number"
49. android:paddingEnd="8dp"
50. android:paddingStart="8dp"
51. android:textColor="@color/whiteColor"
52. android:textSize="15sp" />
53.
54. </android.support.design.widget.TextInputLayout>
55.
56. <FrameLayout
57. android:layout_width="match_parent"
58. android:layout_height="match_parent"
59. android:layout_above="@+id/generateQrCodeButton"
60. android:layout_below="@+id/ageLayout"
61. android:layout_marginBottom="5dp"
62. android:layout_marginTop="5dp">
63.
64. <ImageView
65. android:id="@+id/qrCodeImageView"
66. android:layout_width="wrap_content"
67. android:layout_height="wrap_content"
68. android:layout_gravity="center"
69. android:layout_marginEnd="25dp"
70. android:layout_marginStart="25dp"
71. android:contentDescription="@null" />
72.
73. </FrameLayout>
74.
75. <Button
76. android:id="@+id/generateQrCodeButton"
77. style="?android:buttonBarButtonStyle"
78. android:layout_width="match_parent"
79. android:layout_height="wrap_content"
80. android:layout_alignParentBottom="true"
81. android:background="@drawable/square_primary_button_drawable"
82. android:text="@string/generate_qr_code"
83. android:textColor="@color/whiteColor"
84. android:textStyle="bold" />
85.
86. </RelativeLayout>

Now in this xml, we have one EditText for the full name and one for user age. We have

an ImageView where we show the QR code and one Button for generating QR code.

I’m gonna show you quickly how to generate QR code except for the prep work.

The following shows how to generate QR code.

1. generateQrCodeButton.setOnClickListener {
2. if (checkEditText()) {
3. val user = UserObject(fullName = fullNameEditText.text.toString(), age = Integer.parseInt(ageEditText.text.toString()))
4. val serializeString = Gson().toJson(user)
5. val bitmap = QRCodeHelper
6. .newInstance(this)
7. .setContent(encryptedString)
8. .setErrorCorrectionLevel(ErrorCorrectionLevel.Q)
9. .setMargin(2)
10. .getQRCOde()
11. qrCodeImageView.setImageBitmap(bitmap)
12. }
13. }

You see in click listener we’re creating a User object for QR code. We can only create QR

code with String. So, we have to serialize the User object into a string with Gson. After that, we need

to set QR code setting for generating the code. The QRCodeHelper is my custom class for the

generating QR code.

Note: You see we’re serializing the user object when generating the code. So, we’ve to deserialize the

string into User object when the scanner successfully scanned the QR code. One more important thing

to say here please do not create a huge object for creating QR code. If you create a huge object your

scanner needs more time to scan the code.

Below is the QRCodeHelper class.

1. public class QRCodeHelper {


2.
3. private static QRCodeHelper qrCodeHelper = null;
4. private ErrorCorrectionLevel mErrorCorrectionLevel;
5. private int mMargin;
6. private String mContent;
7. private int mWidth, mHeight;
8.
9. /**
10. * private constructor of this class only access by stying in this class.
11. */
12.
13. private QRCodeHelper(Context context) {
14. mHeight = (int) (context.getResources().getDisplayMetrics().heightPixels / 2.4);
15. mWidth = (int) (context.getResources().getDisplayMetrics().widthPixels / 1.3);
16. Log.e("Dimension = %s", mHeight + "");
17. Log.e("Dimension = %s", mWidth + "");
18. }
19.
20. /**
21. * This method is for singleton instance od this class.
22. *
23. * @return the QrCode instance.
24. */
25.
26. public static QRCodeHelper newInstance(Context context) {
27. if (qrCodeHelper == null) {
28. qrCodeHelper = new QRCodeHelper(context);
29. }
30. return qrCodeHelper;
31. }
32.
33. /**
34. * This method is called generate function who generate the qrcode and return it.
35. *
36. * @return qrcode image with encrypted user in it.
37. */
38.
39. public Bitmap getQRCOde() {
40. return generate();
41. }
42.
43. /**
44. * Simply setting the correctionLevel to qrcode.
45. *
46. * @param level ErrorCorrectionLevel for Qrcode.
47. * @return the instance of QrCode helper class for to use remaining function in class.
48. */
49.
50. public QRCodeHelper setErrorCorrectionLevel(ErrorCorrectionLevel level) {
51. mErrorCorrectionLevel = level;
52. return this;
53. }
54.
55. /**
56. * Simply setting the encrypted to qrcode.
57. *
58. * @param content encrypted content for to store in qrcode.
59. * @return the instance of QrCode helper class for to use remaining function in class.
60. */
61.
62. public QRCodeHelper setContent(String content) {
63. mContent = content;
64. return this;
65. }
66.
67. /**
68. * Simply setting the width and height for qrcode.
69. *
70. * @param width for qrcode it needs to greater than 1.
71. * @param height for qrcode it needs to greater than 1.
72. * @return the instance of QrCode helper class for to use remaining function in class.
73. */
74.
75. public QRCodeHelper setWidthAndHeight(@IntRange(from = 1) int width, @IntRange(from = 1) int height) {
76. mWidth = width;
77. mHeight = height;
78. return this;
79. }
80.
81. /**
82. * Simply setting the margin for qrcode.
83. *
84. * @param margin for qrcode spaces.
85. * @return the instance of QrCode helper class for to use remaining function in class.
86. */
87.
88. public QRCodeHelper setMargin(@IntRange(from = 0) int margin) {
89. mMargin = margin;
90. return this;
91. }
92.
93. /**
94. * Generate the qrcode with giving the properties.
95. *
96. * @return the qrcode image.
97. */
98.
99. private Bitmap generate() {
100. Map<EncodeHintType, Object> hintsMap = new HashMap<>();
101. hintsMap.put(EncodeHintType.CHARACTER_SET, "utf-8");
102. hintsMap.put(EncodeHintType.ERROR_CORRECTION, mErrorCorrectionLevel);
103. hintsMap.put(EncodeHintType.MARGIN, mMargin);
104. try {
105. BitMatrix bitMatrix = new QRCodeWriter().encode(mContent, BarcodeFormat.QR_CODE, mWidth, mHeight, hintsMap);
106. int[] pixels = new int[mWidth * mHeight];
107. for (int i = 0; i < mHeight; i++) {
108. for (int j = 0; j < mWidth; j++) {
109. if (bitMatrix.get(j, i)) {
110. pixels[i * mWidth + j] = 0xFFFFFFFF;
111. } else {
112. pixels[i * mWidth + j] = 0x282946;
113. }
114. }
115. }
116. return Bitmap.createBitmap(pixels, mWidth, mHeight, Bitmap.Config.ARGB_8888);
117. } catch (WriterException e) {
118. e.printStackTrace();
119. }
120. return null;
121. }
122. }

That’s it guy’s, this is my demonstration about generating and reading QR code with the custom

object. If you guy’s want to see the code of the example, that I’ve shown you in the above see it

on GitHub.

I hope you guys learn how can we generate and read QR code. If you have any queries please do

comment below.

Thank you for being here and keep reading…

You might also like