How to Implement QR Code Scanner in Android

Welcome to the First Tutorial on AndroidCavalry. Today, we are going to learn how we can implement QR Code scanner in our own Android app.

We’ll use Zxing library to handle scanning and decoding the QR Code.

Let’s start implementing the QR Code scanner:

1. Create  a New Project

Create a new project by going through File > New > New Project option. Now when prompted, the default activity, select Empty Activity and proceed.

2. Download Zxing Library

Now Download the Zxing library and extract it on your computer.

3. Add Modules in Android Project

Goto File > New > Import Module option and navigate to the folder where you extracted Zxing Library. Select Android folder and proceed.

Android Studio will automatically convert this module to Gradle based module and generate a build.gradle file.

4. Updating build.gradle of Zxing module

  • Update the gradle plugin from apply plugin: ''  to apply plugin: ''
  •  Add below lines to add required dependencies to the Zxing module.
    compile ''
    compile ''
    compile ''

Now sync Gradle.

5. Changing AndroidManifest.xml of Zxing module

Open AndroidManifest.xml file in the module added from Zxing library and remove the following lines from the CaptureActivity tag.

       <action android:name="android.intent.action.MAIN" />

       <category android:name="android.intent.category.LAUNCHER" />

6. Change switch case to if-else

You may get errors while compiling the Zxing library, that “constant expression required” at every switch case used in the library. The basic reason for this is that the resource constants in file of library, are not final.

To overcome this error, change the switch case to if-else-if ladder. For more info, please read this

7. Let’s call the CaptureActivity

  1. Create  a button in the Activity, open activity_main.xml from layouts folder and add following lines:
            android:text="click me"
  2. Let’s handle the button click event in class:
    Button btnClick = (Button) findViewById(;
           btnClick.setOnClickListener(new View.OnClickListener() {
               public void onClick(View v) {
                   Intent intent = new Intent(MainActivity.this, CaptureActivity.class);

    This will call CaptureActivity from the Zxing library to scan and decode the QR Code. The request code sent here is IntentIntegrator.REQUEST_CODE, which results in CaptureActivity to return the result of decoding.

  3. Let’s fetch the result returned by CaptureActivity:
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            IntentResult result= IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
                String rs=result.getContents();

    Here we use, parseActivityResult method of class IntentIntegrator to parse the result returned by CaptureActivity.

7. Executing the Application 

Go ahead and run the application to scan the QR Code successfully.