QR stands for "Quick Response" Which is a two-dimensional version of the barcode. QR Code stores small piece of information like plain text, URL, email address, product’s unique information. Information is hidden from the outside world. QR Code and Barcode are very popular nowadays.

In this blog, we will learn How to create QR Code and Barcode scanner using ZXing library. Please follow below steps to create QR Code scanner. 

Step 1. Create an Android Project with an empty Activity called MainActivity.  As we have created Activity, two files activity_main.xml and MainActivity.java will be created in its correspondent folders. You have to create two more activity QRCodeScanActivity and ScanResultActivity. One is used to scan the QR Code and second is used to show result text stored in QR Code. See project structure given at end of this blog.

Step to create new Activity: Right click on app-> New-> Activity-> Empty Activity-> Give proper name and Finish.

Step 2. Open app/build.gradle file and add Google Mobile Vision API library me.dm7.barcodescanner:zxing:1.9.8 in gradle file. After adding the library Sync project.

app/build.gradle

apply plugin: 'com.android.application'

  

android {

    compileSdkVersion 23

    buildToolsVersion "28.0.3"

  

    defaultConfig {

        applicationId "com.example.qrcodescannerusingzxing"

        minSdkVersion 15

        targetSdkVersion 23

        versionCode 1

        versionName "1.0"

    }

    buildTypes {

        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }

    }

}

  

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])

    testCompile 'junit:junit:4.12'

    compile 'com.android.support:appcompat-v7:23.4.0'

    compile 'me.dm7.barcodescanner:zxing:1.9.8' /* Add this dependency */

}

Step 3. Setup permission to access the mobile camera in AndroidMenifest.xml file.

AndroidMenifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.qrcodescannerusingzxing">

  

    <!-- Set permission to access Camera -->

    <uses-permission android:name="android.permission.CAMERA" />

  

    <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=".QRCodeScanActivity" />

        <activity android:name=".ScanResultActivity" />

    </application>

  

</manifest>

Step 4. Open activity_main.xml, modify it according to your requirements. Below the code is given.

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:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="#ffffff"

    tools:context=".MainActivity">

  

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:layout_marginBottom="40dp"

        android:gravity="center"

        android:orientation="vertical">

  

        <ImageView

            android:layout_width="120dp"

            android:layout_height="120dp"

            android:layout_marginBottom="20dp"

            android:src="@drawable/qrcode" />

  

        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Click button to scan your QR Code"

            android:textSize="16dp" />

  

    </LinearLayout>

  

    <Button

        android:id="@+id/btnScanQRCode"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_alignParentBottom="true"

        android:padding="15dp"

        android:text="Scan QR Code"

        android:textSize="18dp" />

  

</RelativeLayout>

Step 5. Now open MainActivity.java file and write below code. On button click, it will open new activity which will be used to scan QR Code.

MainActivity.java

package com.example.qrcodescannerusingzxing;

  

import android.content.Intent;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

  

public class MainActivity extends AppCompatActivity {

  

    Button btnScanQRCode;

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

  

        btnScanQRCode = (Button) findViewById(R.id.btnScanQRCode);

        btnScanQRCode.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Intent intent = new Intent(MainActivity.this, QRCodeScanActivity.class);

                startActivity(intent);

            }

        });

    }

}

Step 6. As you click on Scan QR Code button it will open QRCodeScanActivity. It will ask you for permission to access the camera and as you allow, you will be able to scan the QR Code. When QR Code will detect it will do beep sound and redirect you to the next activity to show text stored in QR Code. Its code for XML and java file is given below. The XML file should be blank. Please read my comments properly to understand the code.

activity_qrcode_scan.xml

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".QRCodeScanActivity">

  

</LinearLayout>

QRCodeScanActivity.java

package com.example.qrcodescannerusingzxing;

  

import android.Manifest;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.media.AudioManager;

import android.media.ToneGenerator;

import android.support.v4.app.ActivityCompat;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

import com.google.zxing.Result;

  

/* Implement Activity with ZXingScannerView.ResultHandler */

public class QRCodeScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {

  

