Open In App

How to Generate Barcode in Android?

Last Updated : 26 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Barcodes are the graphical representation of data that enables effortless scanning. When we aim to incorporate this functionality for various purposes in Android applications it becomes crucial to understand the underlying principles and techniques involved in generating barcodes effectively. In this article, we are going to implement that. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2:

Add Dependencies in build.gradle file from that we’ll generate the Bar code make sure you sync your gradle file

dependencies {
//....Other Dependencies
implementation "com.google.zxing:core:3.2.1"
}

Step 3:

Now open your activity where we’ll create a UI, we have created a simple UI. For demonstration purposes you can create your own UI, we have added one EditText for user input, and one ImageView, so that the image barcode will be shown in that ImageView and added one Button.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".MainActivity7">
  
    <EditText
        android:id="@+id/et1"
        android:layout_width="239dp"
        android:layout_height="57dp"
        android:layout_marginTop="184dp"
        android:hint="Enter Text"
        android:textColorHint="@color/black"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
  
    <ImageView
        android:id="@+id/img1"
        android:layout_width="292dp"
        android:layout_height="214dp"
        tools:layout_editor_absoluteX="76dp"
        tools:layout_editor_absoluteY="285dp"
        app:layout_constraintTop_toBottomOf="@id/et1"
        android:layout_marginTop="25dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>
  
    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/img1"
        android:layout_marginTop="25dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:text="Generate Barcode"
        />
  
</androidx.constraintlayout.widget.ConstraintLayout>


UI Output:
xml_activity

Step 4:

Working on Kotlin File, it generates a barcode from user input. It uses MultiFormatWriter to encode the input creates a bitmap representation and displays it in an ImageView.

Kotlin




package com.ayush.gfgapp
  
import android.graphics.Bitmap
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
  
class MainActivity7 : AppCompatActivity() {
    
    private lateinit var et:EditText
    private lateinit var bt:Button
    private lateinit var img:ImageView
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main7)
  
        // Initialize UI components 
          // from your XML File
        et = findViewById(R.id.et1)
        bt = findViewById(R.id.btn1)
        img = findViewById(R.id.img1)
  
       
        bt.setOnClickListener {
            genBarcode()
        }
    }
  
    private fun genBarcode() {
        // Geting input value from the EditText
        val inputValue = et.text.toString().trim()
  
        if (inputValue.isNotEmpty()) {
            // Initializing a MultiFormatWriter to encode the input value
            val mwriter = MultiFormatWriter()
  
            try {
                // Generating a barcode matrix
                val matrix = mwriter.encode(inputValue, BarcodeFormat.CODE_128, img.width, img.height)
  
                // Creating a bitmap to represent the barcode
                val bitmap = Bitmap.createBitmap(img.width, img.height, Bitmap.Config.RGB_565)
  
                // Iterating through the matrix and set pixels in the bitmap
                for (i in 0 until img.width) {
                    for (j in 0 until img.height) {
                        bitmap.setPixel(i, j, if (matrix[i, j]) Color.BLACK else Color.WHITE)
                    }
                }
  
                // Seting the bitmap as the image resource of the ImageView
                img.setImageBitmap(bitmap)
            } catch (e: Exception) {
                  
                Toast.makeText(this, "Exception $e", Toast.LENGTH_SHORT).show()
            }
        } else {
            // Showing an error message if the EditText is empty
            et.error = "Please enter a value"
        }
    }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads