How to Generate QRCode in Android?

Many apps use QR codes to show data in a way that is machine-readable. Data is represented using these codes in a secure manner such that only computers, not humans, are able to read it. Numerous apps that offer QR codes that we can scan with our mobile device have been spotted. We'll look at how to create a QR Code for our app in this tutorial. So, to implement this feature, we'll use a GitHub library.

Android's implementation of the QR Code Generator

To create a QR Code that displays the data inside it, we'll be building a straightforward programme that acts as a generator of QR Codes. You may get a general concept of what we'll be doing in this tutorial by looking at the sample GIF that is provided below. We are not constructing this project in Java, though.

Step by Step Execution

Step 1: Create a New Project

Instructions on how to achieve this can be found in the article How to Create/Start a New Project in Android Studio. Make sure you choose Java as your programming language.

Step 2: Requirement addition in build.gradle ( Module:app )

You may add the dependent shown below in the dependencies section by going to Gradle Scripts >build.gradle(Module:app).

implementation ‘androidmads.library.qrgenearator:QRGenearator:1.0.3’

To sync the project, choose Sync now in the top right corner.

Step 3: Implement changes to the strings.xml file

The strings.xml file's source code is shown below.

XML Code:

<resources>
	<string name="application_name"> My App</string>
	<string name=" QR_code"> QR_code</string>
	<string name="enter_your_details ">Enter your details </string>
	<string name="generate_the_QR_code">Generate the QR Code</string>
</resources>

Step 4: Using the activity main.xml file

The following code should be referenced in the activity main.xml file. The activity main.xml file's source code is shown below.

<?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:layout_width="match_parent"
	android:layout_height="match_parent"
	tools:context=".MainActivity">


	<!--Our QR code will be shown
 using this image view. -->
	<ImageView
		android:id="@+id/idIVQrcode1"
		android:layout_width="320dp"
		android:layout_height="320dp"
		android:layout_centerHorizontal="true"
		android:layout_marginTop="50dp"
		android:contentDescription="@string/QR_code" />


	<!--Edit text for entering the text
		to create a QR code-->
	<EditText
		android:id="@+id/idEdt1"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_below="@id/idIVQrcode1"
		android:layout_marginStart="25dp"
		android:layout_marginTop="35dp"
		android:layout_marginEnd="25dp"
		android:autofillHints=""
		android:hint="@string/enter_your_details"
		android:inputType="text"/>


	<!--Button to generate a QR code -->
	<Button
		android:id="@+id/idBtnGenerateQR1"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_below="@id/idEdt"
		android:layout_marginStart="25dp"
		android:layout_marginTop="35dp"
		android:layout_marginEnd="20dp"
		android:text="@string/generate_QR_code" />


</RelativeLayout>

Step 5: Accessing and using the MainActivity.java file

The following code should be found in the MainActivity.java file. The MainActivity.java file's source code is shown below. Inside the code, comments are added to help the reader comprehend it better.

Java Code:

import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.WriterException;
import androidmads.library.qrgenearator.QRGContents;
import androidmads.library.qrgenearator.QRGEncoder;


public class MainActivity extends AppCompatActivity {


	// variables for the bitmap, button, edittext,
	// imageview, and qrencoder .
	private ImageView qrCodeIV1 ;
	private EditText dataEdt1 ;
	private Button generateQrBtn1 ;
	Bitmap bitmap1 ;
	QRGEncoder qrgEncoder1 ;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// we are initialising all the variables .
		qrCodeIV1 = findViewById(R.id.idIVQrcode1);
		dataEdt1 = findViewById(R.id.idEdt1);
		generateQrBtn1 = findViewById(R.id.idBtnGenerateQR);


		// establishing the button's onclick listener.
		generateQrBtn1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (TextUtils.isEmpty(dataEdt1.getText().toString())) {
					
					// The method will be executed and a toast message displayed
					// if the edittext inputs are empty .
					Toast.makeText(MainActivity.this, "Enter text for generating a QR Code", Toast.LENGTH_SHORT).show();
				} else {
					// the windowmanager service can be obtained 
					// with the line below.
					WindowManager manager1 = (WindowManager) getSystemService(WINDOW_SERVICE);					
					// setting up a variable to display by default.					Display display1 = manager1.getDefaultDisplay();				
					// establishing a variable for the point that
					// will be shown in the QR code.
					Point point1 = new Point();
					display.getSize(point1);					
					// getting height and
					// width of a certain point
					int width1 = point1.x;
					int height1 = point1.y;				
					// dimension creation using width and height .
					int dimen1 = width1< height1 ? width1 : height1 ;
					dimen1 = dimen1 * 3 / 4;
					
					// Setting these dimensions in our qr code
					// encoder will produce our qr code.
					qrgEncoder1 = new QRGEncoder(dataEdt1.getText().toString(), null, QRGContents.Type.TEXT, dimen1);
					try {
					// obtaining our QR Code as a Bitmap.
						Bitmap1 = qrgEncoder.encodeAsBitmap();
					// the bitmap is for setting the inside our image
					// using the.setimagebitmap function to view.
						qrCodeIV1.setImageBitmap(bitmap1 );
					} catch (WriterException e) {
						// In order to handle exceptions,
						// this procedure is used.
						Log.e("Tag", e.toString());
					}
				}
			}
		});
	}
}

