QR code generating in Android

    QR code short Quick Response Code is a two-dimensional matrix type barcode. Designed by the automotive industry in Japan has gained popularity due to its large storage capacity and fast readability. It has become very common in the mobile industry where you scan a QR code to download an application. QR code is detected as a 2-dimensional digital image. There are plenty of apps that take an image of the QR code using the device camera and process them.
    In this topic, ZXing is the most popular library in both generating and reading the QR code. The weakness of this library only it's size: too big, many features and integrating process is much complicated, not suitable for the tiny/simple applications. So, in this post, I will present the way to generate a QR code from String input in Android by using an other external library (named QRCodeGenerator) which convenience and tiny are featured.

Importing library

    In order to use QRCodeGenerator, please add this dependency to your app/build.gradle:
compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0'

How to use it

    The important work here is generating a QR Code. Use this following code as inputValue is a String:
// Initializing the QR Encoder with your value to be encoded, type you required and Dimension
QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension);
try {
  // Getting QR-Code as Bitmap
  bitmap = qrgEncoder.encodeAsBitmap();
  // Setting Bitmap to ImageView
  qrImage.setImageBitmap(bitmap);
} catch (WriterException ex) {
  ex.printStackTrace();
}
    You will have a QR code image in Bitmap format!
    Beside that, this library supports well in storing QR code image as a JPG/PNG file with this simple code:
String savePath = Environment.getExternalStorageDirectory() + "/QRCode/";
save = QRGSaver.save(savePath, "WebSite QR code", bitmapResult, 
                                        QRGContents.ImageType.IMAGE_JPEG);

Full project code

    First, design a layout for our main activity, which allows user input an input text:
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"
    android:padding="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

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

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

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

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

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

</LinearLayout>
    And this is the activity Java code:
MainActivity.java
package info.devexchanges.qrcodegenerator;

import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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 {

    private static final String TAG = "MainActivity";
    private EditText editText;
    private ImageView imageView;
    private QRGEncoder qrgEncoder;
    private Bitmap bitmapResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.QR_Image);
        editText = (EditText) findViewById(R.id.edt_value);
        Button btnStart = (Button) findViewById(R.id.start);
        final Button btnSave = (Button) findViewById(R.id.save);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (editText.getText().toString().trim().length() > 0) {

                    //calculating bitmap dimension
                    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(editText.getText().toString().trim(), null, QRGContents.Type.TEXT, smallerDimension);
                    try {
                        bitmapResult = qrgEncoder.encodeAsBitmap();
                        imageView.setImageBitmap(bitmapResult);
                        btnSave.setVisibility(View.VISIBLE);
                    } catch (WriterException e) {
                        Log.v(TAG, e.toString());
                    }
                } else {
                    editText.setError("Enter some text");
                }
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean save;
                String result;
                try {
                    String savePath = Environment.getExternalStorageDirectory() + "/QRCode/";
                    save = QRGSaver.save(savePath, "WebSite QR code", bitmapResult, QRGContents.ImageType.IMAGE_JPEG);
                    result = save ? "Image Saved" : "Image Not Saved";
                    Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Running application

    Input some texts, and click "Generate QR Image", we'll have this result:
    Click at "Save QR image", your bitmap will be saved:
    Open "QRCode" folder in your SD Card, you will see this image:

Final thoughts

    That's all about generating QR code in Android. With some simple steps, now I have an own QR code for my website. Reading QR code or barcode is so simple with ZXing (I had a post about reading barcode HERE, so absolutely similarly, you can use this library to read the QR code).
    References to the library page on @Githubhttps://github.com/androidmads/QRGenerator

Share


Previous post
« Prev Post
Next post
Next Post »