Android QR Code Scanner using ZXingScanner Library Tutorial

Udemy Generic 728x90

Objective

In this tutorial we learn how to implement QR Code Scanner using ZXingScanner library in Android Application.

 

 

  • Quick Response(QR) code is a two dimensional barcode(matrix codes) that allows content to be decoded at a high speed. QR Code system was invented in 1994 by japanese company Denso-Wave.
  • The use of QR code is license-free. numetriclabz qr code
  • A QR code consists of black modules (square dots) arranged in a square grid on a white background, which can be read by an imaging device (such as a camera, scanner, etc.). The smallest QR codes are 21×21 pixels, and the largest are 177×177. The sizes are called versions. The 21×21 pixel size is version 1, 25×25 is version 2, and so on. The 177×177 size is version 40.
  • QR codes storing addresses and URLs may appear in magazines, on signs, on buses, on business cards, or on almost any object about which users might want information.
  • QR Scanner is mechanism to decode the QR Code. An app having QR scanner uses the camera of your device to scan the code. Scanner scans the image of QR Code taken by the camera and decodes the information provided with the code.

This tutorial explains, how to implement QR Scanner using ZXing Library. We will implement the process of scanning the image of the QR Code on the click of Button. So, we will add a Button widget in the activity_main.xml file. We will implement the ZXingScannerView.ResultHandler class to handle the scanned result in the MainActivity.java file and will initialize the ZXingScannerView in MainActivity.java file. It will start your camera and scan the image of QR Code to decode the QR code. After complete scanning of QR Code, result is handled by handleResult() method.
 

Step 2

Creating project

Create a new Project in Android Studio, goto File ⇒ New ⇒ New Projects.
 

Step 3

Adding Library in the dependencies

To compile the ZXing library, we need to add the library in the app’s dependencies. Open the app’s build.gradle file. Add the library in the dependencies. It will compile the library at run time.

<br />
dependencies {<br />
     compile 'me.dm7.barcodescanner:zxing:1.8.4'<br />
}<br />

 

Step 4

Creating Layout

Since, we will implement the process of image scanning on the click of a Button, therefore we need a Button in our app. To add the Button widget in activity_main.xml file, use the following code snippet.

<br />
 &lt;Button android:layout_height=&quot;wrap_content&quot;<br />
        android:layout_width=&quot;match_parent&quot;<br />
        android:text=&quot;QRScanner&quot;<br />
        android:onClick=&quot;QrScanner&quot; /&gt;<br />

1

Step 4

Implement Result Handler

To get the scanned result of QR Code, we will implement the ZXingScannerView.ResultHandler class. This class will handle the result by using the handleResult() method. So, we need to add this method in the MainActivity.java file. The handleResult() gets the result and displays it in the dialog box.

<br />
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {<br />
    private ZXingScannerView mScannerView;</p>
<p>    @Override<br />
    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);</p>
<p>    }</p>
<p>    @Override<br />
    public void handleResult(Result rawResult) {<br />
        // Do something with the result here</p>
<p>        Log.e(&quot;handler&quot;, rawResult.getText()); // Prints scan results<br />
        Log.e(&quot;handler&quot;, rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode)</p>
<p>        // show the scanner result into dialog box.<br />
        AlertDialog.Builder builder = new AlertDialog.Builder(this);<br />
        builder.setTitle(&quot;Scan Result&quot;);<br />
        builder.setMessage(rawResult.getText());<br />
        AlertDialog alert1 = builder.create();<br />
        alert1.show();</p>
<p>        // If you would like to resume scanning, call this method below:<br />
       // mScannerView.resumeCameraPreview(this);<br />
    }<br />
}<br />

 

Step 4

Creating a method to perform onClick() method

We need a method, which will be executed on button’s click. In this method, we will open the camera as a scanner and decode the image of QR Code. We need to initialize the ZXingScannerView method and pass it in setContentView() method. ZXingScannerView class starts your camera, captures the image, scans it and decodes the QR code. Do not forgot to stop the camera onPause() method.

<br />
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {<br />
    private ZXingScannerView mScannerView;</p>
<p>    @Override<br />
    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);<br />
    }</p>
