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 reduce the size of APK in Android

What exactly is an APK file? The full form of APK is Android Package Kit. It is the Android operating system's application file format. We use Android Studio to generate APK...

7 minutes read.

Button Widget in Android Tutorial

Explanation: Button is a widget under Buttons section which is used to execute specific code. Example: XML file: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" tools:context=".MainActivity">     <Button         android:id="@+id/button"         android:layout_width="wrap_content"    ...

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

How to show image on an android application

ImageView Widget in Android What you should already KNOW? You should be familiar with: 1) Creating, building, and running apps in Android Studio 2) Basics of android widgets   Explanation: Image View widget is used...

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

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.

Android GridView

Theview group that displays items in a two-dimensional scrolling grid is called GridView. The data isadded into this grid layout from anArray List or database. The adapter class isutilized to...

4 minutes read.

Android TextView

Widgets are user interface (UI) elements that help users to interact with Android applications. It is one of many equipments that can be used to improvise the user interface of...

4 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 Activity

What is an Activity? Android Activity is a screen in the user interface of an Android application. In this way, Android activity is very similar to the desktop application window. An...

4 minutes read.

Android 9.0 Pie vs. Android 10, which one is better

Android smartphone users are always searching for new system upgrades and keep an eye on system updates whenever the next version is published. Android 9 Pie and Android Q 10 are...

5 minutes read.

Top 7 Android App Development Books

Do you want to create Android apps but don't know where to start? One should first be familiar with the basics of Android before we discuss these books. With the...

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

Top Programming Languages for Android Development

For mobile apps, there are so many programming languages. You would need to spend days simply researching if you had to pick one from a list of 30 coding languages...

8 minutes 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.

Different Ways to Create aar File in Android Studio

A file called an Android archive file (*.aar) can be created using Android Studio and comprises classes and methods that use related files and classes for Android. The Android library...

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

Android Styles and Themes

Android styles allow you to design the appearance (for example, colors, size, and fonts) of Android UI components from XML resource files. With this method, you only need to set...

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

Android RecyclerView

RecyclerView is a ViewGroup brought to AndroidStudio as successor to ListView and GridView. These are all improvements and are included in the latest v7 support package. It was written to...

8 minutes read.