Implement Android QR Code Scanner Using ZXing Library in Kotlin

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.

Video Output

Download Source Code

You can download source code of this tutorial on QR code scanner using ZXing library –

Getting Started

At first, we will see some basic concepts about QR Code. For example, what is QR Code, different usages of QR Code, how to generate QR code etc. After that, we will see how to implement Android QR Code Scanner Using ZXing library in Kotlin.

  1. 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

  2. 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

  3. Generating QR Code

    Note – If you want to skip this part, you can just download sample QR Code for this tutorial. Open link in new tab. Then, right click and click on “Save As Image”. Then, move to implement QR Code Scanner section.

    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 –

    1. Go to website – http://goqr.me/.
    2. 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

Follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as ZXingLibrary. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?
Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access widget in Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

2. Adding ZXing Library in app/build.gradle

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:4.2.0'
implementation 'androidx.appcompat:appcompat:1.3.1'

This is gradle for ZXing library with appcompat 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 (dimens.xml, strings.xml). 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="helper_activity">HelperActivity</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"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/padding_medium"
    tools:context=".MainActivity">

    <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"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/nameKey"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnScan" />

    <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"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/nameKey" />

    <TextView
        android:id="@+id/site_name_key"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/site_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/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"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/site_name_key" />

    <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"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/site_name" />

</androidx.constraintlayout.widget.ConstraintLayout>

Designed ui will look like below –
Tutorialwing Android Kotlin Zxing Library UI Design

Here, we have used two buttons, two textViews. Since we know the data stored in QR Code, we can design ui accordingly.

  • Click on button, SCAN QR CODE, to start scanning QR Code.
  • Result is displayed in Name and Site Name fields.

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

