How to generate QR Code in Android



How to generate QR Code in Android.
Quick Response Code (QR Code) is a 2-Dimensional matrix type barcode used to store data.
It is more popular because of its storage capacity and fast readability.

Zxing & QR Generator Library

Zebra Crossing (Zxing) is an awesome library used to generate and read QR codes in mobile apps.
But it is bigger in size. So, we have to go for another one, QR Generator which is a tiny, open source library.

Creating a New Project with Android Studio
  1. Open Android Studio and Select "Create New Project".
  2. Name the project as per your wish and select your activity template.
  3. Click finish button to create a new project in Android Studio.



Setting up the library and manifest
1.Open App level gradle file and import the library.

implementation 'androidmads.library.qrgenearator:QRGenearator:1.0.3'
2.The, click “Sync Now”.
3.Then, open your Manifest file and add the following permissions. It is used to save QR Code to file storage.

QR Code Full Code

 activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Name" />


    <EditText
        android:id="@+id/phone_no"
        android:layout_marginTop="5dp"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:hint="Enter Phone No"
        ></EditText>

    <EditText
        android:id="@+id/email"
        android:layout_marginTop="5dp"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:hint="Enter Email"
        ></EditText>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <Button
            android:layout_weight="1"
            android:id="@+id/start"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Generate" />

        <Button
            android:layout_weight="1"
            android:id="@+id/save"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Save" />
    </LinearLayout>

    <ImageView
        android:id="@+id/QR_Image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/app_name" />

</LinearLayout>

MainActivity.java

package com.codewithandroid;

import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Environment;
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 com.google.zxing.WriterException;
import androidmads.library.qrgenearator.QRGContents;
import androidmads.library.qrgenearator.QRGEncoder;
import androidmads.library.qrgenearator.QRGSaver;

public class MainActivity extends AppCompatActivity {

    String TAG = "GenerateQRCode";
    EditText name,email,phoneno;
    ImageView qrImage;
    Button start, save;
    String inputValue;
    String savePath = Environment.getExternalStorageDirectory().getPath() + "/QRCode/";
    Bitmap bitmap;
    QRGEncoder qrgEncoder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        qrImage =  findViewById(R.id.QR_Image);
        name =  findViewById(R.id.name);
        phoneno = findViewById(R.id.phone_no);
        start =  findViewById(R.id.start);
        save =  findViewById(R.id.save);
        email = findViewById(R.id.email);


        //Todo Generate QR Code Start

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputValue = " \n" + name.getText().toString().trim() + " \n" + phoneno.getText().toString().trim() + " \n" + email.getText().toString().trim();
                Log.d(TAG,inputValue);



                if (inputValue.length() > 0) {
                    WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
                    Display display = manager.getDefaultDisplay();
                    Point point = new Point();
                    display.getSize(point);
                    int width = point.x;
                    int height = point.y;
                    int smallerDimension = width < height ? width : height;
                    smallerDimension = smallerDimension * 3 / 4;

                    qrgEncoder = new QRGEncoder(
                            inputValue, null,
                            QRGContents.Type.TEXT,
                            smallerDimension);
                    try {
                        bitmap = qrgEncoder.encodeAsBitmap();
                        qrImage.setImageBitmap(bitmap);
                    } catch (WriterException e) {
                        Log.v(TAG, e.toString());
                    }
                } else {
                    name.setError("Required");
                    phoneno.setError("Required");
                    email.setError("Required");
                }
            }
        });

        //Todo Generate QR Code End


        //Todo Save QR Code Button Start

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean save;
                String result;
                try {
                    save = QRGSaver.save(savePath, name.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
                    result = save ? "Image Saved" : "Image Not Saved";
                    Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        //Todo Save QR Code Button End


    }
}


Post a Comment

0 Comments