Generate QR Code using Java (Android)

ZXing Android Embedded library

  1. Add zxing-android-embedded dependency in the module's build.gradle file:

app/build.gradle

dependencies {
    implementation 'com.journeyapps:zxing-android-embedded:4.3.0'
}
  1. Add ImageView element in the layout XML file:

app/src/main/res/layout/activity_main.xml

<?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">

    <ImageView
        android:id="@+id/myImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:contentDescription="QR Code" />

</RelativeLayout>
  1. Generate QR code:

app/src/main/java/com/example/app/MainActivity.java

package com.example.app;

import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import com.google.zxing.BarcodeFormat;
import com.journeyapps.barcodescanner.BarcodeEncoder;

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String text = "Hello";

        try {
            BarcodeEncoder encoder = new BarcodeEncoder();
            Bitmap bitmap = encoder.encodeBitmap(text, BarcodeFormat.QR_CODE, 400, 400);

            ImageView imageView = findViewById(R.id.myImageView);
            imageView.setImageBitmap(bitmap);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.