Scan Barcode And QRcode Programmatically In Android Studio

scan barcode and qrcode programmatically in android

In scan barcode and QRcode programmatically in android tutorial, we will implement scan functionality in our android app programmatically.

Scan feature is needed in the app regarding grocery stores and inventory android apps.

This article covers two different example relating to android barcode scanner.

Every barcode contains unique format which represents the product id. Using this app, you will be able to find out that id from the barcode by scanning it.

Scanning barcode programmatically with android device is always a topic of discussion among android developers.

There are certain ways using which you can accomplish your goal.

  • Write your own algorithm to scan the image based barcodes.
  • Using google’s mobile vision API.
  • Web based Solution, where you upload the barcode on the server, Web API scan it and returns the results in the text format.
  • Use third party library which will use android devices camera to scan the barcode

We will use fourth option in this tutorial. Using google’s api and third party library are almost same. You need to import classes and use them in your app.

1. Android Scan Barcode Programmatically

In the end, our Android app will be able to scan both Barcode as well as QRCode.

Check out what will be final result in the following video output.

Step 1: Create a new project in Android Studio.

When you are making new activity, select empty activity as a default activity.

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

Add following code into dependencies{} 

compile 'me.dm7.barcodescanner:zbar:1.8.4'

Here we are using ZBar, but you can also use ZXing.

Github link for ZBar or ZXing library : ZXing or ZBar

This line will integrate required classes from the github.

Step 3: Updating AndroidManifest.xml file

add camera permission between <manifest>….</manifest> tag.

<uses-permission android:name="android.permission.CAMERA" />

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

For using camera, we have to get permission from the user.

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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    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.scanbarcodeqrdemonuts.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.

When the user will click the button, camera preview will be opened and you can scan barcode or QRCode from here.

After successful scanning, system will enter the value of the barcode in the textview.

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;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvresult = (TextView) findViewById(R.id.tvresult);
        Button 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 click.

Step 6: Opening new activity in android studio

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

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

You can use below image for more reference.

scan barcode qrcode android
open 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 android.widget.Toast;
import me.dm7.barcodescanner.zbar.ZBarScannerView;
public class ScanActivity extends AppCompatActivity implements ZBarScannerView.ResultHandler {
    private ZBarScannerView mScannerView;
    //camera permission is needed.
    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        mScannerView = new ZBarScannerView(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(me.dm7.barcodescanner.zbar.Result result) {
        // Do something with the result here
        Log.v("kkkk", result.getContents()); // Prints scan results
        Log.v("uuuu", result.getBarcodeFormat().getName()); // Prints the scan format (qrcode, pdf417 etc.)
        MainActivity.tvresult.setText(result.getContents());
        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 layout file.

Step 8: Brief Description of ScanActivity.java

In onCreate() method, we have set 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(me.dm7.barcodescanner.zbar.Result result) {
        // Do something with the result here
        Log.v("kkkk", result.getContents()); // Prints scan results
        Log.v("uuuu", result.getBarcodeFormat().getName()); // Prints the scan format (qrcode, pdf417 etc.)
        MainActivity.tvresult.setText(result.getContents());
        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.getContents() method. This method returns the value of barcode in text format.

we have set this barcode text into TextView of MainActivity.

onBackPressed() method will return the user to the Main Activity.

So it was all about scan barcode and QRcode programmatically in android studio example. Thank you šŸ™‚





2. Scan QRCode With ZXing in Android

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.

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

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  

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.

Step 3: Updating AndroidManifest.xml file

 add camera permission between <manifest>ā€¦.</manifest> tag.

 <uses-permission android:name="android.permission.CAMERA" />

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.

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.