<p>    public void QrScanner(View view){</p>
<p>        mScannerView = new ZXingScannerView(this);   // Programmatically initialize the scanner view<br />
        setContentView(mScannerView);<br />
        mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.<br />
        mScannerView.startCamera();         // Start camera<br />
    }</p>
<p>    @Override<br />
    public void onPause() {<br />
        super.onPause();<br />
        mScannerView.stopCamera();   // Stop camera on pause<br />
    }</p>
<p>    @Override<br />
    public void handleResult(Result rawResult) {<br />
        // Do something with the result here</p>
<p>        Log.e(&quot;handler&quot;, rawResult.getText()); // Prints scan results<br />
        Log.e(&quot;handler&quot;, rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode)</p>
<p>        // show the scanner result into dialog box.<br />
        AlertDialog.Builder builder = new AlertDialog.Builder(this);<br />
        builder.setTitle(&quot;Scan Result&quot;);<br />
        builder.setMessage(rawResult.getText());<br />
        AlertDialog alert1 = builder.create();<br />
        alert1.show();</p>
<p>        // If you would like to resume scanning, call this method below:<br />
       // mScannerView.resumeCameraPreview(this);<br />
    }<br />
}<br />


3

2

 

Udemy Generic 728x90

Spread the word. Share this post!

  • Guest

    Thanks for this tutorial, it’s the easiest i have found to integrate a scanner, i’m totally new to android and needed this for a Uni project !
    is there any way to launch a new screen (activity) instead of replacing the crurent one, so i can press back from the scanner to go back to main screen where is the button?

  • kelvin

    It is nice tutorial. By the way, do you know how to include barcode scanner as well ? Thank you.

  • kevin

    When this library is added to by project ,the apk build size increased to 5 MB. Resulting in my 10MB apk to 15MB

  • Hussein Khalife

    thanks alot , but i have a question , how can i send the scanner result to sqlite database or make a history page of the scanned result ! please help ..

  • Tim Black

    Thanks for the sample!
    I followed your instructions and when I click on the button it just displays a blank view. With debug, the method runs without an error. Just displays blank view.
    Any ideas?

    • Aloysius Michael

      I think i have the solution. Maybe it all about the Camera permission. so i tried adding

      and Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
      startActivityForResult(intent, 0); and after that i commented the Intent to start Camera activity and uncomment the activity of Zxing scanner. it works well now!

      • newbie

        where need to put the Intent? in activity?

    • Martin Montero

      I had the same problem a while ago but I have figured out the problem.
      You may have not yet requested permission for the camera.

      In AndroidManifest.xml, add

      This solved my error. :)

  • JiiN Wee

    Very good sample and tutorial, but i having a problem to show back my previous screen …. it able to scan the qrcode and show the right content but i need to put the scanned data to an edittext, how to stop or quick the camera/scanner?

  • Vishal Bhandare

    I just downloaded the source code & run in android studio. However, when I click on QRSCANNER button, it just disappears & nothing happens then after. I am testing it on Asus Nexus Tablet. Also, on Samsung Galaxy Grand, it works okay. So, I am confused about does it work on devices having OS below 5.0 or is it a device specific issue? Please help me.

    • Vishal Bhandare

      Guys, Any updates on above???

  • Johan Nieuwoudt

    Excellent sample.
    Just one question, how do I close the scan view?

    • Ahmad Bassiouny

      you can do so by adding this code to handleResult method

      mScannerView.stopCamera();
      setContentView(R.layout.activity_main);

      • Johan Nieuwoudt

        Thank you Ahmad,
        Sorry, one last question.
        In the snip below, the toast works, but the setText does not. What can I do to rectify it?
        @Override
        public void handleResult(Result rawResult) {
        SResult = rawResult.toString();
        txtScanResult.setText(SResult);
        Toast.makeText(MainActivity.this, SResult, Toast.LENGTH_LONG).show();

        • Ahmad Bassiouny

          the snip is fine, is it from an activity or fragment ?

          • Johan Nieuwoudt

            It is from the handleResult in the main activity. SResult is also a global variable.
            @Override
            public void handleResult(Result rawResult) {
            SResult = rawResult.toString();
            txtScanResult.setText(SResult);
            mScannerView.stopCamera();
            setContentView(R.layout.activity_main);
            }
            I also just noticed that I can scan only once. If I click on the scan button again, it does not do the scan again.

          • Johan Nieuwoudt

            The once only operation is now corrected after I changed the:
            setContentView(R.layout.activity_main);
            to:
            Intent settingsIntent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(settingsIntent);

  • Vikas Pandey

    camrea does not open.
    There is a method ZxingScannerView.startCamera() evatually calls BarcodeScannerView.startCamera(-1),camerainstance is null.
    Camera is not opening.

    • Ben

      In AndroidManifest.xml, add

  • liting_tlt

    why i can’t scan the QR code more than once? is there a way that i can scan more than once?

    • Ahmad Bassiouny

      you can by uncommenting the last line in the handleResult method

  • Vikas Pandey

    how can we start front camera for scannerview.

  • haze

    can anyone tell me ,how can i save scanned data into my sqlite database ?? is there any one ???

    • Guest

      you get a String back and then db.insert() ? Shouldnt be that difficult if you know how to insert data in your sqlite database

  • Joe

    While scanning the QR Code, I need to capture and save the image too, without opening other camera apps.
    Could somebody help with the code?

  • Er Deep Sidhu

    Thanks, good tutorial

  • Felipe

    It is possible to put something like: builder.setMessage(result.getText().toLink);
    Like we do on toString? I know that exacly like what I wrote above doesnt exist, but I would like to know if there is something that i can do.
    Thanks.

  • Think Techapps

    can ZxingScanner method be changed?

  • William Onnyxiforus

    I am trying all the tutorial but why after i click the QRSCANNER button, it open a blank page and there is an error on my my android studio said “W/CameraBase: An error occurred while connecting to camera: 0″

    • Michael

      Oh, I have these permissions but didnt show a box to accept so when i manually accept permission in app info it works.

      • Radu Bogdan

        And how do you do that ? I tried to adapt the AndroidManifest.xml with but didn’t work. Thanks.

  • meagbenyegah

    Thanks, works 100% don’t forget to add this to your manifest

    • Christian Paul Santos

      Hello meagbenyegah, is there a way to automatically open web pages when scanned?

      • meagbenyegah

        String myUrl = rawResult.getText();

        if (Patterns.WEB_URL.matcher(myUrl).matches()) {
        Intent visitUrl = new Intent(Intent.ACTION_VIEW, Uri.parse(myUrl));
        startActivity(visitUrl);
        }

        • Maverick Plainview

          Hi meagbenyegah, forgive my ignorance, I am very new to android studio and programming in general. But where exactly do we put these String myUrl codes? Because I want the pages to automatically open when the QR code is scanned.

          • meagbenyegah

            It should be within the body of handleResult method

  • Christian Paul Santos

    Is there a way to open the web page automatically when scanned by the qr code?

  • Krishna Ch

    hi, i want to show the scanned result in a TextView that i created under the button in design. and also have added OK and Cancel buttons to alertDialog. want i want is after clicking OK the scanned result should be showed in Textview.

  • Pramod

    It is not working on marshmallow device. Could you please help me.

    • midhilaj m

      permission problem ???

  • Aqsa

    thanks for simple tutorial. can u guide me that how can i scan 2 dimensional barcodes?

  • Raj ak

    How to add the flashlight button and done button on the scanner view android ? can any one help me please….

  • Safwan Senen

    why the coding cannot resolve symbol ‘scan’ and ‘handler’. sorry I’m newbie in android studio

  • Mayur

    can we remove all control button from camera if we do so please tell me

  • Scott Przybilla

    https://uploads.disquscdn.com/images/36e1b5a94e223ab543a46e42ab594f49aef61047b4a13d445e22f8d3fa4928af.png
    having a lot of issues with the section above and i don’t understand why.

    • Shiza Shafiq

      Replace ‘"’ with ‘ ” ‘ on each side.

  • Phan Lý Phương Nghi

    I want to add button Finish on screen scan. Can you help me?
    Many thanks.

  • Mehmet Tamaç

    Its not work about camera permission .

  • Viane Phill

    i want scanned code in textview its not working for me, can anyone tell me how can i get in textview

  • Snehal Shirsat

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