Implement Android QR Code Scanner Using ZXing Library in Kotlin

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.
In this tutorial, we will study about one of the popular android library for QR Code scanner in android application. We will see how to implement android QR Code Scanner Using ZXing library in kotlin. We will see how to use ZXing library in activity, how to use ZXing library in fragment etc. Since kotlin is official programming language for android application development, this tutorial has been covered in kotlin programming language. However, you can get source code for android ZXing library in kotlin and java both.

Video Output

Download Source Code

You can download source code of this tutorial on qr code scanner using ZXing library by entering the details –

Getting Started

At first, we will see some basic concepts about QR Code. Then, we will see how to implement Android QR Code Scanner Using ZXing library in kotlin.

What is QR Code?

QR Code (abbreviated from Quick Response Code) is a trademark for two dimensional bar code that contains information about the item to which it is attached.

It became popular due to it’s fast readability and greater storage capacity compared to standard UPC barcode.
A QR Code consists of black squares arranged in a square grid on a white background that can be read by an imaging devices such as camera. For example,

Tutorialwing Android QR Code Scanner Using ZXing Library in Kotlin ZXing Library

QR Code Sample

Different Uses of QR Code

QR Code can be used in different ways –
– Most commonly in consumer advertising.
– URLs redirection.
– QR Code Payment.
– Website Login.
– WIFI Network Login.
– Video games and many more

For the sake of simplicity of this post, we have just given an introduction about QR Code. If you want to learn more about QR Code – Visit https://en.wikipedia.org/wiki/QR_code

Generating QR Code

Note – If you want to skip this part, you can just download sample QR Code for this tutorial. Right click and click on “Save As Image”. Then, move to implement QR Code Scanner.

Since we know what a QR Code is, we will see how to implement QR Code scanner in android application. This scanner helps us to retrieve the data stored in QR Code. Before implementing android QR Code scanner, we will see how to generate QR Code.

Here, we will use http://goqr.me/ to generate QR Code. Generated QR Code will be used as a sample QR Code in this tutorial.

Follow steps below to generate QR code –
(a) Go to website – http://goqr.me/.
(b) Screen similar to shown as below will appear.

Tutorialwing Generate QR Code Kotlin

Generate QR Code

Enter the text as shown in the Section 2. Contents. Then, click on the download button (as shown in bottom-right of the above image).

Note that we are assuming that you have entered text in json format. Here, we have entered

{"name": "Rajeev Kumar", "site_name": "Tutorialwing.com"}



Implementing QR Code Scanner Using ZXing Library

Till now, we have seen what a QR Code is, different uses of QR Code, how to generate QR Code etc. Now, we will see how to implement android QR Code scanner using ZXing library in kotlin.

As we already know, a QR Code scanner is used to retrieve the data stored in the QR code. We have already generated a QR code and stored some data – {“name”: “Rajeev Kumar”, “site_name”: “Tutorialwing.com”}

Now, we will create a scanner that will retrieve this information.

You may see Button, TextView and Different Android Project Structures to understand this post (qr code scanner using zxing library) clearly.

So, Let’s start by creating a new android application.

1. Creating New Project in Kotlin

Follow steps below to create new project. Please ignore the steps if you have already created the project.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as ZXingLibrary. Then, check Include Kotlin Support and click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. You will get a newly created project successfully if you have followed steps properly. If you want, visit post to get the steps in detail to create a new project

2. Adding ZXing Library

As we have already mentioned, we will be using ZXing library to create QR Code Scanner. So, once your project is created successfully, Open app/build.gradle file. Then, add below code into it.

implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
implementation 'com.android.support:appcompat-v7:27.1.1'

This is gradle for ZXing library with support library packages.

After adding ZXing library gradle, Sync your project by clicking on Sync Now button shown at top-right section of the IDE.

3. Modify values Folder

Now, we will add code into values folder. These code contains all constants values to be used in the application. So, it would be better if you add it now to avoid any error.

Open res/values/strings.xml file. Then, add below code into it.

<resources>
    <string name="app_name">ZXingLibrary</string>
    <string name="showing_code_in_fragment">Showing code in fragment</string>
    <string name="scan_qr_code">SCAN QR CODE</string>
    <string name="name">Name</string>
    <string name="empty">---</string>
    <string name="site_name">Site Name</string>
    <string name="scan_a_code">Scan a QR Code</string>
    <string name="result_not_found">Result Not Found</string>
    <string name="show_scanner_from_fragment">Show Scanner From Fragment</string>