Till now, we have defined only ui part in activity_main.xml file. Now, we will access view objects defined in that 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 com.tutorialwing.zxinglibrary

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.tutorialwing.zxinglibrary.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

	private lateinit var binding: ActivityMainBinding

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		binding = ActivityMainBinding.inflate(layoutInflater)
		val view = binding.root
		setContentView(view)

		setOnClickListener()
	}

	private fun setOnClickListener() {
		binding.btnScan.setOnClickListener { performAction() }

		binding.showQRScanner.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 (will be added later).

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 com.tutorialwing.zxinglibrary

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.google.zxing.integration.android.IntentIntegrator
import com.tutorialwing.zxinglibrary.databinding.ActivityMainBinding
import org.json.JSONException
import org.json.JSONObject

class MainActivity : AppCompatActivity() {

	private lateinit var binding: ActivityMainBinding
	private var qrScanIntegrator: IntentIntegrator? = null

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		binding = ActivityMainBinding.inflate(layoutInflater)
		val view = binding.root
		setContentView(view)

		setOnClickListener()
		setupScanner()
	}

	private fun setupScanner() {
		qrScanIntegrator = IntentIntegrator(this)
	}

	private fun setOnClickListener() {
		binding.btnScan.setOnClickListener { performAction() }

		binding.showQRScanner.setOnClickListener {
			// Add code to show QR Scanner Code in Fragment.
		}
	}

	private fun performAction() {
		// Code to perform action when button is clicked.
		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.
					binding.name.text = obj.getString("name")
					binding.siteName.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?
Follow steps below to solve it –

  1. 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" />
    
  2. Then, add below code into MainActivity.kt file inside setupScanner() method.

    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

Using ZXing Library in Activity

6. Creating QR code Scanner in Fragment Using ZXing Library

Just like activity, we can implement Android QR code scanner using ZXing library in fragment. So, our next topic will be using zxing library in fragment. In this part, we will have below steps –

  1. Creating User Interface For Fragment
  2. Creating Kotlin File For Fragment
  3. Defining View Object
  4. Code for QR Code Scanner in Fragment
  5. Using QR Code of Fragment in Helper Activity

6.1 Creating User Interface For Fragment

Create a new xml file (named fragment_qrcode.xml) in res/layout folder. Then, open res/layout/fragment_qrcode.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:padding="@dimen/padding_medium">

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_medium"
        android:text="@string/showing_code_in_fragment"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <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"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/label">

    </Button>

    <TextView
        android:id="@+id/nameKey"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnScan" />

    <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"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/nameKey" />

    <TextView
        android:id="@+id/site_name_key"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_default"
        android:text="@string/site_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/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"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/site_name_key" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here, we have designed ui like below –
Tutorialwing Android Kotlin Zxing Library UI Design

Here,

  • Click on button, SCAN QR CODE, to start scanning QR Code.
  • Result is displayed in Name and Site Name fields.

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 Creating Kotlin File For Fragment

Create a new Kotlin file (named QRCodeFragment.kt) in main/java/tutoriawing.com.zxinglibrary package. Then, write below code into it –

package com.tutorialwing.zxinglibrary

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.tutorialwing.zxinglibrary.databinding.FragmentQrcodeBinding

class QRCodeFragment : Fragment() {

	private lateinit var binding: FragmentQrcodeBinding

	override fun onCreateView(
		inflater: LayoutInflater,
		container: ViewGroup?,
		savedInstanceState: Bundle?
	): View {
		binding = FragmentQrcodeBinding.inflate(layoutInflater)
		return binding.root
	}
}

6.3 Defining View Object and Set Click Listener

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

package com.tutorialwing.zxinglibrary

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.tutorialwing.zxinglibrary.databinding.FragmentQrcodeBinding

class QRCodeFragment : Fragment() {

	private lateinit var binding: FragmentQrcodeBinding

	override fun onCreateView(
		inflater: LayoutInflater,
		container: ViewGroup?,
		savedInstanceState: Bundle?
	): View {
		binding = FragmentQrcodeBinding.inflate(layoutInflater)
		return binding.root
	}

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

		setOnClickListener()
	}

	private fun setOnClickListener() {
		binding.btnScan.setOnClickListener { performAction() }
	}

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

6.4 Code for QR Code Scanner in Fragment

Till now, we have defined ui, setup etc. for scanning. 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 com.tutorialwing.zxinglibrary

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.google.zxing.integration.android.IntentIntegrator
import com.tutorialwing.zxinglibrary.databinding.FragmentQrcodeBinding
import org.json.JSONException
import org.json.JSONObject

class QRCodeFragment : Fragment() {

	private lateinit var binding: FragmentQrcodeBinding
	private lateinit var qrScanIntegrator: IntentIntegrator

	override fun onCreateView(
		inflater: LayoutInflater,
		container: ViewGroup?,
		savedInstanceState: Bundle?
	): View {
		binding = FragmentQrcodeBinding.inflate(layoutInflater)
		return binding.root
	}

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

		setupScanner()
		setOnClickListener()
	}

	private fun setupScanner() {
		qrScanIntegrator = IntentIntegrator.forSupportFragment(this)
		qrScanIntegrator.setOrientationLocked(false)
	}

	private fun setOnClickListener() {
		binding.btnScan.setOnClickListener { performAction() }
	}

	private fun performAction() {
		// Code to perform action when button is clicked.
		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.
					binding.name.text = obj.getString("name")
					binding.siteName.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.

6.5 Using QR Code of Fragment in Helper Activity

Till now, we have defined ui for scanning in fragment, written code to scan QR Code in fragment etc. Now, we will use this fragment, i.e. QRCodeFragment, in Helper Activity and Scan some QR Code.

So, create helper activity, it’s xml file to use implemented QR Code in fragment. Follow steps below to do it –

  1. Create a new xml file , named activity_helper.xml, in main/res/layout/ folder. Then, add below code into it –
    <?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>
    
  2. Now, Create a new Kotlin file, named HelperActivity.kt, in main/java/tutorialwing.com.zxinglibrary package. Then, write below code in it –
    package com.tutorialwing.zxinglibrary
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.zxinglibrary.databinding.ActivityHelperBinding
    
    class HelperActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityHelperBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityHelperBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    	}
    }
    
  3. Now, mention about this Activity File in AndroidManifest.xml file. So, add below line in AndroidManifest.xml file –
    <activity
         android:name=".HelperActivity"
         android:label="@string/helper_activity" />
    
  4. Now, write code to add fragment, QRCodeFragment into HelperActivity. So, add below line in HelperActivity –
    supportFragmentManager
    	.beginTransaction()
    	.add(R.id.rootContainer, QRCodeFragment())
    	.commit()
    

    Finally, HelperActivity.kt file will be –

    package com.tutorialwing.zxinglibrary
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.zxinglibrary.databinding.ActivityHelperBinding
    
    class HelperActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityHelperBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityHelperBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		addFragment()
    	}
    
    	private fun addFragment() {
    		supportFragmentManager
    			.beginTransaction()
    			.add(R.id.rootContainer, QRCodeFragment())
    			.commit()
    	}
    }
    
  5. Call to Show HelperActivity

    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 HelperActivity when this button is clicked.

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

    Finally, it will be like

    binding.showQRScanner.setOnClickListener {
    	// Add code to show QR Scanner Code in Fragment.
    	startActivity(Intent(this@MainActivity, HelperActivity::class.java))
    }
    

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="com.tutorialwing.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/Theme.ZXingLibrary">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <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=".HelperActivity"
            android:label="@string/helper_activity" />
    </application>

</manifest>

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 in Fragment

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.

7. 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 Bar Code 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.

Leave a Reply