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:

star said...

i need this for iPhone, any idea?

star said...

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

thank you

Simon Mac Donald said...

Yup, and the BlackBerry one is here:

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

jenishdonald said...

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

freshstock said...

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

thanks

Simon Mac Donald said...

@freshstock

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

gvd said...

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

Simon Mac Donald said...

@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

Nick S said...

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

Simon Mac Donald said...

@Nick

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

Unknown said...

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.

Nick S said...

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

Nick S said...

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!

Simon Mac Donald said...

@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.

Simon Mac Donald said...

@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.

Vaibhav said...

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 .

eskim0 said...

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!

Simon MacDonald said...

@eskim0

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

Catarina Almeida said...

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

Nick S said...

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

pdschuller said...

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.

Simon MacDonald said...

@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.

pdschuller said...

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.

Simon MacDonald said...

@pdschuller

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

Nick said...

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

Simon MacDonald said...

@Nick

See my update on 1.9.0

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

George said...

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

Simon MacDonald said...

@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.

Massimo74Rome said...

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

popman said...

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.

Simon MacDonald said...

@popman

What do you see in "adb logcat"?

Brian Kalbster said...

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.

Brian Kalbster said...

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.

Simon MacDonald said...

@Massimo74Rome

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

xazinn said...

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

Simon MacDonald said...

@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.

Uma Mahesh said...

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..

Simon MacDonald said...

@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.

Ambassador said...

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.


Simon MacDonald said...

@Ambassador

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

Ranju Francis said...

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.?

Simon MacDonald said...

@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.

George said...

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.

Simon MacDonald said...

@George

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

nareshrajuu said...

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

Simon MacDonald said...

@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.

Chris said...

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.

Simon MacDonald said...

@Chris

What Android SDK are you building against?

ayesha said...

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.

Coder-007 said...

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

Coder-007 said...

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.

Simon MacDonald said...

@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/

guru said...

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?

jack tizew said...

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.

Simon MacDonald said...

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

Wallace said...

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

Simon MacDonald said...

@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?

Chris "Digi" Timberlake said...

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

Simon MacDonald said...

@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.

Wallace said...

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

Simon MacDonald said...

@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.

Jason Lin said...

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

Simon MacDonald said...

@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.

Louemm said...

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

Simon MacDonald said...

@Louemm

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

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

Hamed Izadpanah said...

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

Maher Massaabi said...

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.

Simon MacDonald said...

@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");

Simon MacDonald said...

@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.

Maher Massaabi said...

@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?

Simon MacDonald said...

@Maher Massaabi

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

Louemm said...

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?

Simon MacDonald said...

@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.

Tyler Henderson said...

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.

Simon MacDonald said...

@Tyler Henderson

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

Tyler Henderson said...

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

Simon MacDonald said...

@Tyler Henderson

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

Tyler Henderson said...

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.

Tyler Henderson said...

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

Simon MacDonald said...

@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.

Kang Andy said...

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

Simon MacDonald said...

@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.

Kang Andy said...

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..

Simon MacDonald said...

@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.

Kang Andy said...

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

Ranju Francis said...

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

Simon MacDonald said...

@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.

koo said...

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

Simon MacDonald said...

@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.

Martin Thorpe said...

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


Simon MacDonald said...

@Martin Thorpe

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

Dan B said...

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

Simon MacDonald said...

@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

ottdev001 said...

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.

Simon MacDonald said...

@ottdev001

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

ottdev001 said...

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

Simon MacDonald said...

@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?

ottdev001 said...

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?

Simon MacDonald said...

@ottdev001

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

Mak said...

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?

Simon MacDonald said...

@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.

Elemenex said...

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.

Simon MacDonald said...

@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

Elemenex said...

@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

Elemenex said...

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[]

Simon MacDonald said...

@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.

Pozz said...

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

Simon MacDonald said...

@Pozz

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

Ben Wilkins said...

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?

Simon MacDonald said...

@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.

pinkphp said...

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

Simon MacDonald said...

@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.

Liu Han said...

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

Simon MacDonald said...

@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.

Abir said...

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

Simon MacDonald said...

@Abir

What do you see in "adb logcat"?

Kay Law said...

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 :)

Simon MacDonald said...

@Kay Law

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

Hari said...

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 ?

Simon MacDonald said...

@Hari

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

Sunil said...

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

Simon MacDonald said...

@Sunil

What compilation errors are you getting?