Generate QR Code in Android using Kotlin
Last Updated :
23 Dec, 2022
Many applications nowadays use QR codes within their application to hide some information. QR codes are seen within many payment applications which are used by the users to scan and make payments. The QR codes which are seen within these applications are generated inside the application itself. In this article, we will take a look at How to generate a QR code in Android using Kotlin. A sample video is given below to get an idea about what we are going to do in this article.
Note: If you are looking to generate QR code in android using Java. Check out the following article: How to Generate QR Code in Android using Java
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add dependency to build.gradle(Module:app)
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation 'androidmads.library.qrgenerator:QRGenerator:1.0.3'
After adding this dependency simply sync this project to install it.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
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:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--on below line we are creating
a text for heading of our app-->
<TextView
android:id="@+id/idTVHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:gravity="center"
android:padding="4dp"
android:text="QR Code Generator"
android:textAlignment="center"
android:textColor="@color/purple_200"
android:textSize="18sp"
android:textStyle="bold" />
<!--We are using this image
view to display our QR code-->
<ImageView
android:id="@+id/idIVQrcode"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:contentDescription="QR Code" />
<!--Edit text to enter text
for creating a QR code-->
<EditText
android:id="@+id/idEdt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idIVQrcode"
android:layout_marginStart="20dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="20dp"
android:autofillHints=""
android:hint="Enter your message"
android:inputType="text" />
<!--Button for creating a QR code-->
<Button
android:id="@+id/idBtnGenerateQR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdt"
android:layout_marginStart="20dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="20dp"
android:text="Generate QR Code"
android:textAllCaps="false" />
</RelativeLayout>
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package com.gtappdevelopers.kotlingfgproject
import android.graphics.Bitmap
import android.graphics.Point
import android.os.Bundle
import android.text.TextUtils
import android.view.Display
import android.view.WindowManager
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidmads.library.qrgenerator.QRGContents
import androidmads.library.qrgenerator.QRGEncoder
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
// on below line we are creating a variable
// for our image view, edit text and a button.
lateinit var qrIV: ImageView
lateinit var msgEdt: EditText
lateinit var generateQRBtn: Button
// on below line we are creating
// a variable for bitmap
lateinit var bitmap: Bitmap
// on below line we are creating
// a variable for qr encoder.
lateinit var qrEncoder: QRGEncoder
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// on below line we are
// initializing our all variables.
qrIV = findViewById(R.id.idIVQrcode)
msgEdt = findViewById(R.id.idEdt)
generateQRBtn = findViewById(R.id.idBtnGenerateQR)
// on below line we are adding on click
// listener for our generate QR button.
generateQRBtn.setOnClickListener {
// on below line we are checking if msg edit text is empty or not.
if (TextUtils.isEmpty(msgEdt.text.toString())) {
// on below line we are displaying toast message to display enter some text
Toast.makeText(applicationContext, "Enter your message", Toast.LENGTH_SHORT).show()
} else {
// on below line we are getting service for window manager
val windowManager: WindowManager = getSystemService(WINDOW_SERVICE) as WindowManager
// on below line we are initializing a
// variable for our default display
val display: Display = windowManager.defaultDisplay
// on below line we are creating a variable
// for point which is use to display in qr code
val point: Point = Point()
display.getSize(point)
// on below line we are getting
// height and width of our point
val width = point.x
val height = point.y
// on below line we are generating
// dimensions for width and height
var dimen = if (width < height) width else height
dimen = dimen * 3 / 4
// on below line we are initializing our qr encoder
qrEncoder = QRGEncoder(msgEdt.text.toString(), null, QRGContents.Type.TEXT, dimen)
// on below line we are running a try
// and catch block for initializing our bitmap
try {
// on below line we are
// initializing our bitmap
bitmap = qrEncoder.encodeAsBitmap()
// on below line we are setting
// this bitmap to our image view
qrIV.setImageBitmap(bitmap)
} catch (e: Exception) {
// on below line we
// are handling exception
e.printStackTrace()
}
}
}
}
}
Now run your application to see the output of it.
Output:
Similar Reads
Generate PDF File in Android using Kotlin
Most of the applications provide users with the facility of bills to be downloaded from the mobile applications. This type of application gets the data from the APIS or data within the application and this data is used to generate the PDF files. PDF files within android are generated using canvas. I
7 min read
How to Generate QR Code in Android?
QR codes are used in many apps to display data in machine-readable form. These codes are used to represent data in a secure manner that is readable only by machines and not by humans. We have seen many apps that provide QR codes and we can scan those QR codes with our mobile device. In this article,
4 min read
CountDownTimer in Android using Kotlin
CountDownTimer app is about setting a time that moves in reverse order as it shows the time left in the upcoming event. A CountDownTimer is an accurate timer that can be used for a website or blog to display the count down to any special event, such as a birthday or anniversary. Likewise, here letâs
2 min read
How to Generate Barcode in Android?
Barcodes are the graphical representation of data that enables effortless scanning. When we aim to incorporate this functionality for various purposes in Android applications it becomes crucial to understand the underlying principles and techniques involved in generating barcodes effectively. In thi
3 min read
Play Audio From URL in Android using Kotlin
Many applications want to add different types of audio files to their android applications. These audio files are played using a media player within the android application. We can play audio files within the android application from different sources by playing audio from a web URL or by simply add
4 min read
Android Fade In/Out in Kotlin
In Android Animations are the visuals that are added to make the user interface more interactive, clear and good looking. Fade In and Fade out animations are used to modify the appearance of any view over a set interval of time so that user can be notified about the changes that are occurring in our
3 min read
Android Exoplayer using Kotlin
ExoPlayer View is one of the most used UI components in media streaming applications for displaying video files within android applications. It is similar to that of Video View, but the quality of the video player in Exoplayer compared to video view is better. In this article, we will look at How to
3 min read
Android SQLite Database in Kotlin
Android comes with an inbuilt implementation of a database package, which is SQLite, an open-source SQL database that stores data in form of text in devices. In this article, we will look at the implementation of Android SQLite in Kotlin. SQLite is a self-contained, high-reliability, embedded, full-
5 min read
Retrofit with Kotlin Coroutine in Android
Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can e
3 min read
How to Convert Text to Speech in Android using Kotlin?
Text to Speech App converts the text written on the screen to speech like you have written âHello Worldâ on the screen and when you press the button it will speak âHello Worldâ. Text-to-speech is commonly used as an accessibility feature to help people who have trouble reading on-screen text, but it
3 min read