Sunday, December 29, 2024
Google search engine
HomeLanguagesJavaHow to Generate QR Code in Android?

How to Generate QR Code in Android?

QR codes are used in many apps for displaying data in machine-readable form. These codes are used to represent data in a secured manner that is readable only by machines and not by humans. We have seen many apps that provide QR codes that and we can scan that QR codes with our mobile device. In this article, we will take a look at how we can generate a QR Code for our app. So for implementing this feature we will be using a library from GitHub.

Implementation of QR Code Generator in Android

We will be creating a simple QR Code generator app in which we will be adding data from the app and generate a QR Code that will display the data inside it. Below is the sample GIF in which you will get a basic idea of what we are going to do in this article. Not that we are using Java language for building this project.

Generate QR Code in Android Sample GIF

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java 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.qrgenearator:QRGenearator:1.0.3’

Now sync the project from the top right corner option of Sync now. 

Step 3: Modify the strings.xml file

Below is the code for the strings.xml file.

XML




<resources>
    <string name="app_name">GFG App</string>
    <string name="qr_code">qr_code</string>
    <string name="enter_your_info">Enter your info</string>
    <string name="generate_qr_code">Generate QR Code</string>
</resources>


Step 4: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!--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="@string/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="@string/enter_your_info"
        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="@string/generate_qr_code" />
  
</RelativeLayout>


Step 5: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




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 imageview, edittext,
    // button, bitmap and qrencoder.
    private ImageView qrCodeIV;
    private EditText dataEdt;
    private Button generateQrBtn;
    Bitmap bitmap;
    QRGEncoder qrgEncoder;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing all variables.
        qrCodeIV = findViewById(R.id.idIVQrcode);
        dataEdt = findViewById(R.id.idEdt);
        generateQrBtn = findViewById(R.id.idBtnGenerateQR);
  
        // initializing onclick listener for button.
        generateQrBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(dataEdt.getText().toString())) {
                      
                    // if the edittext inputs are empty then execute 
                    // this method showing a toast message.
                    Toast.makeText(MainActivity.this, "Enter some text to generate QR Code", Toast.LENGTH_SHORT).show();
                } else {
                    // below line is for getting 
                    // the windowmanager service.
                    WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
                      
                    // initializing a variable for default display.
                    Display display = manager.getDefaultDisplay();
                      
                    // creating a variable for point which 
                    // is to be displayed in QR Code.
                    Point point = new Point();
                    display.getSize(point);
                      
                    // getting width and 
                    // height of a point
                    int width = point.x;
                    int height = point.y;
                      
                    // generating dimension from width and height.
                    int dimen = width < height ? width : height;
                    dimen = dimen * 3 / 4;
                      
                    // setting this dimensions inside our qr code
                    // encoder to generate our qr code.
                    qrgEncoder = new QRGEncoder(dataEdt.getText().toString(), null, QRGContents.Type.TEXT, dimen);
                    try {
                        // getting our qrcode in the form of bitmap.
                        bitmap = qrgEncoder.encodeAsBitmap();
                        // the bitmap is set inside our image 
                        // view using .setimagebitmap method.
                        qrCodeIV.setImageBitmap(bitmap);
                    } catch (WriterException e) {
                        // this method is called for 
                        // exception handling.
                        Log.e("Tag", e.toString());
                    }
                }
            }
        });
    }
}


Output: 

Note: You may also refer to How to Read QR Code in Android?

Check out the project: https://github.com/ChaitanyaMunje/QRCodeGenerator

RELATED ARTICLES

Most Popular

Recent Comments