Scan Barcode And QRcode Using ZXing Android Studio Programmatically

scan barcode and qrcode using zxing android kotlin

Hello, developers. In scan barcode and QRcode using zxing Android example, we will learn how to scan the barcode and read QRcode using a zxing library in Android studio.

Barcode or QRCode contains an unique id which is associated with any particular product.

This scanning feature will read that unique id from barcode logo on product box or from the computer screen.

You can develop barcode scanning feature using below methods

  • Using a web API. Means that you upload the barcode to server first where web based API will scan it and after that it will return the result to the android device.
  • You develop or write your own image scanning algorithm which is really complex.
  • You can use google’s mobile vision API.
  • Using Github third party library and integrate it in your android studio project.

In this tutorial example, I am going to use last option: Github third party library.

We will use the camera of the android device to scan the barcode.

App For DemoNuts

Now access useful tutorials on this app : https://play.google.com/store/apps/details?id=com.main.demonuts

First of all check output of this scan barcode and QRcode using zxing android tutorial then we will implement it programmatically.

Creating scan barcode and qrcode using zxing android Example

Visit Birthday App

Use following app which allows you to wish a happy birthday with name and photo on birthday cake to your friend.

Visit app here : https://play.google.com/store/apps/details?id=com.snetchalabs.name_photo_on_birthday_cake

Step 1: Create a new project in Android Studio.

Step 2: Updating build.gradle(Module:app) file

add following code into dependencies{} 

 compile 'me.dm7.barcodescanner:zxing:1.9'

Here we are using ZXing library. You can also use ZBar library.

Follow this tutorial for ZBar: Scan Barcode QRcode Android

Github link for ZBar or ZXing library: ZXing or ZBar

Step 3: Updating AndroidManifest.xml file

 add camera permission between <manifest>….</manifest> tag.
 <uses-permission android:name="android.permission.CAMERA" />

Note: If you are targeting SDK version above 22 (Above Lollipop)  then you need to ask a user for granting runtime permissions. Check marshmallow runtime permission for more information.

Step 4: Updating activity_main.xml file:

Copy following code into android_main.xml file:

<?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="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.exampledemo.parsaniahardik.scanzxingdemonuts.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Scan Barcode or QR code" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tvresult"
        android:textColor="#000"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Result will be here"/>
</LinearLayout>

I have taken one button and one textview in the main layout file.

When the user clicks on the button, system will open a Scan activity.

Unique id from the barcode will appear in the textview after successful scanning.

Step 5: Updating MainActivity.java file:

Update MainActivity.java as per below code:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    public static TextView tvresult;
    private  Button btn;

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

        tvresult = (TextView) findViewById(R.id.tvresult);

        btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ScanActivity.class);
                startActivity(intent);
            }
        });

    }
}

Here we will open ScanActivity on the button’s click.

We will set up the logic for the scanning task in ScanActivity.

Step 6: Opening new activity in android studio

To open new activity in the android studio, click on File tab which is present at the left top bar.

Now go to File->New->Activity->Empty Activity and place name of activity as ScanActivity.

zxing scan barcode qrcode scanner android
new activity

Step 7: Updating ScanActivity.java file:

Add below code to ScanActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.zxing.Result;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{

    private ZXingScannerView mScannerView;

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        mScannerView = new ZXingScannerView(this);   // Programmatically initialize the scanner view
        setContentView(mScannerView);                // Set the scanner view as the content view
    }

    @Override
    public void onResume() {
        super.onResume();
        mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
        mScannerView.startCamera();          // Start camera on resume
    }

    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();           // Stop camera on pause
    }

    @Override
    public void handleResult(Result rawResult) {
        // Do something with the result here
       // Log.v("tag", rawResult.getText()); // Prints scan results
       // Log.v("tag", rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)

        MainActivity.tvresult.setText(rawResult.getText());
        onBackPressed();

        // If you would like to resume scanning, call this method below:
        //mScannerView.resumeCameraPreview(this);
    }
}

Note: We do not need to update activity_scan.xml file because we will open camera preview here so no need to do anything in the layout file.

Step 8: Brief Description of ScanActivity.java

  • In onCreate() method, we have set the view as scannerview instead of xml file layout.
  • In onResume() method, we have set the resulthandler and started camera preview.
  • In onPause() method, we are stopping camera preview.

Step 9: Explaining handleResult() method

@Override
    public void handleResult(Result rawResult) {
        // Do something with the result here
       // Log.v("tag", rawResult.getText()); // Prints scan results
       // Log.v("tag", rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)

        MainActivity.tvresult.setText(rawResult.getText());
        onBackPressed();

        // If you would like to resume scanning, call this method below:
        //mScannerView.resumeCameraPreview(this);
    }
  • As you can see in above code, we get result object which contains resulting Barcode or QRcode after scanning is completed.
  • We will get the final result by running result.getText() method and we have set it into TextView of MainActivity.

Kotlin Version

Kotlin version of this tutorial : Android Kotlin Scan Barcode QRCode ZXing

We will use same library but will integrate it with kotlin.

So it was all about scan barcode and qrcode using zxing android example programmatically.

Use comment section if you find any difficulty while developing this example. You can also share your reviews in the comment section.

Thank you.

Download Source Code

[sociallocker]Download Demo Code Tutorial[/sociallocker]