Output:

How to Generate QRCode in Android

Related Topics

How to insert an email in android application in android version 8

Email Address Insertion It is used to insert email adrress from the user in the android application.The only point of difference between an EditText and an Emailtext is that EmailText consisits...

1 minute read.

Android ScrollView

A ScrollView is a view group that is used to create vertically scrollable views in an android application. Only a single direct child can be contained by ScrollView. For placing...

5 minutes read.

What is Android Studio

Android Studio powered by the IntelliJ platform is an integrated development environment (IDE) and is officially recognized for developing androidapplications. Its foundation lies on JetBrains' IntelliJ IDEA and is specialized...

3 minutes read.

Android EditText

In Android, EditText is a UI widget utilized to allow the user to input or change the text. While using the EditTextwidget in your Android application, you need to use...

4 minutes read.

Android Toast

Android is one of the most successful operating systems available in today's world. It is an open-source phone platform, compatible with almost all the devices. There are numerous features and...

3 minutes read.

How to Update Gradle in Android Studio?

The Android Gradle plugin adds a number of features that are unique to develop Android apps to the Gradle build system, which is the foundation of the Android Studio development...

2 minutes read.

Creating a Calendar View App in Android

This article demonstrates how to make an Android application that uses CalendarView to display the Calendar. It also provides the option to pick the current date and view the date....

3 minutes read.

Android Date picker example

How to pick date from the user in Android? Write an android example to pick date from the user and display it. Android provides control for the user to pick a date...

3 minutes read.

Content Providers of Android with Example

An essential part of Android that performs the function of a relational database by storing application data is called a content provider. The function of the content provider in the...

13 minutes read.

Dashboard UI Design in Android

One of the essential components that draw the user’s attentions into the application's operation is the dashboard design. It offers details on the application's general functionality in one location. Imagine...

11 minutes read.

How to crop Image from Camera and Gallery in Android?

In this tutorial, we'll learn how to crop photos in the Android Gallery and Camera. There is no crop feature in this project, contrary to what was covered in the...

5 minutes read.

Android Navigation Drawer

A sliding menu used to show important links in the Android Application is called Navigation Drawer. The navigation drawermakes it easier to navigate between the fragments. It is not displayed...

5 minutes read.

Broadcast Receiver in Android with Example

When a device wakes up, receives a message, receives an incoming call, switches to aeroplane mode, or initiates any other system-wide action, it is said to have been broadcast in...

5 minutes read.

Android Studio's Layout Editor

The Layout Editor allows you to efficiently create layouts by dragging UI elements from the Palette into the visual design editor instead of manually creating the layout XML file by...

8 minutes read.

Android Emulator

A tool for creating Android virtual devices (including software and virtual hardware) on your personal desktop is known as Emulator. We can use these virtual devices as the target device...

4 minutes read.

Android Tutorial

This Android tutorial will provide you with all the concepts that will be beneficial for both beginners and advanced-level students or candidates. You can learn this tutorial to begin your...

6 minutes read.

AdapterViewFlipper in Android with Example

The AdapterViewFlipper class, a subclass of the ViewAnimator class, is what we use to switch from two or multiple views when only one is present at a time. The AdapterViewFlipper...

10 minutes read.

Assets folder in Android

You might have noticed that unlike the Eclipse ADT (App Development Tools), the Android Studio does not have an Assets folder, which is mainly used to store the web resources...

3 minutes read.

Android Time picker example

How to pick Time from the user in android? Write an android example to pick Time from the user and display the date to the user. Android provides controls for the user...

3 minutes read.

Android ListView

A kind of AdapterView that displays a vertical list of scrollable views, each of which is laid out below each other is called ListView. Using adapters, items are inserted into...

4 minutes read.