Android QR code and Barcode Scanner Tutorial

Before we start tutorial on how to build barcode scanner (or barcode reader) application in Android, let’s check out what actually barcode scanner is. A barcode scanner (or reader) is an electronic device which is used to capture
and read the information contained in barcodes available on the products and display information about the product.

Nowadays Barcodes and QR Codes are widely used in a lot of mobile apps. In a QR Code, you can store information like Text, SMS, Email, URL, Image, Audio and few other formats. In Android, you can extract the information stored in barcodes and QR code by using Zxing Library.

In this article, will are going to learn how to create a barcode scanner/reader which is able to read barcodes and QR codes available on the products using an android application by using the Zxing library.

Barcode Scanner

Creating Barcode Scanner Android Project:

Refer Android beginners app development guide if you are a beginner or if you don’t know how to create a project in the android studio.

1. Create a new project in Android Studio from File ⇒ New Project and fill the project details.

2. Open build.gradle (app/build.gradle) and set the minSdkVersion and targetSdkVersion, and also don’t forget to include and implement the following line under the dependencies in your app gradle.

implementation 'com.journeyapps:zxing-android-embedded:[email protected]'
implementation 'com.google.zxing:core:3.2.1'
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.gadgetcreek.barcode"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.journeyapps:zxing-android-embedded:[email protected]'
    implementation 'com.google.zxing:core:3.2.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

3. Open the layout file for main activity(activity_main.xml) located under src/main/res/layout/activity_main.xml and add the below layout code.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.gadgetcreek.barcode.MainActivity">

    <TextView
        android:id="@+id/contents"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Camera icon to Scan BarCode"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Web Search"
        android:onClick="search"
        app:layout_constraintBottom_toBottomOf="parent"/>

</android.support.constraint.ConstraintLayout>

4. Implementing option menu with a camera icon, so to create a menu, you need a menu folder, create one inside the “res” folder by selecting it and choosing “File->New->Android resource directory” and entering “menu” as the name. Then defined an XML file inside the new menu folder with file name main.xml and add the following below item under that XML file.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_camera"
        android:orderInCategory="100"
        app:showAsAction="always"
        android:icon="@android:drawable/ic_menu_camera"
        tools:ignore="MenuTitle" />
</menu>

5. Now let’s define the Main Activity where the Android QR/Barcode Scanner takes place. In this tutorial, we are going to scan the QR/Barcode by clicking the camera icon from the menu and after scanning the barcode, app will display or set the result to TextView or you can create Toast message. After getting the result from reading QR/Barcode we are also going to search that result on the web.

so open the MainActivity.java file located under src/main/Java/MainActivity.java and add below code.

package com.gadgetcreek.barcode;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class MainActivity extends AppCompatActivity {

    TextView tv;
    Button bt;
    String contents="", format="";

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

        tv = (TextView)findViewById(R.id.contents);
        bt = (Button)findViewById(R.id.search);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent in) {

        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, in);

        if (scanningResult != null) {
            try {
                contents = in.getStringExtra("SCAN_RESULT");
                format = in.getStringExtra("SCAN_RESULT_FORMAT");
                tv.setText("Content-" + contents + "\n" + " Format-" + format);
            }
            catch (NullPointerException e){}
        }
    }
    
    public void search(View v){
        if(contents.equals("")){
            Toast.makeText(getApplication(),"Click Camera icon to Scan BarCode",Toast.LENGTH_LONG).show();
        }
        else{
            //search scan result on web
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(contents)));
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);//Menu Resource, Menu
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_camera:
                IntentIntegrator scanIntegrator = new IntentIntegrator(MainActivity.this);
                scanIntegrator.initiateScan();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

6. Note that you need to add the following permission and meta-data under your application tag in AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gadgetcreek.barcode">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data
            android:name="com.google.android.gms.vision.DEPENDENCIES"
            android:value="barcode" />
    </application>

</manifest>

7. Run the app and try to scan the below QR codes or Barcode Scanner. You should able to see the proper information as shown in the demo.

One thought on “Android QR code and Barcode Scanner Tutorial

  1. I am really impress with your blog so 3 words for your website, unique information, good selection of topic and quality.

Leave a Reply