Friday, December 2, 2011

Installing the Barcode Plugin for PhoneGap Android

Some folks are having problems getting the Barcode Scanner plugin up and running for PhoneGap Android so I figured I'd write a more detailed explanation on how to get it up and running.

First you'll want to go download the Library Project part from GitHub. You'll want to use the code from github as I've modified it slightly so that it is responds to the correct intent.

Once downloaded you'll want to create a new Android project from existing source in Eclipse. The project name shows up as CaptureActivity but I'm going to change it to BarcodeLibrary which is more descriptive.


but don't click on Finish yet. Click the Next button...


and select the highest level of Android SDK you have installed before clicking Finish.

Now that you've created the library project which contains the barcode scanning code you'll want to right mouse click on the BarcodeLibrary project and select Properties. In the Properties dialog, select the Android tab and ensure the Is Library checkbox is click. The benefit of doing things this way is you can link this library into multiple Android projects without needing to copy a bunch of source around.

Now that we've got our library setup let's add it to our project. Right click on your PhoneGap project, in my case it is called BarTest, and select Properties.


In the Android tab under the library section click the Add button.


In the Project Selection dialog select BarcodeLibrary.


Now our application can use the BarcodeLibrary project so we can click OK.

Let's now add in the BarcodeScanning plugin code. Under the assets/www directory copy in the barcodescanner.js file from github. Under src, right click and create a new package com.phonegap.plugins.barcodescanner then copy in the BarcodeScanner.java file from github.

So were all set now right? Well know we forgot one thing. We need to add a line for our plugin under the res/xml/plugins.xml file so let's open that up now and add this line after the last <plugin/> tag but before the </plugins> line.

<plugin name="BarcodeScanner" value="com.phonegap.plugins.barcodescanner.BarcodeScanner"/>

Okay, so were good now. Well no, there is one more bit to take care of. Open up your AndroidManifest.xml file so we can add some new activities that will take care of the scanning and encoding. You'll need to paste these activity lines inside the <application/> tag.

<activity android:name="com.google.zxing.client.android.CaptureActivity"
    android:screenOrientation="landscape"
    android:configChanges="orientation|keyboardHidden"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
    android:windowSoftInputMode="stateAlwaysHidden">
  <intent-filter>
    <action android:name="com.phonegap.plugins.barcodescanner.SCAN"/>
    <category android:name="android.intent.category.DEFAULT"/>
  </intent-filter>
</activity>
<activity android:name="com.google.zxing.client.android.encode.EncodeActivity" 
    android:label="@string/share_name">
  <intent-filter>
    <action android:name="com.phonegap.plugins.barcodescanner.ENCODE"/>
    <category android:name="android.intent.category.DEFAULT"/>
  </intent-filter>
</activity>
Update: With later versions of PhoneGap the CAMERA permission was removed as it was not required. However, for the barcode scanner it is. So add the following permissions line:

<uses-permission android:name="android.permission.CAMERA" />

Alright, finally we are all setup. But how does one call the BarcodeScanner? Well we provide two main piece of functionality.

Scan
window.plugins.barcodeScanner.scan( function(result) {
        alert("We got a barcode\n" +
                  "Result: " + result.text + "\n" +
                  "Format: " + result.format + "\n" +
                  "Cancelled: " + result.cancelled);
    }, function(error) {
        alert("Scanning failed: " + error);
    }
);

Encode
window.plugins.barcodeScanner.encode(BarcodeScanner.Encode.TEXT_TYPE, "http://www.nytimes.com", function(success) {
        alert("encode success: " + success);
      }, function(fail) {
        alert("encoding failed: " + fail);
      }
    );

I've put together a small example html (and css) page which will be listed below that you can use to test the BarcodeScanner.



If you have problems with the Barcode Scanner the best place to ask questions is over on the PhoneGap Google Group where I check multiple times per day for questions I can answer.

122 comments:

  1. i need this for iPhone, any idea?

    ReplyDelete
  2. the plugin for iphone here https://github.com/phonegap/phonegap-plugins/tree/master/iPhone/BarcodeScanner

    thank you

    ReplyDelete
  3. Yup, and the BlackBerry one is here:

    https://github.com/phonegap/phonegap-plugins/tree/master/BlackBerry/BarcodeScanner

    ReplyDelete
  4. Wow ! what a nice and useful information about installing a barcode plugins. You give step by step detail of this process. Now a days many smartphone support the barcode application.

    barcodes

    ReplyDelete
  5. HI,
    I have another phoneGap Android project(using another plugin) already. Can I add this Barcode part into my existing project?

    thanks

    ReplyDelete
  6. @freshstock

    Yes, there is no limit to the amount of plugins you can use in a PhoneGap app.

    ReplyDelete
  7. My barcode plugin for Android is working fine when I do the build using the Eclipse workspace in my desktop.

    However, when I create the APK file through the build sercices hosted at build.phonegap.com, the resultant APK file throws me "Class Not found" error.

    Please help

    ReplyDelete
  8. @gvd

    I'm not sure that build.phonegap.com supports external plugins yet. You'll want to check with them at: http://community.phonegap.com/nitobi/products/nitobi_phonegap_build?from_gsfn=true

    ReplyDelete
  9. Thank you very much for this write-up, very straightforward and helpful.

    I just wanted to point out that it looks like some of your code example for the androidManifest.xml file was cut off, specifically the two closing intent-filter and activity tags are cut in half.

    Thanks again -

    Nick

    ReplyDelete
  10. @Nick

    Thanks, I updated the manifest.xml section. It's a pain to escape XML in blogger.

    ReplyDelete
  11. I know this is a bit old, however, I tried these instructions and keep getting a ForceClose (in emulation / phone) for the Scan portion.

    I noticed, as well, that the LibraryProject requires an AndroindManifest.xml file for the project to even compile, not sure if this was a recent change. I just copied the manifest file from the project so it would build. Works, but not sure if that is causing me the guff.

    When it ForceCloses, it closes stating that the com.google.zxing.client.android.CaptureActivity class not found.

    I have tried everything I can think of, including following multiple (similar) tutorials written up, deleting the projects and re-creating them (several times) to not avail. Would appreciate any insight you may have on this.

    ReplyDelete
  12. Hi Simon, I had a quick question, wondered if you had any insight:

    The barcode scanner plugin worked great on an original Droid I was borrowing. Now I have a Droid 2 (A955) and for some reason the camera view when using the barcode scanner plugin is squished and the x and y axes are inverted (moving the phone up moves the image down, etc.)

    Any ideas why this might be? Any help at all is most appreciated.

    Thanks,

    Nick

    ReplyDelete
  13. FWIW, I was able to fix my previous problem - apparently attempting to force the plugin to run in portrait in the manifest yields unpleasant results!

    ReplyDelete
  14. @Unknown

    Sorry, I can't help you further. The tutorial that I've written works for me and a number of other folks at my work place have used it to get the BarcodeScanner working.

    ReplyDelete
  15. @Nick

    Sorry, I'm not sure why that would be the case. I'd try downloading the "BarcodeScanner" app from the marketplace on your Droid 2 to see if the same problem exists.

    ReplyDelete
  16. hi Simon ,

    great tutorial and also great work.

    i am developing phonegap application in which i need to scan barcode.i have done the same by using barcode scanner plugin.

    now i want if barcode reader is unable to scan code in 10 or 20 seconds then it should back to the application with retry alert.

    is this possible?

    I have seen some setTimeout and setInterval functions of javascripts but not so helpful.

    Please help .

    ReplyDelete
  17. Simon, thanks for the great tool! We're using it in our app, and one of the last things we have to do is to customize the scan screen. Is there a simple way to do this I might be overlooking? Seems like you have to assign an Android theme to it. Is a png placement or similar possible easily?

    Where to start on this?

    Thanks much!

    ReplyDelete
  18. @eskim0

    You'd have to dig into the library project to see where you can add a something to the scan screen.

    ReplyDelete
  19. Thank you so much for this post, it was very helpful! Great work!

    ReplyDelete
  20. Does anyone have any experience using this with a Samsung Galaxy Tab or similar Android tablet?

    My Galaxy Tab 2 (7.0)'s back facing camera has a fixed focus (presumably at infinity) and thus can't seem to read codes. Can this behavior be changed, OR can the Barcode Scanner plugin be changed to use the front-facing camera? Any help is appreciated.

    Nick

    ReplyDelete
  21. For those of you as new to this as me, when Simon writes, Now that we've got our library setup let's add it to our project. Right click on your PhoneGap project. (I am pretty that) he means a Phonegap project that is in GitHub, a little further up the tree from phonegap-plugins. I am trying to work with phonegap-startup but am not sure that is the correct one.

    ReplyDelete
  22. @pdschuller

    No, I mean the Android application you are working on that uses PhoneGap. You have to add the library into your application project so the plugin can find the right classes when it is called.

    ReplyDelete
  23. OK, but your tutorial does not have us create that application, correct? [I realize I may not know what I'm talking about. :-) ]

    And thanks for the tutorial. I know that once I finally get it, I know its going to be a game changer.

    ReplyDelete
  24. @pdschuller

    No, it doesn't but I have to assume you are adding this plugin to one of your own projects.

    ReplyDelete
  25. When I add the BarcodeScanner.java file to the new package, I receive an error on the third to last line. The error reads "The method startActivity(Intent) is undefined for the type CordovaInterface"

    What do I need to do to get rid of the error and make the java file usable in my application?

    Thanks for the tutorial,

    Nick Cunningham

    ReplyDelete
  26. @Nick

    See my update on 1.9.0

    http://simonmacdonald.blogspot.ca/2012/07/phonegap-android-plugins-sometimes-we.html

    ReplyDelete
  27. Simon,
    I am a bit concerned about the mismatch between sdk target of library project (4.0) and that of the main app project (2.1).

    Since majority of android handsets are still in 2.x, do you see any potential problem compiling the barcodeScanner library targeting 4.x?

    Btw, has github repo https://github.com/phonegap/phonegap-plugins/tree/master/Android/BarcodeScanner been updated to work with cordova 1.9?

    Look forward to hearing your advice.

    Thanks,

    George

    ReplyDelete
  28. @George

    You always want to build your app agains the latest version of the Android SDK. The SDK can handle the backwards compatibility aspects. If you want to target from Android 2.1 and higher set the minimum SDK to 7 in your AndroidManifest.xml.

    ReplyDelete
  29. Hi Simon, I had a quick question.
    I use dreamweaver cs6.
    How can we use the phonegap plugins ?
    or even better how can I use the BarcodeScanner plugin ?
    Thank you

    ReplyDelete
  30. I have followed this tutorial to the end and run the application on my htc anroid phone 4.0.4. However, when I click the Scan button, nothing shows up and the application exits with error unknown.

    ReplyDelete
  31. @popman

    What do you see in "adb logcat"?

    ReplyDelete
  32. Simon,

    I have been trying to compile the Library Project for Android, so that I can use the barcode scanner in a phonegap 2.0.0 project. However, I am unable to build the CaptureActivity library because of an "R cannot be resolved to a variable" error which appears in many of the com.google.zxing.client.android classes.

    I have copied the Library Project from github. When I create a new android project from existing source, I do not have the option to rename the project to BarcodeLibrary, and it imports as com.google.zxing.client.android.CaptureActivity.

    I did get the Barcode plugin working for iOS with little difficulty, and I am having a hard time figuring out the R cannot be resolved to a variable issue.

    Thanks again for all of your hard work on this project. Any advice would be appreciated.

    ReplyDelete
  33. Simon, It turns out that the build.xml file in the libraryproject was causing the problem. I removed this file and the "R cannot be resolved as a variable error" is no longer appearing. I am rather new to Android development and again, thank you for the great phonegap plugin.

    ReplyDelete
  34. @Massimo74Rome

    Sorry, I never have and probably never will use Dreamweaver so I can't tell you how to add plugins into your project.

    ReplyDelete
  35. hey simon !
    do you have the same tutorial , but for iOS ?

    ReplyDelete
  36. @xazinn

    Sorry, I don't have a tutorial on iOS. Check out the readme at:

    https://github.com/phonegap/phonegap-plugins/tree/master/iOS/BarcodeScanner

    as most everything you need is covered. Look under compile errors for common problems.

    ReplyDelete
  37. hi simon i installed latest sdk-20 and when i create on new android project im not getting the option to workspace how cani do it latest sck post me..

    ReplyDelete
  38. @Uma Mahesh

    Right click on the project, select properties, select Android and in that right hand pane of the dialog near the bottom click the "is library" checkbox.

    ReplyDelete
  39. Hello Simon!

    I used your tutorial and I made Barcode Scanner work well, and now I want to build my app on build.phonegap.com.

    Barcode Scanner is used as a Library.
    Can my App know it?

    How can I do? Should I pack?

    I use Android now for my App and I want to run it on iPhone.


    ReplyDelete
  40. @Ambassador

    I have no idea as I've never used PhoneGap Build.

    ReplyDelete
  41. Simon,
    Great tutorial...Could you please help me on how to manage the size of the QR code if I use the app created in a TABLET.

    And on encoding the text is shown below the QR code. How to get rid of the text below QR code image.?

    ReplyDelete
  42. @Ranju Francis

    Sorry, that functionality that you want to change is part of the ZXing library project. I try not to mess with that bit.

    ReplyDelete
  43. Simon,

    Very helpful post.

    Quick question, note that BarTest project merely references the Barcode library project.

    Will BarTest.apk contains the Barcode.jar when you build BarTest and sign it and upload to Google Play Market?

    I am trying to find out what happens when user download BarTest from Google Play market and use the scan, will the user be prompted to download the Barcode library project?

    Thanks in advance.

    ReplyDelete
  44. @George

    yes the code and resources will be included in your app. you only will need to download one .ask.

    ReplyDelete
  45. Hi there,
    I am using Phonegap with WindowsPhone. i called a webservice through AJAX with Javascript. worked fine in Windows Phone after Build the PhoneGap Builder i tried in the BB,but getting object Object error. but in iOS also Working Fine only problem in BlackBerry.

    How can i will overcome this ?
    Thanks In Advance,
    Nareshrajuu

    ReplyDelete
  46. @nareshrajuu

    I'm not the BB expert but what does your code look like and what is the error? You might be better off taking this over to my Formspring account.

    ReplyDelete
  47. i get loads of errors. i have created the libproject from source and copied over the 2.0.0 barcodescanner.js, created the package com.phonegap.plugins.barcodescanner and tried to start it. Plugins.xml was missing but I found and copied it from the internet. I get all errors like Unable to resolve target 'android-12', Error in an XML file: aborting build.... and so on. The code of the libproject is really large and I don't understand what it does in detail yet. But it seems like it has to be there as all the code is related to zxing. not working for me yet. but hopefully i'll learn how to get it working. anyway thanks for the doc. it's helpful.

    ReplyDelete
  48. @Chris

    What Android SDK are you building against?

    ReplyDelete
  49. Hi sir, I am using barcode Scanner plugin for android. I want to perform scanning functionality on Button click event. For that purpose I have added a button in capture.xml with id CLOSE. here is code of xml file
    http://pastie.org/4811155

    And to implement onclick functionality I have added event handler in CaptureActivity.Java.
    What I did in java class I added handler in init function and tried to add the whole code of init method in onClick event. but application throws error
    [2012-09-27 00:43:28 - Device] Error during Sync: An existing connection was forcibly closed by the remote host.

    here is code
    http://pastie.org/4811161
    which runs perfect, but guide me how to execute myFunction() on Button Click.

    ReplyDelete
  50. I have followed this tutorial step by step, i got no errors to the end
    i got it running on my htc anroid phone 4.0.3. However, when i click scan button nothing happen and i have this line in the LogCat

    "E/Web Console(11880): Uncaught ReferenceError: cordova is not defined at file:///android_asset/www/barcodescanner.js:36"

    !!!!

    thank you so much for your efforts

    ReplyDelete
  51. hi Simon,
    thank you for this great post, i got it working nice, can you use this plugin to recognize numbers i want to use it like OCR, is it possible ?

    i'll be waiting got you feedback..

    thank you.

    ReplyDelete
  52. @Coder-007

    Glad you got it working. No the barcode scanner does not support OCR. You'd have to write a plugin to pull in OCR:

    http://dottech.org/23223/android-best-free-ocr-image-to-text-app/

    ReplyDelete
  53. Hi Simon,

    After I choose 'LibraryProject' my 'Next' button is not enabled. My eclipse version is 3.7.2 & ADT version is 20.0.3. Also I cannot change the name from CaptureActivity to BarcodeScanner.

    Can you please help me?

    ReplyDelete
  54. Hi simon, I followed your steps for the android barcode scanner and the html page showed up. But when I clicked the scan link it says "java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.androidsep30/com.google.zxing.client.android.CaptureActivity}: java.lang.ClassNotFoundException: com.google.zxing.client.android.CaptureActivity"
    I tried to figure out what went wrong by repeating the steps but the result was the same.
    Could you help me by pointing out the problem.

    ReplyDelete
  55. I just posted full example projects that you can import into Eclipse for anyone who is having problems getting this to work.

    http://simonmacdonald.blogspot.com/2012/10/barcode-scanner-example-projects.html

    ReplyDelete
  56. Hi Simon, thanks for the great tutorial. I was able to get the barcode scanner working in a phonegap, jquery Android app. When I scan a barcode with just numbers it works great! But when I scan a barcode with letters or a QR code it returns "Nan" = not a number. Am I doing something wrong? Is there a config I can set so it returns alhpa and numeric characters?

    Thanks,
    Mark

    ReplyDelete
  57. @Wallace

    No, it should work just fine. The code is setup to accept all possible barcodes including QR codes. Is there an example barcode anywhere you can point me to?

    ReplyDelete
  58. @Simon, Some of the issues being shown are because there is a step missing. See here; http://stackoverflow.com/a/12953476/820348

    ReplyDelete
  59. @Chris "Digi" Timberlake

    I believe I covered that in this post. You can see how I explained it by looking at the 3rd to 5th screen shots in this post.

    ReplyDelete
  60. Hi Simon,

    Here is a link to the problem type barcode:

    http://www.leadtools.com/help/leadtools/v175/dh/to/leadtools.topics.barcode~ba.topics.miscellaneousbarcodeinleadtools.html

    "The Code 39 symbol, also known as USD-3 and Code 3 of 9, supports alphanumeric data and is widely used"

    So, this type "USD-3" is returning "NaN" as a result. Also any QR code I have attempted returns "NaN" as well.

    As I stated earlier barcodes with only numberic characters work swimmingly well!

    Thanks,
    Mark Wallace

    ReplyDelete
  61. @Wallace

    Hey, I went to that site and I could get my Samsung Galaxy S to recognize the Code 39 barcode without any issues. As well I have no trouble with QR codes.

    Are you using the latest JS? Once upon a time there was a way to specify only recognizing certain types of barcodes.

    ReplyDelete
  62. Hi simon,
    Is it possible to make the scanner orientation to portrait?

    ReplyDelete
  63. @Jason Lin

    Probably. You'd have to dig into the Library Project code. Just changing android:screenOrientation to "portrait" won't do it as the camera view is not oriented properly.

    ReplyDelete
  64. How can I possibly download the barcode Library Project from Github???

    ReplyDelete
  65. @Louemm

    You'd have to grab it from the Download page:

    https://github.com/phonegap/phonegap-plugins/downloads

    ReplyDelete
  66. Hello Simon, Great work, I loved your article... I could make the Barcode Scanner work but the problem is when it scan something there is no alert on the screen, and when I hit back it goes back to scan something else. there is no return value... I've been searching for an answer but I couldn't find any ...
    You can find same issues here ...
    I've attached screen shots.
    Thanks again.

    Pictures:
    Scan the code
    http://uploadpic.org/v.php?img=cUXfw1FXe5

    Logcat
    http://uploadpic.org/v.php?img=3X5dsq6UeU

    When I go back two times:
    http://uploadpic.org/v.php?img=sGHazfxCtd

    ReplyDelete
  67. Hi Simon!

    Thank you for this Tutorial.

    In fact, I want to retrieve datas from "result", especially "result.text" in order to use them in another html file.

    How can I please do it?

    Thanks.

    ReplyDelete
  68. @Maher Massaabi

    The easiest thing to do would be to set a value in local storage and then read it on your new page. Something like:

    var scanCode = function() {
    window.plugins.barcodeScanner.scan(
    function(result) {
    alert("Scanned Code: " + result.text
    + ". Format: " + result.format
    + ". Cancelled: " + result.cancelled);
    localStorage.setItem("scanResult", result.text);
    }, function(error) {
    alert("Scan failed: " + error);
    });
    }

    and then in your second page do:

    var scanResult = localStorage.getItem("scanResult");

    ReplyDelete
  69. @Hamed Izadpanah

    Double check your setup. Based on that first screen shot with the 3 buttons on the bottom it doesn't appear like you are calling the right activity. Check out my example projects in a later post on this blog.

    ReplyDelete
  70. @Simon Mac Donald

    Thank you for your quick answer.

    In fact I did exactly the same. Here is my code:

    main.js:

    var scanCode = function() {
    window.plugins.barcodeScanner.scan(
    function(result) {
    alert("Scanned Code: " + result.text
    + ". Format: " + result.format
    + ". Cancelled: " + result.cancelled);
    localStorage.setItem("scanResult", result.text);
    }, function(error) {
    alert("Scan failed: " + error);
    });
    }

    consult.html:

    getResult();

    where getResult() is:


    function getResult()
    {
    var scanResult = localStorage.getItem("scanResult");
    document.write (scanResult);
    }


    After scanning the code, when I go to consult.html, the program seems to load (circle of loading)but nothing happens.

    What's wrong?

    ReplyDelete
  71. @Maher Massaabi

    Sorry, I'm not sure what the problem is. Are you saying the second page of your app never loads?

    ReplyDelete
  72. Hello Simon...
    I followed your instructions on the barcode scanner

    - I made a library
    - i made a new android project etc. with a MainActivity and called the barcode library.
    - I changed "phonegap-1.7.0.js" in "cordova-1.7.0.js" in the index html

    - now i am stuck with the rest of it.

    What should I do with index.html?? how can I make it work?
    I placed the index.html in the assets dir.
    the projects loads in the VDM with a !done but nothing happens...

    What do i forget?

    ReplyDelete
  73. @Louemm

    Try grabbing the example projects:

    http://simonmacdonald.blogspot.ca/2012/10/barcode-scanner-example-projects.html

    as that may be an easier way to get things working the first time.

    ReplyDelete
  74. Hi!

    I keep getting 'Alert Scanning failed: Class not found'. I read somewhere else you said it could be a manifest issue? https://gist.github.com/4146601

    Thanks,
    Tyler.

    ReplyDelete
  75. @Tyler Henderson

    Actually it sounds like you are missing the BarcodeScanner from the config.xml or plugins.xml.

    ReplyDelete
  76. Ah, yes, that was it. Silly me.
    Does it actually say above to add it to the config file? Or is that a given?

    ReplyDelete
  77. @Tyler Henderson

    The post mentions to add it to res/xml/plugins.xml which has been superseded by res/xml/config.xml.

    ReplyDelete
  78. Oh ok. Shows how new to this i am. I've been running both.

    After i take a 'scan' it seems to crash.
    https://gist.github.com/4150918

    Thanks,
    Tyler.

    ReplyDelete
  79. turned out to be a screen orientation issue.
    you should seriously think about a 'donate now' button :)

    ReplyDelete
  80. @Tyler Henderson

    Wait, I can get paid for this? I've considered adding a donate button but I think I'll ask one of my friends who has one on his blog to see if it is worth it.

    ReplyDelete
  81. Hi Simon, First of all thanks for the great plugin. I am currently working on a project targeting ICS devices. I tested my app using different devices (hdpi, mdpi) and encountered a crash on one of the device (ICS, 320x480, camera with no autofocus).

    This crash only happens in that particular device.. below are fraction of the error log:

    ...

    11-28 08:06:30.213 V/QualcommCameraHardware( 89): startPreviewInternal X
    11-28 08:06:30.213 I/QualcommCameraHardware( 89): getBuffersAndStartPreview : X
    11-28 08:06:30.213 V/QualcommCameraHardware( 89): startPreview X
    11-28 08:06:30.213 E/QualcommCamera( 89): Qint android::start_preview(camera_device*): X
    11-28 08:06:30.213 E/QualcommCamera( 89): Qint android::auto_focus(camera_device*): E
    11-28 08:06:30.213 V/QualcommCameraHardware( 89): autoFocus E
    11-28 08:06:30.213 E/QualcommCameraHardware( 89): Auto Focus not supported
    11-28 08:06:30.213 V/QualcommCameraHardware( 89): autoFocus X
    11-28 08:06:30.213 D/SignalClusterView( 374): mobile: VISIBLE mWifiVisible VISIBLE sig=2130837727 sig_evdo=2130837695 act=0 typ=2130837662 mIsAirplaneMode false
    11-28 08:06:30.213 D/StatusBar.NetworkController( 374): changing data overlay icon id to 2130837737
    11-28 08:06:30.223 W/CaptureActivity(30741): Unexpected error initializating camera
    11-28 08:06:30.223 W/CaptureActivity(30741): java.lang.RuntimeException: autoFocus failed
    11-28 08:06:30.223 W/CaptureActivity(30741): at android.hardware.Camera.native_autoFocus(Native Method)
    11-28 08:06:30.223 W/CaptureActivity(30741): at android.hardware.Camera.autoFocus(Camera.java:871)
    11-28 08:06:30.223 W/CaptureActivity(30741): at com.google.zxing.client.android.camera.CameraManager.requestAutoFocus(CameraManager.java:215)
    11-28 08:06:30.223 W/CaptureActivity(30741): at com.google.zxing.client.android.CaptureActivityHandler.restartPreviewAndDecode(CaptureActivityHandler.java:122)
    11-28 08:06:30.223 W/CaptureActivity(30741): at com.google.zxing.client.android.CaptureActivityHandler.(CaptureActivityHandler.java:63)
    11-28 08:06:30.223 W/CaptureActivity(30741): at com.google.zxing.client.android.CaptureActivity.initCamera(CaptureActivity.java:609)
    11-28 08:06:30.223 W/CaptureActivity(30741): at com.google.zxing.client.android.CaptureActivity.surfaceCreated(CaptureActivity.java:346)

    ...

    Could you pls kindly share your thoughts for fixing this error, since most of the users will be using that particular model of device.. Thanks

    ReplyDelete
  82. @Kang Andy

    It looks like the ZXing library relies on auto-focus. You could try modifying the library project at:

    com.google.zxing.client.android.camera.CameraManager.requestAutoFocus(CameraManager.java:215)

    and remove the call to request auto focus.

    ReplyDelete
  83. Hi Simon, thank you for the fast respond. I did what you told me, commenting the camera.autoFocusCallback on line 213 + 215. And, wow.. it works!! Now the mentioned device can use the barcode scanner. Great help, man...

    However, with no autofocus, it seems I can only scan QR codes, because barcodes (especially little ones) looks blurry.

    I wonder if there's a way to make conditional statement there, something like

    if( camera-auto-focus-exists )
    {
    make-the-auto-focus-callback
    }

    so that devices with autofocus can still use its camera autofocus feature.

    If that's not too much to ask, kindly assist me on this one.. Thanks Simon..

    ReplyDelete
  84. @Kang Andy

    Well you need to do this:

    getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_AUTOFOCUS);

    That will return a boolean true/false for you. The getPackageManger method can be called from any Activity.

    ReplyDelete
  85. Hi again Simon,

    Thanks for your suggestion, I finally made it works by changing the whole block into this:

    @SuppressLint("NewApi") // supressing warnings
    public void requestAutoFocus(Handler handler, int message) {
    if (camera != null && previewing) {
    Camera.Parameters parameters = camera.getParameters(); /* to check if camera has AF */
    List focusModes = parameters.getSupportedFocusModes(); /* */
    if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) /* if has AF then make the AFcall */
    {
    autoFocusCallback.setHandler(handler, message);
    //Log.d(TAG, "Requesting auto-focus callback");
    camera.autoFocus(autoFocusCallback);
    }
    }
    }


    However, I had to include @SuppressLint("NewApi") line because those checking logic was meant for older version of android. But it works. So I'll be using this solution for a while. Thanks again Simon

    ReplyDelete
  86. Hi Simon,

    NEED HELP!!!

    I have asked similar queries before. QR encoding and decoding are working fine as a plugin in one of the apps I have created. When QR code is generated for a text, along with the QR code the text is also displayed on the phone screen. Could somebody please help me to remove 'text' part displayed along with the QR code generated.

    regards
    Ranju

    ReplyDelete
  87. @Ranju Francis

    You would need to go into the Barcode Library project and modify com.google.zxing.client.android.encode.EncodeActivity.java. In the onResume method if you comment out:

    TextView contents = (TextView) findViewById(R.id.contents_text_view);
    contents.setText(qrCodeEncoder.getDisplayContents());

    that should probably do what you want. Note, I have not tested this. I just looked at the code.

    ReplyDelete
  88. Hi, i need to implement tis plugins to my sencha project. Did you got any example ?

    ReplyDelete
  89. @koo

    Try grabbing the example projects:

    http://simonmacdonald.blogspot.ca/2012/10/barcode-scanner-example-projects.html

    as that may be an easier way to get things working the first time.

    ReplyDelete
  90. Hello.
    Thanks for the plugin but I have a problem with it. I tried posting to google groups but it has not passed moderation for some reason, still wiating. Basically after I scan a QR code the plugin just hangs until I press back on the phone and then the onKeyDown event is called in CaptureActivity and the result is returned ot the BarcodeScanner class. The code is using the handleDecodeExternally method which is correct from what I can see. If back is not pressed the plugin just sits here:

    01-09 13:32:43.140: D/dalvikvm(23978): GC_FOR_MALLOC freed 181K, 49% free 3273K/6343K, external 600K/1110K, paused 31ms
    01-09 13:32:43.289: D/DecodeHandler(23978): Found barcode in 141 ms
    01-09 13:32:43.320: D/dalvikvm(23978): GC_FOR_MALLOC freed 219K, 48% free 3315K/6343K, external 600K/1110K, paused 34ms
    01-09 13:32:43.375: D/dalvikvm(23978): GC_FOR_MALLOC freed 0K, 47% free 3540K/6599K, external 600K/1110K, paused 33ms
    01-09 13:32:43.398: D/CaptureActivityHandler(23978): Got decode succeeded message
    01-09 13:32:44.960: D/CaptureActivityHandler(23978): Got return scan result message
    01-09 13:32:45.007: V/FlashlightManager(23978): This device does not support control of a flashlight
    01-09 13:32:46.101: D/CameraConfigurationManager(23978): Setting preview size: Point(320, 240)
    01-09 13:32:46.156: D/CameraManager(23978): Calculated framing rect: Rect(40, 0 - 280, 240)


    and on the phone there is just a red blinking horizontal line and the test place a barcode....

    I have tried setting the mode to be QR only in the BarcodeScanner class thus: intentScan.putExtra(Scan.MODE, Scan.QR_CODE_MODE);

    Anything I can set anywhere that I can get the plugin to return to my application automatically *without* hitting the back button?

    cheers


    ReplyDelete
  91. @Martin Thorpe

    Based on what I read on the google group you got your problem resolved right?

    ReplyDelete
  92. Is it currently possible to make the scanner only recognize certain barcode types?

    ReplyDelete
  93. @Dan B

    Yes, it is possible but you'd need to modify some Java code. You'd need to pass in SCAN_FORMATS to the intent that starts the barcode scanner. For instance:

    intentScan.putExtra("SCAN_FORMATS", barcodeFormats);

    The original barcode scanner code did do this:

    https://github.com/phonegap/phonegap-plugins/commit/d762dd7181e9557b0cdfc085ed57061ee6aca0e2

    ReplyDelete
  94. Thanks for everything Simon.

    I have the plugin working on ICS on Nexus 4, but it crashes on Gingerbread.

    Running PhoneGap 2.4 with the latest BarcodeScanner plugin.

    ReplyDelete
  95. @ottdev001

    What error do you see on Gingerbread in "adb logcat"?

    ReplyDelete
  96. When I look at logcat, I don't see anything meaningful. Filtered by the app name, captureactivity, phonegap...

    ReplyDelete
  97. @ottdev001

    Hard for me to debug that. I have a Gingerbread phone running 2.3.5 and it works for me.

    As an aside are you in Ottawa?

    ReplyDelete
  98. I see in the log, after the scanner starts, there is a STOPPED note. Not sure if it's related:

    02-15 10:03:11.874: V/AudioTrack(553): Underrun user: 3c00, server: 3c00, flags 0002
    02-15 10:03:11.874: V/AudioTrack(553): stop 0x487018
    02-15 10:03:11.874: V/AudioFlinger(226): stop(4102), calling thread 553
    02-15 10:03:11.874: V/AudioFlinger(226): (> STOPPED) => STOPPED (4102) on thread 0x62268


    Yup, in Ottawa! Can you email me?

    ReplyDelete
  99. @ottdev001

    Me too. I'd email you but I don't know your address mine is "my name"@gmail.com so ping me there.

    ReplyDelete
  100. Now it scans properly any barcode/QR code.Also it encodes email type,phone,text.

    My requirement is how can i scan a QR code which is having all the fields like website,email,phone etc and differentiate between those.

    I mean when i scan the code it should not show all them together.It should show them separately.(e.g; email:a@abc.com phone:12345 name: xyz )

    Also when it encodes it should encode them separately so as to get them separately when scanning.

    Is there any way to achieve it?

    ReplyDelete
  101. @Mak

    Encode the data in the JSON format so when you get the string back from the BarcodeScanner you can just do "var obj = JSON.parse(result);". Then obj will contain all the properties you want.

    ReplyDelete
  102. i have done all of the steps above. i got an error when i build the project within command line. i can easily run this project in eclipse, although i can't buid the project. i run into this error message:
    taskdef class com.android.ant.SetupTask cannot be found

    i encounter this problem as i add the library to my project.

    ReplyDelete
  103. @Elemenex

    Make sure your "local.properties" file inside framework has a sdk.dir line that points to your Android SDK.

    for instance:

    sdk.dir=/Development/android-sdk-macosx

    ReplyDelete
  104. @simon

    my local.properties file has the following line that is exactly where i located my SDK folder during bundle installation. as u can see i use linux.

    sdk.dir=/home/amin/adt-bundle-linux-x86-20130219/sdk

    ReplyDelete
  105. here is the whole error message:

    BUILD FAILED
    /home/amin/adt-bundle-linux-x86-20130219/sdk/tools/ant/build.xml:595: The following error occurred while executing this line:
    /home/amin/phonegap-plugins-master/Android/BarcodeScanner/LibraryProject/build.xml:64: taskdef class com.android.ant.SetupTask cannot be found
    using the classloader AntClassLoader[]

    ReplyDelete
  106. @Elemenex

    Well if the path to the SDK is correct try doing:

    android update project --path .

    to see if that fixes the project so it can find the ant task.

    ReplyDelete
  107. How can i rotare the barcode scanner to landascape mode to portrait mode?
    i use 2.2.0 version of the plugin

    ReplyDelete
  108. @Pozz

    You would have to mess with the library project from ZXing to do it.

    ReplyDelete
  109. Hi, I'm new to Android, so I could be doing something wrong, but I've followed the steps in the README from the project on GitHub AND I've tried following your steps above, but I can't get it to build. I get over 200 errors, all of them saying "R cannot be resolved to a variable."

    I'm using PhoneGap 2.6. Any idea what I'm doing wrong?

    ReplyDelete
  110. @Ben Wilkins

    If you are new to Android you should try starting with my sample projects which are already setup instead of trying to add the BarcodeScanner to your own project.

    The issue with the 200+ errors from the R class may be the fact you don't have the library project setup correctly or you didn't import the project properly.

    ReplyDelete
  111. i love simon.
    One tip:
    In phonegap 2.7.0
    Barcodescanner.java has errors:

    // private static final String EMAIL_TYPE = "EMAIL_TYPE";
    // private static final String PHONE_TYPE = "PHONE_TYPE";
    // private static final String SMS_TYPE = "SMS_TYPE";

    Thank you

    ReplyDelete
  112. @pinkphp

    What does it say the error is for those lines? Cause those are just constants and shouldn't ever be an error. Is it possible you are confusing errors with warnings? In eclipse I see warnings as those constants are not used in BarcodeScanner.java.

    ReplyDelete
  113. Hi.

    I have one problem that need to solve urgently.

    I made one barcode scanner app and it is using phonegap barcode scanner now.
    It works well on My iphone back face camera.
    But I have to change it to scan barcode on iphone front face camera.
    For example, when I touch scan button, then it has to open front-facing camera and check barcode.

    Can I make my app ?
    Any help will be appreciated.
    Regards

    ReplyDelete
  114. @Liu Han

    I don't usually work with the iPhone Barcode Scanner but to do what you want to do you'll need to open up the ZXing library and set it to use the front camera.

    ReplyDelete
  115. HI Simon,

    I've tried the example, all worked weel. Then i did a factory reset for my Samsung Galaxy mini and since that the app crashs

    ReplyDelete
  116. @Abir

    What do you see in "adb logcat"?

    ReplyDelete
  117. hello Simon, I'm came from Hong Kong, sorry for my bad English. I would like to ask how can i enable flashlight when the barcode scanner is running? any similar feature/setting can be found in the barcode scanner's setting? Is it "Use front light"? I saw CaptureActivity project there have been a FlashlightManager.java.
    Moreover, setting of barcode scanner. There have been a Bulk scan mode also, the description is scan and save many barcodes continously. But how? I ticked the option, but the barcode scanner still the same, scan a barcode and show the result, i don't think it is scan and save many barcodes continously. Am i misunderstand anything?
    I'm using same version phonegap barcode scanner with your Barcode scanner example project.
    Thank you :)

    ReplyDelete
  118. @Kay Law

    I honestly don't know as I've not played around with those options.

    ReplyDelete
  119. Hi Simon ,

    I followed the steps which you have mentioned in

    http://simonmacdonald.blogspot.in/2012/10/barcode-scanner-example-projects.html

    but still when i tested the app in AVD , the app shows for a sec and closes imm... any idea why its happending ?? can u pls quide me ?

    ReplyDelete
  120. @Hari

    What do you see in adb logcat when you try to start the app?

    ReplyDelete
  121. Hi, I am unable to build my phonegap app after doing all the changes as recommended in this article. Though I get a success message "com.phonegap.plugins.barcodescanner.BarcodeScanner" but the apk isnt being generated.

    Can someone help?

    Thanks

    ReplyDelete
  122. @Sunil

    What compilation errors are you getting?

    ReplyDelete