Simplified Coding

  • About
  • Contact Us
  • Advertise
  • Privacy Policy
You are here: Home / Android Application Development / Android QR Code Scanner Tutorial using Zxing Library

Android QR Code Scanner Tutorial using Zxing Library

December 15, 2016 by Belal Khan 41 Comments

Hey guys in this tutorial we will learn creating Android QR Code Scanner. So if you need something like a Barcode or QR Code Scanner in your android application, then you are at the right place. So lets start creating our Android QR Code Scanner.

Contents

  • 1 What is a QR Code?
  • 2 Generating a QR Code
  • 3 Creating Android QR Code Scanner
    • 3.1 Creating a new Project
    • 3.2 Adding Zxing Library
    • 3.3 Creating User Interface
    • 3.4 Building Android QR Code Scanner
      • 3.4.1 Defining View Objects
      • 3.4.2 Attaching OnClickListener
      • 3.4.3 Android QR Code Scanner
    • 3.5 Sharing is Caring:
    • 3.6 Related

What is a QR Code?

You may already seen QR Code many times. Whatsapp web also uses QR Code for login. QR Code stands for Quick Response Code. QR Code is actually a 2 dimensional bar code. A QR Code consist of black squares over a white background, and it can store some data, which can be read by camera or other imaging devices. Below you can see a sample QR Code.

qr code

Sample QR Code

Generating a QR Code

To scan a QR Code the first thing needed is itself a QR Code.  So for this tutorial we will generate a Simple QR Code consisting of Name and Address.  Below is the QR Code I already generated a free service.

qr code

Sample QR Code

To generate your own QR Code you can go to this link. I have given JSON string as QR Data you can see in the below screenshot.

generating qr code

Creating Android QR Code Scanner

The following project will work for Barcode as well.

Creating a new Project

  • As always create a new Android Studio project.
  • I just created AndroidQRCodeScanner.
android qr code scanner

Android QR Code Scanner

Adding Zxing Library

  • For reading QR Code we will be using Zxing Library.
  • So once your project is loaded go to your app level build.gradle file and add the following dependency.

1
2
3
4
5
6
7
8
9
10
11
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    testCompile 'junit:junit:4.12'
 
    //add this dependency
    compile 'com.journeyapps:zxing-android-embedded:3.4.0'
}

  • Now sync your project with gradle.

Creating User Interface

  • We have two values (Name, Address) in the QR Code that we generated. So I designed the following layout that will display Name and Address. We also have a button in the layout that will open up camera for scanning the QR Code.
android qr code scanner

Android QR Code Scanner

  • For designing the above layout you can use the following xml code.

activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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="net.simplifiedcoding.androidqrcodescanner.MainActivity">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="vertical">
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Name" />
 
        <TextView
            android:id="@+id/textViewName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="xyz"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Address" />
 
        <TextView
            android:id="@+id/textViewAddress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="xyz"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
 
 
    </LinearLayout>
 
    <Button
        android:id="@+id/buttonScan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Scan QR Code" />
 
</RelativeLayout>

Building Android QR Code Scanner

Defining View Objects

  • Now come inside MainActivity.java and first define the view objects.

MainActivity.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class MainActivity extends AppCompatActivity {
 
    //View Objects
    private Button buttonScan;
    private TextView textViewName, textViewAddress;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //View objects
        buttonScan = (Button) findViewById(R.id.buttonScan);
        textViewName = (TextView) findViewById(R.id.textViewName);
        textViewAddress = (TextView) findViewById(R.id.textViewAddress);
    }
}

  • Now we will attach OnClickListener to button.

Attaching OnClickListener

  • Now we will attach OnClickListener to our button.

