Logo

Navigation
  • Home
  • Android
  • Web
  • Raspberry Pi
  • PHP
  • Go

Android QR Code scanner

By Rajinder Deol | on March 4, 2015 | 34 Comments
Android Technology

This post is in response to queries posted by few users for my article “Android Barcode Scanner”

In this post I will re-use the code which I have written in my old post, here is a quick summery,

  • I have written an application to scan barcodes.
  • My requirement was not to depend on any other application to scan barcodes

So after some R&D online I came across an awesome library called Zxing (Zebra crossing)

This library offers scanning UPC-A, UPC-E, EAN-8, EAN-13, QR Code, RSS-14, RSS Expanded, Data Matrix, Aztec, PDF 417, Codabar, ITF, Codes 39, 93, and 128. So I will extend my old application and add feature to scan Bar code and QR code.

Step 1 : create a project and add ZXing library in you app

I have written step by step instructions on how to do this in my prevous post click here for reference.

Step 2 : update layout

We will add a button in our activity layout and add a onclick function named “scanQR”


 <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/scan_qrcode"
        android:onClick="scanQR"
        android:id="@+id/btn_qrcode"
        android:layout_marginBottom="@dimen/activity_vertical_margin" />

Step 3 : Create the method “scanQR” in your activity class

In the code below, function “scanQR” is similar to function “scanNow” detailed in my old post for scanning barcodes, except for the DesiredBarcodeFormat which is “QR_CODE_TYPES”. This is where I am selecting QR code to be scanned.

 
public void scanQR(View view){
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
        integrator.setPrompt(String.valueOf(R.string.txt_scan_qr_code));
        integrator.setResultDisplayDuration(0);     
        integrator.setCameraId(0);  // Use a specific camera of the device
        integrator.initiateScan();
    }