</resources>

Then, open res/values/dimens.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="padding_medium">20dp</dimen>
    <dimen name="padding_high">30dp</dimen>
    <dimen name="padding_default">10dp</dimen>
    <dimen name="padding_low">5dp</dimen>
    <dimen name="padding_highest">40dp</dimen>
</resources>

Till now, we have added ZXing library in our application. Then, we have added all the constant values to be used in the application. Now, we will implement the QR Code scanner in activity as well as in fragment.

So, Let’s start by creating QR Code Scanner in Activity.

4. Creating QR Code Scanner in Activity Using ZXing Library

Now, we will see how to implement QR Code scanner in activity.

At first, we will create user interface. Then, we will implement QR code scanner using zxing library.

4.1 Creating User Interface for Activity

Open res/layout/activity_main.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="@dimen/padding_medium">

    <Button
        android:id="@+id/btnScan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/padding_high"
        android:text="@string/scan_qr_code">

    </Button>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/name" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/empty"
        android:textStyle="bold|italic" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/site_name" />

    <TextView
        android:id="@+id/site_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/empty"
        android:textStyle="bold|italic" />

    <Button
        android:id="@+id/showQRScanner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/padding_highest"
        android:text="@string/show_scanner_from_fragment" />

</LinearLayout>

Here, we have defined user interface to start scanning the QR code on button click and show the result in textView.

Note – Since we know about the types of data stored in QR Code. We have created the user interface accordingly. However, you can design interface as per your need.

You can see one more button with id showQRScanner that show, whenever it is clicked, user interface implemented for QR Code Scanner in fragment.



4.2 Defining View Object and Click Listener

Now, we will access view objects defined in xml file and set click listener in button to perform QR Code scanning using ZXing library.

So, open your main/java/tutorialwing.com.zxinglibrary/MainActivity.kt file. Then, add below code into it.

package tutorialwing.com.zxinglibrary

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    internal var txtName: TextView? = null

    internal var txtSiteName: TextView? = null

    internal var btnScan: Button? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        txtName = findViewById(R.id.name)
        txtSiteName = findViewById(R.id.site_name)

        btnScan = findViewById(R.id.btnScan)
        btnScan!!.setOnClickListener { performAction() }

        val button = findViewById<Button>(R.id.showQRScanner)
        button?.setOnClickListener { 
            // Add code to show QR Scanner Code in Fragment.
        }
    }

    private fun performAction() {
        // Code to perform action when button is clicked.
    }
}

Here, we have defined view objects and set click listener on button to perform some actions.

4.3 Code for QR Code Scanner in Kotlin

Now, we will add the code to scan the QR Code using ZXing library in kotlin.

So, open your main/java/tutorialwing.com.zxinglibrary/MainActivity.kt file. Then, add below code into it.

package tutorialwing.com.zxinglibrary

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast

import com.google.zxing.integration.android.IntentIntegrator

import org.json.JSONException
import org.json.JSONObject

class MainActivity : AppCompatActivity() {

    internal var txtName: TextView? = null

    internal var txtSiteName: TextView? = null

    internal var btnScan: Button? = null

    internal var qrScanIntegrator: IntentIntegrator? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        txtName = findViewById(R.id.name)
        txtSiteName = findViewById(R.id.site_name)

        btnScan = findViewById(R.id.btnScan)
        btnScan!!.setOnClickListener { performAction() }

        qrScanIntegrator = IntentIntegrator(this)

        val button = findViewById<Button>(R.id.showQRScanner)
        button?.setOnClickListener { 
              // Add code to show QR Scanner Code in Fragment.
        }
    }

    private fun performAction() {
        qrScanIntegrator?.initiateScan()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            // If QRCode has no data.
            if (result.contents == null) {
                Toast.makeText(this, getString(R.string.result_not_found), Toast.LENGTH_LONG).show()
            } else {
                // If QRCode contains data.
                try {
                    // Converting the data to json format
                    val obj = JSONObject(result.contents)

                    // Show values in UI.
                    txtName?.text = obj.getString("name")
                    txtSiteName?.text = obj.getString("site_name")

                } catch (e: JSONException) {
                    e.printStackTrace()

                    // Data not in the expected format. So, whole object as toast message.
                    Toast.makeText(this, result.contents, Toast.LENGTH_LONG).show()
                }

            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }
}

Here, we are starting the QR Code scanning when button is clicked. Then, retrieving the scanned data in onActivityResult method. After that, we are showing the data in textViews.

Note that we have not done anything in click listener set to button with id showQRScanner. We will use this later in this tutorial.

5. Problem in Landscape and Portrait Mode Change Automatically?

At this point of time, when you run the app, you will notice that whenever you click on button (SCAN QR CODE), camera is displayed in landscape mode. The orientation mode changes back to portrait mode as soon as QR Code scanning is complete. This causes frustration because your app orientation mode changes rapidly.

How to solve this?

– Add code to check app’s orientation into AndroidManifest file. So, open main/AndroidManifest.xml file. Then, add below code into it.

<activity
      android:name="com.journeyapps.barcodescanner.CaptureActivity"
      android:screenOrientation="fullSensor"
      tools:replace="screenOrientation" />

– Then, add below code into MainActivity.kt file.

qrScanIntegrator = IntentIntegrator(this)
qrScanIntegrator?.setOrientationLocked(false)

Now, run the app. You will notice that screen orientation is not changing now. You will get output as shown below –

Tutorialwing Android QR Code Scanner Using ZXing library Output Using Kotlin

QR Code Scanner Using ZXing library Output



6. Implementing Android QR Code Scanner in Fragment

Just like activity, we can implement Android QR code scanner using ZXing library in fragment.

Now, we will create fragment and it’s user interface. So,
1. Create a new kotlin file ( named QRCodeFragment.kt) in main/java/tutoriawing.com.zxinglibrary package.
2. Create a new xml file (named fragment_qrcode.xml) in res/layout folder.

6.1 Creating User Interface

Open res/layout/fragment_qrcode.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical"
    android:padding="@dimen/padding_medium">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_medium"
        android:text="@string/showing_code_in_fragment" />

    <Button
        android:id="@+id/btnScan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/padding_high"
        android:text="@string/scan_qr_code">

    </Button>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/name" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/empty"
        android:textStyle="bold|italic" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/site_name" />

    <TextView
        android:id="@+id/site_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/empty"
        android:textStyle="bold|italic" />

</LinearLayout>

Here, we have shown a button and some textViews that will display the data retrieved from QR Code after scanning using ZXing library.

6.2 Defining View Object

Now, we will add code in QRCodeFragment.kt file to access objects defined in xml file. Then, perform some operations on click. So, open main/java/tutoriawing.com.zxinglibrary/QRCodeFragment.kt file. Then, add below code into it.

package tutorialwing.com.zxinglibrary

import android.app.Fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast

class QRCodeFragment : Fragment() {

    internal var txtName: TextView? = null

    internal var txtSiteName: TextView? = null

    internal var btnScan: Button? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_qrcode, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        txtName = view.findViewById(R.id.name)
        txtSiteName = view.findViewById(R.id.site_name)

        btnScan = view.findViewById(R.id.btnScan)
        btnScan!!.setOnClickListener { performAction() }

        super.onViewCreated(view, savedInstanceState)
    }

    private fun performAction() {
        // Add code to perform some operation when button is clicked. 
    }
}

6.3 Code for QR Code Scanner in Fragment

Now, we will add code to create android QR code scanner in fragment (QRCodeFragment.kt). So, open main/java/tutoriawing.com.zxinglibrary/QRCodeFragment.kt file. Then, add below code into it.

package tutorialwing.com.zxinglibrary

import android.app.Fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast

import com.google.zxing.integration.android.IntentIntegrator
import com.google.zxing.integration.android.IntentResult

import org.json.JSONException
import org.json.JSONObject

class QRCodeFragment : Fragment() {

    internal var txtName: TextView? = null

    internal var txtSiteName: TextView? = null

    internal var btnScan: Button? = null

    internal var qrScanIntegrator: IntentIntegrator? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_qrcode, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        txtName = view.findViewById(R.id.name)
        txtSiteName = view.findViewById(R.id.site_name)

        btnScan = view.findViewById(R.id.btnScan)
        btnScan!!.setOnClickListener { performAction() }

        qrScanIntegrator = IntentIntegrator.forFragment(this)
        qrScanIntegrator?.setOrientationLocked(false)

