Skip to content
Related Articles

Related Articles

How to Read QR Code using Zxing Library in Android?
  • Last Updated : 15 Jan, 2021

Zxing stands for Zebra Crossing, it is one of the most popular open-source API for integrating QR(Quick Response) Code processing. It is a barcode image processing library implemented in Java, with ports to other languages. It has support for the 1D product, 1D industrial, and 2D barcodes. Google uses ZXing by web search to obtain millions of barcodes on the web indexable. It also creates the foundation of Android’s Barcode Scanner app and is combined into Google Product and Book Search.

Note: To read QR code using CAMView Library you may refer to How to Read QR Code using CAMView Library in Android?

QR Code

It is an abbreviation for Quick Response Code. It is a combination of white and black squares and can be read easily with a QR Scanner. It generally uses four encoding modes

  • Numeric
  • Alphanumeric
  • Byte/Binary
  • Kanji

It is used for authentication and online payments. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Read QR Code using Zxing Library in Android Sample GIF



Step by Step Implementation

In this project, we are creating a basic QR Scanner application which is used to scan a QR Code and display the result over the screen.

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Note: Choose API 24 and onwards as Minimum SDK

Step 2: Adding dependencies

In order to use the Zxing library in our application we need to add it’s dependency in our application’s gradle file. For adding the dependency Go to Gradle Scripts > build.gradle(Module: app) and add the following dependencies. After adding the dependency you need to click on Sync Now.

dependencies {

   implementation ‘com.journeyapps:zxing-android-embedded:4.1.0’



}

Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. 

XML




<resources
    <color name="colorPrimary">#0F9D58</color
    <color name="colorPrimaryDark">#16E37F</color
    <color name="colorAccent">#03DAC5</color
</resources>

Step 3: Creating the layout file activity_main.xml

In this step, we will create the layout of our application, which is having a Button for scan and two TextView one is for the message content of QR Code, and the second one is for the format of the scanned message. Go to app > res > layout > activity_main.xml and add the following code snippet.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
  
    <TextView
        android:id="@+id/textContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="messageContent"/>
  
    <TextView
        android:id="@+id/textFormat"
        android:text="messageFormat"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:layout_height="wrap_content" />
  
    <Button
        android:id="@+id/scanBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:backgroundTint="#0F9D58"
        android:layout_gravity="center"
        android:text="Scan"/>
    
</LinearLayout>

Step 4: Working with MainActivity.java file

In this step, we will work with the MainActivity.java file where we first initialize the button and the two TextViews. In onClick() behavior of the button we create the object of IntentIntegrator class which is used to call initiateScan() method for scan process. After that in the onActivityResult() method, we’ll check if the scanned message is null then toast a message as “Cancelled” otherwise we’ll set the scanned message and its format over the TextViews.

Java




import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
  
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
  
// implements onClickListener for the onclick behaviour of button
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button scanBtn;
    TextView messageText, messageFormat;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // referencing and initializing
        // the button and textviews
        scanBtn = findViewById(R.id.scanBtn);
        messageText = findViewById(R.id.textContent);
        messageFormat = findViewById(R.id.textFormat);
  
        // adding listener to the button
        scanBtn.setOnClickListener(this);
  
    }
  
    @Override
    public void onClick(View v) {
        // we need to create the object 
        // of IntentIntegrator class
        // which is the class of QR library
        IntentIntegrator intentIntegrator = new IntentIntegrator(this);
        intentIntegrator.setPrompt("Scan a barcode or QR Code");
        intentIntegrator.setOrientationLocked(true);
        intentIntegrator.initiateScan();
    }
  
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        // if the intentResult is null then
        // toast a message as "cancelled"
        if (intentResult != null) {
            if (intentResult.getContents() == null) {
                Toast.makeText(getBaseContext(), "Cancelled", Toast.LENGTH_SHORT).show();
            } else {
                // if the intentResult is not null we'll set 
                // the content and format of scan message
                messageText.setText(intentResult.getContents());
                messageFormat.setText(intentResult.getFormatName());
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}

Output:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :