Android barcode scanner using Zxing

How to call Zxing barcode scanner from you application using Intent? The ZXing project provides a standalone barcode reader application using Android's intent mechanism, can be called by other applications who wish to integrate barcode scanning.

If you want to integrate barcode scanning directly into your application without relying on having the separate ZXing application installed, then you can do so! It's an open source project and the code is available for free and can be downloaded at http://code.google.com/p/zxing/.You are going to add the whole ZXing project core to your app and modify as you wish. This way your app will no longer require ZXing app exist in client device.

ZXing uses phone or tablet camera to scan barcodes, QR codes or multi-format 1D/2D barcodes. So the scan result highly depends on the camera quality and resolution. ZXing has relatively fast processing speed. More importantly, it is an open source projectso you can do whatever changes you like to it!

Android barcode scanner using Zxing

Example source code for using Zxing barcode scanner from you application using Intent



Source for main.xml screen layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="vertical" 
 android:layout_gravity="center">
 <TextView 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" 
  android:text="@string/hello"
  android:gravity="center" android:textSize="25sp"/>
 <Button android:text="Scan QR Code" android:id="@+id/scanner" 
  android:layout_width="wrap_content" android:layout_height="wrap_content" 
  android:gravity="center" android:layout_gravity="center_horizontal">
 </Button>
 <Button android:text="Scan BAR Code" android:id="@+id/scanner2" 
  android:layout_width="wrap_content" android:layout_height="wrap_content" 
  android:gravity="center" android:layout_gravity="center_horizontal">
 </Button>
</LinearLayout>

Source for AndroidScanner.java program for barcode scanning

package com.as400samplecode;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AndroidScanner extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        try {
            Button scanner = (Button)findViewById(R.id.scanner);
            scanner.setOnClickListener(new OnClickListener() {
               
                public void onClick(View v) {
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                    startActivityForResult(intent, 0);
                }

            });
           
            Button scanner2 = (Button)findViewById(R.id.scanner2);
            scanner2.setOnClickListener(new OnClickListener() {
               
                public void onClick(View v) {
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
                    startActivityForResult(intent, 0);
                }

            });
           
        } catch (ActivityNotFoundException anfe) {
            Log.e("onCreate", "Scanner Not Found", anfe);
        }
       
    }
   
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                String contents = intent.getStringExtra("SCAN_RESULT");
                String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
                // Handle successful scan
                Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format , Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP, 25, 400);
                toast.show();
            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
                Toast toast = Toast.makeText(this, "Scan was Cancelled!", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP, 25, 400);
                toast.show();
               
            }
        }
    }

}

TIP: You can make your application check for existence of the Zxing application. 

See IntentIntegrator for a possibly easier way to integrate. In particular this will handle the case where Barcode Scanner is not yet installed. Click on the link below for more details

http://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentIntegrator.java

Sample code from IntentIntegrator.java

private static final String PACKAGE = "com.google.zxing.client.android"; 

catch (ActivityNotFoundException e) {
      return showDownloadDialog(activity, stringTitle, stringMessage, stringButtonYes, stringButtonNo);
    }

private static AlertDialog showDownloadDialog(final Activity activity,
                                                CharSequence stringTitle,
                                                CharSequence stringMessage,
                                                CharSequence stringButtonYes,
                                                CharSequence stringButtonNo) {
    AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
    downloadDialog.setTitle(stringTitle);
    downloadDialog.setMessage(stringMessage);
    downloadDialog.setPositiveButton(stringButtonYes, new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialogInterface, int i) {
        Uri uri = Uri.parse("market://search?q=pname:" + PACKAGE);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        try {
          activity.startActivity(intent);
        } catch (ActivityNotFoundException anfe) {
          // Hmm, market is not installed
          Log.w(TAG, "Android Market is not installed; cannot install Barcode Scanner");
        }
      }
    });
    downloadDialog.setNegativeButton(stringButtonNo, new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialogInterface, int i) {}
    });
    return downloadDialog.show();
  }

More information on Zxing scanner application