MainActivity.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//implementing onclicklistener
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    //View Objects
    private Button buttonScan;
    private TextView textViewName, textViewAddress;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //View objects
        buttonScan = (Button) findViewById(R.id.buttonScan);
        textViewName = (TextView) findViewById(R.id.textViewName);
        textViewAddress = (TextView) findViewById(R.id.textViewAddress);
        
        //attaching onclick listener
        buttonScan.setOnClickListener(this);
    }
 
    @Override
    public void onClick(View view) {
 
    }
}

Android QR Code Scanner

  • Now its time to scan the QR Code.
  • For scanning modify the code of MainActivity.java as below.

MainActivity.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package net.simplifiedcoding.androidqrcodescanner;
 
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;
import android.widget.Toast;
 
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
 
import org.json.JSONException;
import org.json.JSONObject;
 
//implementing onclicklistener
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    //View Objects
    private Button buttonScan;
    private TextView textViewName, textViewAddress;
 
    //qr code scanner object
    private IntentIntegrator qrScan;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //View objects
        buttonScan = (Button) findViewById(R.id.buttonScan);
        textViewName = (TextView) findViewById(R.id.textViewName);
        textViewAddress = (TextView) findViewById(R.id.textViewAddress);
 
        //intializing scan object
        qrScan = new IntentIntegrator(this);
 
        //attaching onclick listener
        buttonScan.setOnClickListener(this);
    }
 
    //Getting the scan results
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            //if qrcode has nothing in it
            if (result.getContents() == null) {
                Toast.makeText(this, "Result Not Found", Toast.LENGTH_LONG).show();
            } else {
                //if qr contains data
                try {
                    //converting the data to json
                    JSONObject obj = new JSONObject(result.getContents());
                    //setting values to textviews
                    textViewName.setText(obj.getString("name"));
                    textViewAddress.setText(obj.getString("address"));
                } catch (JSONException e) {
                    e.printStackTrace();
                    //if control comes here
                    //that means the encoded format not matches
                    //in this case you can display whatever data is available on the qrcode
                    //to a toast
                    Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
    @Override
    public void onClick(View view) {
        //initiating the qr code scan
        qrScan.initiateScan();
    }
}

  • Now you can try running your application.
android qr code scanner

Android QR Code Scanner

  • Bingo! Our Android QR Code Scanner is working absolutely fine.

So thats all for this Android QR Code Scanner Tutorial friends. Feel free to leave out your comments if having any confusions or queries. Thank You 🙂

Sharing is Caring:

  • Tweet
  • Share on Tumblr
  • More
  • Pocket
  • Print
  • Email

Related

Filed Under: Android Application Development, Android Intermediate Tagged With: android qr code scanner, qr code android

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, android etc.

Comments

  1. Manas Das says

    December 16, 2016 at 5:12 am

    Thank you so much.

    Reply
  2. Youcef says

    December 20, 2016 at 12:34 pm

    Thank you mate

    Reply
  3. Jerry says

    December 21, 2016 at 9:05 am

    Great tutorial! Can you kindly show me how to open the qr code within a fragment and with the camera not at full screen but only the middle part of the fragment is the camera

    Reply
  4. Rozer says

    December 23, 2016 at 9:20 am

    Very Nice 🙂
    Appreciated.

    Reply
  5. sivaiah says

    December 30, 2016 at 8:18 am

    sir please make the scanner view with square shape and delete the red horizontal line in between the scanner view.

    I need this requirement sir.please post it…

    Reply
    • Sandip says

      January 27, 2017 at 6:45 am

      https://github.com/journeyapps/zxing-android-embedded#usage-with-intentintegrator. Go to this link which is the Github page for used library. Read about use from Fragment and Customize options. I hope you will find your answer.

      Reply
  6. sivaiah says

    December 30, 2016 at 8:20 am

    Atlease post the code how to remove the red horizontal line on top of Scanner view.

    Reply
  7. amit pandya says

    February 21, 2017 at 6:28 am

    awesome man!!!
    you ROCK <3. its working fine. just i wanted to send this result data in an edittext instead of showing result in a toast.

    anyone!!! plz help me in this.

    Reply
  8. Areej says

    February 25, 2017 at 5:15 pm

    what if I wanted to retrieve data from SQL database, the QR code contains an ID number that is unique in the database and I want to retrieve that specific record by scanning the ID .. can you help me, please?

    Reply
    • aman says

      May 10, 2017 at 5:57 am

      Did u get any soln for ur query?
      I m stuck with same thing.
      If u have any idea pleaselet me know asap

      Reply
  9. Burhanudinr says

    March 19, 2017 at 3:08 am

    Thank you sir! Appreciated 😀

    From Bandung, West Java, Indonesia.

    Reply
  10. Amit Kumar says

    March 29, 2017 at 8:04 am

    Hi Sir,
    I am Getting Error
    Error:Execution failed for task ‘:app:transformClassesWithDexForDebug’.
    > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process ‘command ‘C:\Program Files\Java\jdk1.7.0_79\bin\java.exe” finished with non-zero exit value 1

    Reply
  11. Narendra Kumar says

    March 30, 2017 at 10:05 am

    Excellent..!!!! Working as a charm

    Reply
  12. Marcelo Casanovas says

    April 21, 2017 at 3:12 pm

    Thanks so much, but i have a trouble , the scan time its so slow, do you have any solutions?

    Reply
  13. Gulnaz Naseer says

    May 16, 2017 at 11:14 am

    i want to fetch textview scan result and match with my localhost data how i can do this kindly give me code i have no idea

    Reply
  14. raghu datta says

    June 20, 2017 at 9:09 pm

    Hi, Wonderful explanation.Can u write a post for multiple QR scanning.And get result to array??

    Reply
    • raghu datta says

      June 20, 2017 at 9:19 pm

      Please inbox me at [email protected]

      Reply
  15. patrick says

    June 23, 2017 at 1:54 pm

    Thank you so much. it works for me.

    Reply
  16. Snehal Shirsat says

    July 17, 2017 at 10:03 am

    Hi can you help me, to scan QR code using front camera?

    Reply
  17. Nilesh says

    July 19, 2017 at 6:18 am

    whai is name in object and direct go in catch block to scan

    Reply
  18. nikita says

    July 28, 2017 at 6:39 pm

    Awesome and helpful article

    Reply
  19. Fuad says

    September 6, 2017 at 2:48 am

    Thank you Belal, but it’s only work in landscape orientation is’n it?

    Reply
  20. Karthi says

    September 22, 2017 at 6:46 am

    How to change the orientation to potrait?

    Reply
    • Siva7170 says

      November 16, 2017 at 5:28 am

      just paste this code into your android manifest.

      Reply
  21. Emre ERBAKILI says

    November 4, 2017 at 10:05 am

    the camera and app turns off after detecting qr code. It started to happen after upgrading the android studio version. 🙁

    Reply
  22. gis says

    December 27, 2017 at 1:32 pm

    I am having an error on this part of the code:

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

    the ‘integration’ part. Can someone please help me? Pleeeaasseee T.T

    Reply
  23. kethu says

    January 4, 2018 at 1:16 am

    In mobile this sample is not working.Please help me.its not scaning QR code/bar code.

    Reply
  24. giri says

    January 22, 2018 at 5:02 am

    hi bro,
    How to change the orientation for the scanner

    Reply
  25. hari says

    February 5, 2018 at 5:33 am

    hi i am invoke the coding is working perfectly so next how to open flash light for barcoding scanner in adroid please help me its very urgent guyes

    Reply
  26. Gourav says

    February 20, 2018 at 6:11 pm

    How can i change the orientation to portrait mode?
    what code to paste?
    ScreenOrientation= “Portrait”
    is not working in manifest file

    Reply
    • Naveen says

      December 11, 2018 at 6:16 am

      How can I do this in Portrait Mode ?
      Have you got any idea scanning in Portrait mode ?
      Please help me on this.

      Reply
  27. MohammadAli says

    March 5, 2018 at 5:35 am

    this work good.

    but when i scan other QR then always print in TOAST so any other way to scan all QR and get data in TextView ?

    Reply
  28. AndroidFirstTimer says

    April 7, 2018 at 7:31 pm

    Hi…the code is running perfectly fine when on the main activity, I was wondering how will I be able to call this activity from another activity on button click. I have tried using Intent but it does not seem to work and the app crashes, do you know why this is happening and how to solve it?

    Reply
  29. jeph says

    May 28, 2018 at 10:51 am

    hello. i love your work. it works on me. thumbs up. i was wondering if the qr code scanning can fetch data from mysql . instead of displaying data, i want to scan the qr code and when it (QR CODE = QR CODE) something like this. it display all the data from mysql (SELECT * FROM data WHERE QRCODE = QRCODE – php file) when scanned. and it will display in listview . thanks. i hope you read this. and i hope you will help me. thank you very much. its for thesis thing. we are making an mobile pos system using qr code scanning. thank you very much

    Reply
  30. MA says

    July 18, 2018 at 10:08 am

    Hi guys, do you have a working apk file for this, kindly send me download link. Many Thanks.

    Reply
  31. pramodkumar says

    July 21, 2018 at 8:09 pm

    excellent explanation sir… thanks

    Reply
  32. John Philip de Torres says

    August 2, 2018 at 4:05 pm

    I try to edit the code given above. how to display the URL of website on the app using qr code scanner?

    Reply
  33. Jasen says

    August 13, 2018 at 5:45 pm

    Can you give direction on how to take the data we get from scanning, and save it to a mysql database?

    Reply
  34. Rakesh Jha says

    September 29, 2018 at 1:52 pm

    what if I wanted to retrieve data from SQL database, the QR code contains an ID number that is unique in the database and I want to retrieve that specific record by scanning the ID .. can you help me, please?

    Reply
  35. Rajani says

    October 7, 2018 at 5:04 am

    please help me as soon as possible …..

    Reply
  36. Mohammed says

    December 9, 2018 at 10:39 am

    It is working for Bar Code but not for QR Code..

    Reply

Leave a Reply to John Philip de Torres Cancel reply

Your email address will not be published. Required fields are marked *

Search




Download our Android App

Simplified Coding in Google Play

About Me

Belal Khan

Hello I am Belal Khan, founder and owner of Simplified Coding. I am currently pursuing MCA from St. Xavier's College, Ranchi. I love to share my knowledge over Internet.

Connect With Me

Follow @codesimplified
Simplified Coding

Popular Tutorials

  • Android JSON Parsing – Retrieve From MySQL Database
  • Android Login and Registration Tutorial with PHP MySQL
  • Android Volley Tutorial – Fetching JSON Data from URL
  • Android Upload Image to Server using Volley Tutorial
  • Android TabLayout Example using ViewPager and Fragments
  • Retrieve Data From MySQL Database in Android using Volley
  • Firebase Cloud Messaging Tutorial for Android
  • Android Volley Tutorial – User Registration and Login
  • Android Upload Image to Server Using PHP MySQL
  • Android Navigation Drawer Example using Fragments




About Simplified Coding

Simplified Coding is a blog for all the students learning programming. We are providing various tutorials related to programming and application development. You can get various nice and simplified tutorials related to programming, app development, graphics designing and animation. We are trying to make these things simplified and entertaining. We are writing text tutorial and creating video and visual tutorials as well. You can check about the admin of the blog here and check out our sitemap

Quick Links

  • Advertise Here
  • Privacy Policy
  • Disclaimer
  • About
  • Contact Us
  • Write for Us

Categories

Android Advance Android Application Development Android Beginners Android Intermediate Ionic Framework Tutorial JavaScript Kotlin Android Others PHP Advance PHP Tutorial React Native

Copyright © 2017 · Simplified Coding· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.