Below is the OnActivityResult function to handle the result. I am displaying the format and content (URL) of QR code on screen in text views you can open a browser and open the URL.


 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        //retrieve scan result
        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);

        if (scanningResult != null) {
            //we have a result
            String scanContent = scanningResult.getContents();
            String scanFormat = scanningResult.getFormatName();

            // display it on screen
            formatTxt.setText("FORMAT: " + scanFormat);
            contentTxt.setText("CONTENT: " + scanContent);

        }else{
            Toast toast = Toast.makeText(getApplicationContext(),"No scan data received!", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

Related

Share this story:
  • tweet

Recent Posts

  • RaspberryPi with PiHole to block ads everywhere

    September 22, 2021 - 2 Comments
  • Reviving RaspberryPi 1 Model B in 2021 After 7 years

    September 13, 2021 - 1 Comment
  • NodeJS Consumer for AWS SQS using Docker

    November 10, 2018 - 3 Comments

Author Description

34 Responses to “Android QR Code scanner”

  1. May 26, 2015

    Roman Reply

    Hi, please, sir, the formatTxt and contentTxt is red in my Android Studio. It writes: “cannot resolve symbol-formatTxt-“. Do you know why?

    • May 27, 2015

      Rajinder Deol Reply

      Hi Roman,

      these are two text views that you need to create in your layout. Check line number 18 to 26 in code here : https://github.com/rajdeol/android-barcode-scanner/blob/master/app/src/main/java/in/whomeninja/android_barcode_scanner/HomeActivity.java

  2. June 27, 2015

    Ted Reply

    Hi Raj,

    Thank you very very very much for these great tutorials. I had been struggling all day long trying to figure out the way to integrate Zxing github project into my project, until finally found your tutorial. They work like magics.

    Could you please make another example showing the way to generate “QR code”?

    Do you know anywhere to find a good documentation to use this zxing-android-embedded?

  3. June 28, 2015

    Rajinder Deol Reply

    Hi Ted,

    there are a lot of libraries available to generate QR code. I would recommend generating QR code on server side rather than on your device.

    For server side QR code generation we have an awesome library : http://phpqrcode.sourceforge.net/

    However if you still want to generate QR code in your application then we can use the same Zxing library. I will post a tutorial real soon.

  4. July 25, 2015

    wer Reply

    How to add another activity that will input strings and then it will generate into qr code, can you make another example please..

  5. July 27, 2015

    Rajinder Deol Reply

    Hi Wer,

    I am already writing an article to generate QR code from android app, Will update the link very soon.

  6. September 16, 2015

    Alexander Reply

    En el método scanQR muestra los errores:

    Cannot resolve symbol txt_scan_qr_code:

    integrator.setPrompt(String.valueOf(R.string.txt_scan_qr_code);

    Cannot resolve method:

    integrator.setResultDisplayDuration(0);

  7. January 24, 2016

    Matias Reply

    Hi! thank you for this tutorial it was very usefull, i would like to know how to change the orientation of the scanner to portrait.
    Thanks!!!

    • February 15, 2017

      Rajinder Deol Reply

      Hi Matias,

      I have written a detailed post on how to change orientation to portrait please read : https://rajislearning.com/android-barcode-scanner-vertical-orientation-and-camera-flash/

  8. February 22, 2016

    bhawesh Reply

    Hi,

    I am a newbie and tried the same but getting below error while clicking scan button
    CaptureActivity: Unexpected error initializing camera
    java.lang.RuntimeException: Fail to connect to camera service

    Any idea?

    • February 22, 2016

      bhawesh Reply

      I Added the below snippet but no luck..

      • February 22, 2016

        bhawesh Reply

        uses-permission android:name=”android.permission.CAMERA”

  9. March 25, 2016

    firdaus Reply

    do you have source code for this one?

    • March 26, 2016

      Rajinder Deol Reply

      Hi Firdaus,

      the source code is available on my Github below is the link to the code :

      https://github.com/rajdeol/android-barcode-scanner

      The post is for Android Barcode Scanner but if you read my blog post above I have detailed the steps you need to do to make the code work for QR code scanning

      Regards
      Raj

  10. April 5, 2016

    chetan joshi Reply

    hi sir,it is showing
    Error:Execution failed for task ‘:app:dexDebug’.
    com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process ‘command ‘C:\Program Files\Java\jdk1.8.0_51\bin\java.exe” finished with non-zero exit value 2

    • April 30, 2016

      Rajinder Deol Reply

      Are you using android studio for your project..?

  11. July 4, 2016

    Ralph Reply

    Hi Mr. Rajinder,

    Thank you for this tutorial. I would like to ask how to continuously scan a QR Code. Thanks.

  12. March 9, 2017

    Moon Sabeen Reply

    Hi Raj,

    Thank you for this tutorial. Please note I am getting below error in public void scanQR(View view) method:

    Cannot resolve symbol txt_scan_qr_code:
    integrator.setPrompt(String.valueOf(R.string.txt_scan_qr_code);

    I tried to resolve it by declaring it as a string variable, but it does not resolved. Please guide.

    Thanks in advance.

    • March 9, 2017

      Rajinder Deol Reply

      Hi Moon,

      That is just a prompt message on the scan screen at the bottom, what I have done in my updated code is to use a string instead of using a value from the String resource.

      Check my code here : https://github.com/rajdeol/android-aadhaar-card-scanner/blob/master/app/src/main/java/com/rajdeol/aadhaarreader/HomeActivity.java#L78

      Alternatively you can use any variable holding string value here.

      • March 12, 2017

        Moon Sabeen Reply

        Hello Raj,

        Thanks for your quick response.
        One more thing I want to share. After connecting physical device, the app starts, scan screen appears but it does not scan any QR code and gives following error:

        “Unfortunately QRApp has stopped”

        I am trying to figure out what could be the issue. I would be thankful if you can also guide in this regard.

        Thanking you.

        • March 15, 2017

          Rajinder Deol Reply

          Hi Moon,

          connect you android device with Android studio and put it in debug mode this will generate logs in Android studio which you can view and see the error.

          Errors will be visible on “log cat”, share the error output and I will have a look at it. Also please check the API version of your app as well, try and match it with API version in my app.

          • March 16, 2017

            Moon Sabeen Reply

            Hi Raj,

            Thank you for your time and response.

            I checked the version thing but still I get the following highlighted errors in logs. I tried to resolve but unfortunately no luck.
            (If you would suggest I can share complete logs).

            1) E/dalvikvm: Could not find class ‘android.graphics.drawable.RippleDrawable’, referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering

            2) E/AndroidRuntime: FATAL EXCEPTION: main
            java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=49374, result=-1, data=Intent { act=com.google.zxing.client.android.SCAN flg=0x80000 (has extras) }} to activity {ad.qr_scan_app_test1/ad.qr_scan_app_test1.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3145)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3188)
            at android.app.ActivityThread.access$1100(ActivityThread.java:134)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4744)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
            Caused by: java.lang.NullPointerException
            at ad.qr_scan_app_test1.MainActivity.onActivityResult(MainActivity.java:81)
            at android.app.Activity.dispatchActivityResult(Activity.java:5192)
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3141)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3188) 
            at android.app.ActivityThread.access$1100(ActivityThread.java:134) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247) 
            at android.os.Handler.dispatchMessage(Handler.java:99) 
            at android.os.Looper.loop(Looper.java:137) 
            at android.app.ActivityThread.main(ActivityThread.java:4744) 
            at java.lang.reflect.Method.invokeNative(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:511) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
            at dalvik.system.NativeStart.main(Native Method) 

            Thank you once again.

            • March 17, 2017

              Rajinder Deol Reply

              Hi Moon,

              seems like you have not compiled the support libraries for your version of android sdk.

              Can you please share your version sdk you are using for your app.

              Also a useful link related to this error:
              http://stackoverflow.com/questions/37108618/could-not-find-class-android-graphics-drawable-rippledrawable

  13. April 13, 2017

    Pradnya Patil Reply

    Hi Sir
    Your Barcode Scanner Tutorial is very helpful for me. so Thanks

  14. April 13, 2017

    Pradnya Patil Reply

    Sir I want imageslider dynamically in android
    add images through admin panel see in app.
    Sir please help me

    • April 18, 2017

      Rajinder Deol Reply

      Hi Pradnya,

      you can use wordpress as your admin panel and it comes with a great admin panel. Then you can use wordpress REST API to fetch the uploaded images into your app. Read https://rajislearning.com/writing-secure-rest-webservices-with-php-for-android/ for WordPress REST API.

      Also read my post Writing Secure REST webservices with PHP for Android on how to fetch data from REST API.

  15. April 17, 2017

    jawahar Reply

    Really nice post.. thank you very much bro..

    • April 18, 2017

      Rajinder Deol Reply

      Thanks for the kind words Jawahar, let me know if you need more help.

  16. June 9, 2017

    Habib Reply

    Hi,
    Thanks for useful posts.
    I want to know if it is possible to scan Barcode and QR code together. (I mean only by one button)

    Regards,
    Habib

    • June 13, 2017

      Rajinder Deol Reply

      Hi Habib,

      I think you can do that but the scan will be really slow. This library scans image taken by camera to decide which barcode format is in the image and then decodes it. Specifying the format at the beginning just make the scan more quick.

  17. November 30, 2017

    admin Reply

    hi,
    i have two barcode matches then get the json data in dialogbox ,how to apply this

    • November 30, 2017

      Rajinder Deol Reply

      Hi,

      you need to specify some more details, I think what you are saying is, you scan a QR-code and get JSON string in return. If that is the case then you need to parse the JSON string and extract the data. If you have a QR-Code which I can look at I will be able to guide you more.

      • December 22, 2017

        admin Reply

        Sir, i want a match barcode and get json data in android dialogbox…
        plzzz sir help me

  18. December 22, 2017

    admin Reply

    sir, i want a match barcode and get json data in android dialogbox ..
    plzz sir help me

Leave a Reply to firdaus

Leave a Reply to firdaus Cancel Reply

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


*
*

Recent Posts

  • RaspberryPi with PiHole to block ads everywhere
  • Reviving RaspberryPi 1 Model B in 2021 After 7 years
  • NodeJS Consumer for AWS SQS using Docker
  • Laravel development using docker-compose with nginx and Mysql
  • Writing Your First Service in Golang Go-Micro

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 9 other subscribers

Categories

  • Android (7)
  • Education (9)
  • Go (2)
  • PHP (5)
  • Raspberry Pi (4)
  • Technology (17)
  • Web (8)

Author details:

Raj Deol

Raj Deol

Traveller, Foodie and electronics enthusiast.

View Full Profile →

© 2016. All Rights Reserved.