According to ZXing (pronounced "zebra crossing") is an open-source, multi-format 1D/2D barcode image processing library implemented in Java, with ports to other languages. Our focus is on using the built-in camera on mobile phones to scan and decode barcodes on the device, without communicating with a server. However the project can be used to encode and decode barcodes on desktops and servers as well. We currently support these formats:

  • UPC-A and UPC-E
  • EAN-8 and EAN-13
  • Code 39
  • Code 93
  • Code 128
  • QR Code
  • ITF
  • Codabar
  • RSS-14 (all variants)
  • Data Matrix
  • PDF 417 ('alpha' quality)
  • Aztec ('alpha' quality)

To scan codabar format pass the intent extra the format as explained below

/**
* Comma-separated list of formats to scan for. The values must match the names of
* {@link com.google.zxing.BarcodeFormat}s, e.g. {@link com.google.zxing.BarcodeFormat#EAN_13}.
* Example: "EAN_13,EAN_8,QR_CODE"
*
* This overrides {@link #MODE}.
*/
public static final String FORMATS = "SCAN_FORMATS";
intent.putExtra("SCAN_FORMATS", "CODABAR");


List of barcode formats supported by ZXING

/** QR Code 2D barcode format. */
public static final BarcodeFormat QR_CODE = new BarcodeFormat("QR_CODE");

/** DataMatrix 2D barcode format. */
public static final BarcodeFormat DATA_MATRIX = new BarcodeFormat("DATA_MATRIX");

/** UPC-E 1D format. */
public static final BarcodeFormat UPC_E = new BarcodeFormat("UPC_E");

/** UPC-A 1D format. */
public static final BarcodeFormat UPC_A = new BarcodeFormat("UPC_A");

/** EAN-8 1D format. */
public static final BarcodeFormat EAN_8 = new BarcodeFormat("EAN_8");

/** EAN-13 1D format. */
public static final BarcodeFormat EAN_13 = new BarcodeFormat("EAN_13");

/** UPC/EAN extension format. Not a stand-alone format. */
public static final BarcodeFormat UPC_EAN_EXTENSION = new BarcodeFormat("UPC_EAN_EXTENSION");

/** Code 128 1D format. */
public static final BarcodeFormat CODE_128 = new BarcodeFormat("CODE_128");

/** Code 39 1D format. */
public static final BarcodeFormat CODE_39 = new BarcodeFormat("CODE_39");

/** Code 93 1D format. */
public static final BarcodeFormat CODE_93 = new BarcodeFormat("CODE_93");

/** CODABAR 1D format. */
public static final BarcodeFormat CODABAR = new BarcodeFormat("CODABAR");

/** ITF (Interleaved Two of Five) 1D format. */
public static final BarcodeFormat ITF = new BarcodeFormat("ITF");

/** RSS 14 */
public static final BarcodeFormat RSS14 = new BarcodeFormat("RSS14");

/** PDF417 format. */
public static final BarcodeFormat PDF417 = new BarcodeFormat("PDF417");

/** RSS EXPANDED */
public static final BarcodeFormat RSS_EXPANDED = new BarcodeFormat("RSS_EXPANDED");

55 comments :

  1. Thanks for the example code. It was just what I needed to get started.
    I pasted it into my test app and it worked with no issues.

    Much appreciated

    ReplyDelete
    Replies
    1. Hi John,

      Can you share your application ( Working project source code).
      I am novice on Java & Android. But i really wish to learn from the working project.

      Please advise.

      Thank you.

      Regards,
      Mic

      Delete
    2. Dear John,

      I just move from c# programming to Android/Java programming. Could you please share your simple application to use Zxing for studying? I am very new in Java and I start using eclipse too.

      Thank you very much,
      Thanin

      Delete
    3. Hi John,

      I was trying to run QR Scanner application by using above sample code, but its automatically exit the application.
      I have added also core jar (Zing) file to application.
      Could you send your whole application to gsp.437@gmail.com

      Delete
    4. pls i need help, i copied the codes above and pasted into a new project in my ADK, but it was realling giving me errors.
      the truth is i am a noob in both android and java development, and i really need a software that will scan a qrcode, it is a fragment of a system i am working on as an academic project, pls help me

      Delete
    5. hi john can u pls help me regarding this code????????????????

      Delete
  2. Hello, even I am developing a barcode scanner, so do I need to add a camera code into it..? And what about the scanning result? I want the output to be the price of the product. How do I integrate the sqlite code and all... Please help me asap

    ReplyDelete
    Replies
    1. No you needn't to add camera code into it. Scanning result can be retrieved in onActivityResult method. you may store the price in your sqlite database.

      Delete
  3. You can use the scanner as shown in the example above. It needs the zxing barcode app to be already installed on the device. Or you can code your app to check if the barcode app is installed or not, and if not installed then guide the user to the market for download.

    Another approach will be to download the source code for the zxing project and put it in your project so you will not have to depend on the other app and it will get deployed with yours.

    Now to get prices you must take the barcode and fetch the price from SQLite database or a HTTP request. There are examples available in this blog to help you.

    ReplyDelete
  4. Would like codabar format support, but otherwise it's great.

    ReplyDelete
  5. There is support for codabar format in zxing. I have added a section above to explain.

    ReplyDelete
  6. Thanks a lot. Okay, I've got yet another query in my mind.. What if I want to construct my own database for products alongwith their prices? I googled a lot but dint find any article on sqlite that wud suffice my needs...

    ReplyDelete
  7. You can look at this for SQLite query from your database of items and prices...

    Android SQLITE query selection example

    ReplyDelete
  8. Sheetal,

    Sounds like we are working towards completing the same type of project. I had decided to create a barcode scanning app from my Tech Capstone project...this has been a nightmare! Maybe by collaborating of what we have accomplished, we can help each other out. Like they say 2 heads are better than one! You can email me also jblack0526@yahoo.com.

    I hope to hear back from you.

    ReplyDelete
  9. Hi, I am scanning the barcode using zxing. everything is fine but i am facing problem i.e., while scanning i found some extra icons i.e., topleft, right top and bottom right icons. instead of that icons i need 2 put my own button i.e., close button. how can i achieve this?? this is my mail id s.seshu143attherategmaildotcom.
    thanks in advance. i need asap..

    ReplyDelete
  10. Satya,

    I guess if you calling the zxing barcode app then you have no control over the screen. May be you need to download the source code and put that in your project and modify it.

    ReplyDelete
  11. Hello,
    I am developing barcode scanning application by integrating ZXing into my app,I can launch it and scan flawlessly but I want to store scanned barcode values onto mobile,am totally stuck here,So could anyone help me doing this

    ReplyDelete
  12. Need more detail on what you are trying to do.
    Anyway after you get the scanned barcode value you can store it in a SQLite database or make Web Request to store it on a server database.

    ReplyDelete
  13. Lot of people seem to be looking for a solution to this problem. Let me explain:

    I am developing a mobile app which needs barcode scanning. However after the scan, I want to handle the results myself.

    So in essence, I want to launch barcode scanner and once it scans a barcode, I want it to return it back to my app so I can manipulate it. Currently I am facing these issues:

    1. When I launch barcode scanner, it takes user to the app and user has to press "open" button to launch it. Is there a way to avoid this?

    2. After barcode scanner scans a code, the only options are to act on it (open in browser etc.), instead I want it to automatically (or after pressing close) return the data back to my app, so I can use it.

    3. I am currently using phonegap + other abstract frameworks. This means I cannot use the source code of barcode scanner directly in my app.

    It should be very easy to add support to barcode scanner where, if a parameter "returndata" is passed, after scanning it simply returns the data to calling app?

    ReplyDelete
    Replies
    1. hey can you please tell me the barcode scanner application in android.

      i read the zxing application i want to convert number to qrcode in android.

      can u please tell me how can i convert?

      if possible try to send the links or source code to my mail\

      shankarraopilli@gmail.com

      Delete
  14. hi,
    I'm having a problem with some samples above. Do I have to use the zxing to your example? BTW, I'm new for androids. You can send me back here. >> error22.mekhef@ymail.com
    tnx a lot . .

    ReplyDelete
  15. Yes you need the Zxing app in your phone or tablet for this demo app to work. To avoid that you have to get the source from the zxing website and put that in your project. There are instructions about that in the site itself. I haven't tried that yet!

    ReplyDelete
  16. how to use?:"Sample code from IntentIntegrator.java"

    the app fc when the barcode scanner is absent..

    i did not implemtn the sample code yet,because i don't know..pls help

    phoenix_dragon21@yahoo.com

    ReplyDelete
  17. thank you so much for this tutorial.
    I have a questions about no which is provided by scanner.
    how to get complete information form given number.
    i m waiting for your +ve response.

    thanks and regards
    rakesh

    ReplyDelete
  18. This application just scans the Barcode and provides you with the scanned value. After that you can take the value and make a HTTP request to your Web service and get all the information about the Product from your ERP backend system.

    ReplyDelete
  19. Hi all, I would really appreciate if someone can upload a working android project with code to help me get started

    ReplyDelete
  20. Nice one thanks for sharing...!!

    ReplyDelete
  21. i want to convert my app from version 14 to version 12, plz help me.

    ReplyDelete
  22. Here is an Android barcode encoder which works nice!
    http://www.keepdynamic.com/barcode-for-android/

    ReplyDelete
  23. The above code works flawlessly when I used QR code.But when I try to scan product barcode using Scan BAR code ,it doesnt seem to work.I try to click camera button but nothing happens..Has anyone got that part working or guide me in resolving the issue

    ReplyDelete
    Replies
    1. also product barcode is working now but is slow as compared to the qr reader

      Delete
    2. The qrcode will always scan faster than the barcode.

      Delete
  24. Nice post.Give it up. Thanks for share this article. For more visit:android development

    ReplyDelete
  25. How to add library for this application and where to place IntentIntegrator.java file.Is there any requirement to add library or not?If yes then from where to download it and wehere place it?Plrase give reply asap

    ReplyDelete
    Replies
    1. You can send me solution on pooja_patel_aaa@yahoo.com

      Delete
  26. Nice post.Give it up. Thanks for share this article. For more visit:android development

    ReplyDelete
  27. can you send me the source please?

    clbr@sapo.pt

    thanks

    ReplyDelete
  28. Nice post.Give it up. Thanks for share this article. For more visit:android development

    ReplyDelete
  29. Hi, am started the bar code scanner but it seems to be not worked in my app, could u explain me how to add library for this application and where to place IntentIntegrator.java file, could tell me how to place library file then from where to download it and wehere place it..
    or else can u send me on mail
    bosekarthiks@gmail.com

    ReplyDelete
  30. Above code is working very well for QR CODE but it is not working for Bar Code scanning . So what is going wrong with me. Any help really Appreciable.

    ReplyDelete
  31. Thanks for sharing this article.. I implement this scanner in my application. Intially it work file while i m trying it in my android mobile phone.. but after some time it showing "unfortunately has stopped" while pressing scan qrcode button.. Plz any body help to fix this issue

    ReplyDelete
  32. Hello, your application code and are great! Thank you for your work! I would like to use your code, it is sufficient to only scan the EAN me and send the URL, what should I do when editing code? Thank you for your time.

    ReplyDelete
  33. Hi
    With the above code it works after we instal the barcode scanner application.
    If I don't have that application, it will ask to install the application or it uses Google's default camera page opens (where we can see Google logo) to capture the image.

    But my requirement is, it should neither open Google camera capturing images nor bar code scanner (zxing application) application. My should should take care opening the camera itself (off course it can use zxling library internally) and capture without dependent on any other app which is installed or not-installed.

    ReplyDelete
  34. Can QR code detect or trace "who ,when and from where qr scan".
    can Qr code scan every Student individual id from single qr code.

    ReplyDelete
  35. Please send me base code. Please advice me.

    ReplyDelete
  36. Superb, its work fine without any issue... very much appreciated...

    ReplyDelete
  37. This was not that easy to manage, due to the limitation of Android library I was require to pull everything from Androidmanifest.xml.Chances are there you will overcome to runtime exception error which I did received.

    ReplyDelete
  38. I want to open the camera in the middle of the screen with the 4 square corner. Please Help me to do that.

    ReplyDelete
  39. how to use barcode scanner to check data in database?

    ReplyDelete
  40. it is working fo QR code but not working for any bar code like -
    UPC_A
    CODABAR

    is any way to scan barcode (not QR code)

    ReplyDelete
  41. HI..I want to know How can I scan bar code without using camera...Plz explain me...Its Urgent..
    Thanks..

    ReplyDelete
  42. I implement this scanner in my application. Intially it work file while i m trying it in my android mobile phone.. but after some time it showing "unfortunately has stopped" while pressing scan qrcode button.. Plz any body help to fix this issue
    Agen Poker Online Indonesia Terpercaya

    ReplyDelete
  43. Hi.
    Could you send me the code, please?
    email: anya230294@gmail.com

    Thanks

    ReplyDelete
  44. hi john can u pls send me the whole app pls my email id is jainshilpi3@gmail.com

    ReplyDelete