    private ZXingScannerView scannerView;

    String resultText = "";

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

  

        scannerView = new ZXingScannerView(this); /* Initialize object */

        setContentView(scannerView); /* Set the ScannerView as a content of current activity */

  

    }

  

    @Override

    public void onResume() {

        super.onResume();

       /* Asking user to allow access of camera */

        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {

            scannerView.setResultHandler(this); /* Set handler for ZXingScannerView */

            scannerView.startCamera(); /* Start camera */

        } else {

            ActivityCompat.requestPermissions(QRCodeScanActivity.this, new

                    String[]{Manifest.permission.CAMERA}, 1024);

        }

    }

  

    @Override

    public void onPause() {

        super.onPause();

        scannerView.stopCamera(); /* Stop camera */

    }

  

    @Override

    public void handleResult(Result scanResult) {

  

        ToneGenerator toneNotification = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100); /* Setting beep sound */

        toneNotification.startTone(ToneGenerator.TONE_PROP_BEEP, 150);

  

        resultText = scanResult.getText(); /* Retrieving text from QR Code */

  

        Intent intent = new Intent(QRCodeScanActivity.this, ScanResultActivity.class);

        intent.putExtra("ResultText", resultText); /* Sending text to next activity to display */

        startActivity(intent);

  

        /* scannerView.resumeCameraPreview(this); */ /* If you want resume scanning, call this method */

    }

}

Understanding the code

  • ZXingScannerView: It is used to capture a view of the camera and to scan QR Code detected by the camera. As our activity_qrcode_scan.xml is blank, no design is available, ZXingScannerView will be set as content for this activity using setContentView(scannerView) method. The whole activity is act as a QR Code scanner.
  • onResume: This method basically calls when activity comes to the foreground. In this app when this method runs, it will ask the user for permission to access camera. As user allow, camera and scanner will start. Also handle is initialized for scannerview.
  • handleResult: This method is initialized to sannerview using scannerView.setResultHandler(this) which is called when QR Code detect and any information received that stored in it. scanResult.getText() method is used to retrieve text from QR Code. Please see my code to understand it.
  • onPause: This method call when any interruptive event occurs to the application which will stop scannerview to scan using scannerView.stopCamera() method.
  • Resume camera preview: If somehow scannerview doesn’t scan QR Code, you can resume scanner using scannerView.resumeCameraPreview(this) method.
  • ToneGenerator: It is used to set beep sound on QR Code detection.

Step 7. Open ScanResultActivity and modify it. This activity retrieves text sent from previous activity and display it. The code is given below.

activity_scan_result.xml

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:paddingTop="50dp"

    tools:context=".ScanResultActivity">

  

    <ImageView

        android:layout_width="80dp"

        android:layout_height="80dp"

        android:layout_gravity="center_horizontal"

        android:src="@drawable/resulticon" />

  

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="40dp"

        android:orientation="vertical">

  

        <TextView

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:paddingBottom="15dp"

            android:paddingLeft="20dp"

            android:text="QR Code details"

            android:textSize="16dp" />

  

        <TextView

            android:id="@+id/txtScanResult"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:background="#ffffff"

            android:padding="20dp"

            android:text="No data found..!!"

            android:textColor="#000000"

            android:textSize="18dp" />

  

    </LinearLayout>

  

</LinearLayout>

ScanResultActivity.java

package com.example.qrcodescannerusingzxing;

  

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.TextView;

  

public class ScanResultActivity extends AppCompatActivity {

  

    TextView txtScanResult;

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_scan_result);

  

        txtScanResult = (TextView) findViewById(R.id.txtScanResult); /* Find TextView and initialize it to object */

  

        Bundle extras = getIntent().getExtras();

        if (extras != null) {

            String scanResult = extras.getString("ResultText"); /* Retrieving text of QR Code */

            txtScanResult.setText(scanResult);

        }

    }

}

Step 8. Now run your application, scan QR Code and see the result. If you have any query please comment to ask it.

Output

Your Project Structure may look like,

Hope this blog will help you. Thank you..!!