Open In App

How to Read QR Code using Zxing Library in Android?

Last Updated : 15 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:



Previous Article
Next Article

Similar Reads

How to Read QR Code using CAMView Library in Android?
CAMView Library is a simple solution for accessing users' device camera. By using this library we can access users' cameras and use to perform so many functions of the camera such as scanning barcodes that are done by using a built-in ZXing decoding engine. This library contains a set of components that are ready to be put in your layout in order t
5 min read
How to Add OpenCV library into Android Application using Android Studio?
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. When it integrated with various libraries,
3 min read
Implementation of Facebook’s Android Device Year Class Library in Android
As developers, we always aim to create an application that would run smoothly on millions of devices, however, the performance of practically every application is influenced by the device specifications. There are currently over 16,000 handsets on the market with varying specifications, and the application may perform poorly on some devices when co
3 min read
How to Use Android Sliding Activity Library in Android App?
Sliding activities allow you to easily set header content, menus, and data onto slidable screens. Easily create activities that can slide vertically on the screen and fit well into the material design age. We can set header images to our sliding activity. We can also customize the color that will affect the header and the status bar. We can also di
3 min read
How to Use Fast Android Networking Library in Android with Example?
In Android, we know multiple networking libraries like Retrofit, Volley. We use these libraries specifically for making networking requests like performing actions on API. But Besides that, there is another library called Fast Networking Library which has a few advantages over other libraries. In this tutorial, we will be specifically focusing on l
4 min read
How to Convert Java Code to Kotlin Code in Android Studio?
In Google I/O 2017, Kotlin has been declared as an official language for Android app development. This language gains popularity among developers very quickly because of its similarities as well as interoperable with Java language. One can mix code of Java and Kotlin while designing an Android project. Some of the major challenges faced by develope
4 min read
How to Convert Kotlin Code to Java Code in Android Studio?
Java programming language is the oldest and most preferred language for Android app development. However, during Google I/O 2017, Kotlin has been declared as an official language for Android development by the Google Android Team. Kotlin has gained popularity among developers very quickly because of its similarities as well as interoperable with th
4 min read
CRUD Operation in MySQL Using PHP, Volley Android - Read Data
In the previous article, we have performed the insert data operation. In this article, we will perform the Read data operation. Before performing this operation first of all we have to create a new PHP script for reading data from SQL Database. Prerequisite: You should be having Postman installed in your system to test this PHP script. Create a PHP
9 min read
How to Read Data From SQLite Database in Android using Jetpack Compose?
In the 1st part of our SQLite database, we have seen How to Create and Add Data to SQLite Database in Android using Jetpack Compose. In that article, we have added data to our SQLite Database. In this article, we will read all this data from the SQLite database and display this data in our ListView using Jetpack Compose. What we are going to build
15 min read
Custom Toast in Android Using PoiziToast Library
A Toast provides information/feedback about an operation. It is a small popup that appears on the current activity UI and automatically disappears after a timeout. In this article, we will learn how to create customized Toast using PoiziToast Library in android. So, we will understand this by making a simple app to display customized Toast. What is
2 min read