        super.onViewCreated(view, savedInstanceState)
    }

    private fun performAction() {
        qrScanIntegrator?.initiateScan()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            // If QRCode has no data.
            if (result.contents == null) {
                Toast.makeText(activity, R.string.result_not_found, Toast.LENGTH_LONG).show()
            } else {
                // If QRCode contains data.
                try {
                    // Converting the data to json format
                    val obj = JSONObject(result.contents)

                    // Show values in UI.
                    txtName?.text = obj.getString("name")
                    txtSiteName?.text = obj.getString("site_name")

                } catch (e: JSONException) {
                    e.printStackTrace()

                    // Data not in the expected format. So, whole object as toast message.
                    Toast.makeText(activity, result.contents, Toast.LENGTH_LONG).show()
                }

            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }
}

Here, we have added code to start the qr code scanning when button is clicked. Then, we are retrieving the data in onActivityResult method. Then, result is being shown in respective textViews.

7. Using Fragment QR Code Scanner

Now, we will create helper activity, it’s xml file to use implemented qr code in fragment.

7.1 Creating Helper Activity

We will create a new activity and use QRCodeFragment in it to show how it works. So, create new

(1) a new kotlin file, named SecondActivity.kt, in main/java/tutorialwing.com.zxinglibrary package.
(2) a new xml file , named activity_second.xml, in main/res/layout/ folder.

Now, add below code into main/java/tutorialwing.com.zxinglibrary/SecondActivity.kt file.

package tutorialwing.com.zxinglibrary

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        fragmentManager
                .beginTransaction()
                .add(R.id.rootContainer, QRCodeFragment(), "")
                .commit()
    }
}

Then, add below code into main/res/layout/activity_second.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="@dimen/padding_low">

</LinearLayout>

Then, mention about this new activity in AndroidManifest file. Add below code into AndroidManifest.xml file.

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

Remember AndroidManifest.xml file is very important file in android application. Finally, our AndroidManifest.xml file would look like below –

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="tutorialwing.com.zxinglibrary">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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="com.journeyapps.barcodescanner.CaptureActivity"
            android:screenOrientation="fullSensor"
            tools:replace="screenOrientation" />

        <activity android:name=".SecondActivity"></activity>
    </application>

</manifest>



7.3 Call to Show SecondActivity

Remember we have defined a button with id showQRScanner in MainActivity. Then, we have set click listener in it. Now, add below code to show SecondActivity when this button is clicked.

startActivity(Intent(this@MainActivity, SecondActivity::class.java))

Finally, it will be like

val button = findViewById<Button>(R.id.showQRScanner)
button?.setOnClickListener { startActivity(Intent(this@MainActivity, SecondActivity::class.java)) }

Now, run the app. Click on button to show “Scanner From Fragment”. You will see user interface defined in fragment.

Tutorialwing Android ZXing Library Output QR Code scanner in fragment

Android ZXing Library Output

Note – For simplicity of this project, we have defined the user interface in fragment to similar as that of activity. However, you can define it as per your need.

This completes implementation of Android QR Code Scanner using ZXing library in fragment.

Now, we will see some more concepts on how can you customise the default features provided in ZXing library.

8. Customise QR Code Scanner Using ZXing Library

Till now, whatever we have discussed is default features provided by ZXing library. However, you can customise it if needed. For example, you can turn on/off beep sound you hear when QR Code scanning is complete, choose camera to scan the code etc.

Different options to customise QR code scanner using zxing library are as below –

(1) Change prompt message – When you run the app and start scanning, you can see a text message shown at bottom of the screen. You can change this prompt message as below –

qrScanIntegrator?.setPrompt(getString(R.string.scan_a_code))

(2) Change Camera – You can select which camera you want to use for QR Code scanning. You can do it as below –

qrScanIntegrator?.setCameraId(0)  // Use a specific camera of the device

(3) ON/OFF Beep Sound – You clearly hear a beep sound when scanning of any QR Code is complete. You can turn it on or off as per your need. You can do it as below –

qrScanIntegrator?.setBeepEnabled(false)

(4) Get the barcode image path – If you need to get the barcode image path, you can get it in result intent as below –

qrScanIntegrator?.setBarcodeImageEnabled(true)

This completes our tutorial on implementing Android QR Code Scanner Using ZXing library in kotlin.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners