Integrating ZXing in your Android App as standalone scanner

In this tutorial i will explain how you can integrate ZXing (a barcode scanner) into your Android app as a standalone scanner. Because by default you need a 3rd party BarCode Scanner app when you integrate ZXing the default way (or something amoung those lines). But we just really want to have a QR Scanner (in this case) integrated into our own app.
Anyway, integrating it into your Android application isn’t that easy. Especially when you’re doing it for the first time. There are quite some steps you’ll have to take in order to make this work. It’s not difficult, but just a few things that must be done. Let’s start!

What we need

I kinda assume that you already have Eclipse installed with the Java/Android SDK. Otherwise, why would you be searching for something like this, right? Anyway, if you don’t have Eclipse and the Android SDK, make sure you download and install that first. The Android docs really do a nice job explaining you how to install it all. Next thing we need to do is download the ZXing library. So goto the following URL and download the latest version (in my case ZXing-2.0.zip): http://code.google.com/p/zxing/downloads/list  Once it’s downloaded extract the .zip folder. So now you should have:
    • an Android project
    • Downloaded and extracted the ZXing library
That’s all we need to get started.

Create a basic Android app

What we’re going to do next is create a simple Android application and add a button to a screen. That button will in return call the ZXing library to invoke a QR Scanner. Lets start by creating a default Android application. Open Eclipse and goto: File > New > Project… This will open the following dialog:
Select: Android > Android Application Project and hit Next. In the next screen enter a name for your Application and select the SDK versions you want to build against. I use the following settings:
Next screen will probably ask you to createLauncher Icon. Just hit next, this is not important right now. Then you should end up in a screen where you have to create an activity.
This should be like the screenshot by default, but simply make sure the checkboxCreate Activity is checked and Blank Activity is selected in the list (this is for mobile devices). Hit Next and after that hit Finish. Your project is ready. By now you should be presented with a GUI where you can drag and drop items into your application. It should look something like this:

Adding a button to our app

Ok, so we have a basic application set up. We can now add a button to our application which will later on invoke the ZXing QR reader. From the GUI window drag and drop a button somewhere on your view. Select the button on your view and switch from the Graphical Layout to activity_main.xml.(You can find those tabs near the bottom). You can change the button text there (ideally you shouldn’t hardcode the text into the button, but that’s not important right now). And also add the following code to the button:
android:onClick="scanNow"
 Next we need to open our Java file. In the top left corner of Eclipse we see our project structure. Open the src folder and then expand yourpackage. My package name iscom.example.androidtut, so yours may differ if you entered a different name. Next open the MainActivity.java file and add the following code:
public void scanNow(View view) {
Log.d("test", "button works!"); }
It probably gives you an error that it can’t find View, just let Eclipse works its magic by adding the right import for you. Also remove the unneeded imports at the top of the code. And clean your project if the errors don’t disappear (Project > Clean > Clean All Projects). By now you should be able to do a test run. Deploy your application to your phone and once the app is loaded, hit the newly created button. You should see a message in your LogCat console, like this:
Dont see the LogCat console? Goto: Windows > Show View > Other… > Android > LogCat

Integrate the ZXing library

So by now you should have your basic Android app and a button which responds to clicks. It’s now time to add the ZXing library to our project. So will be the most annoying part of the tutorial. Open the ZXing folder and navigate to: zxing-2.0 > android > res In there copy all the contents of the valuesfolder to the values folder in YOUR project.Becareful!!! by replacing existing files. Check the differences and merge them if needed. THe only conflict you’ll probably get is in strings.xml with app_name andmenu_settings. Just keep your settings and remove the duplicates that you got from zxing.
  • Next copy the contents of the drawable folder to your project. If the folder doesn’t exist, then simply create it.
  • After that copy the rawfolder to your project (also place it inside the res folder!).
  • Then copy the contents of the Layout folder to the Layouts folder of your project.
  • And finally copy the xml folder to your project.
That’s the first step. ZXing needs all those files or it won’t compile. Now let’s add the source code to the project. Go back to the ZXing folder and navigate to:zxing-2.0 > core > src In there you should see a folder called com. Copy that folder to the src folder of your project. NOTE: If you already have a COM folder in your SRC folder. Then copy the contents INSIDE the COM folder from ZXing and place that INSIDE the COM folder of your project. So that you don’t overwrite anything!! Go back to ZXing and navigate to: zxing-2.0 > android > src > com > google > zxing > client From there copy the android folder and paste it into the following directory of your project: Your project > src > com > google > zxing > client Next clean your project like you did before (in Eclipse: Project > Clean > Clean All Targets). And refresh your project. Right click in Eclipse on your src folder and hitRefresh. You should see the following. Notice that we have alot of errors, but we’ll fix those in a moment.
So all the zxing libraries should reside in a com.google.zxing package (like in the screenshot). If not, then you did something wrong :) But we have alot of errors to fix. Luckily it’s not that hard. Alot of errors are caused because some methods have the @Override annotation. Simply remove those where needed. You’ll have to do this for all the files that produce an error! That’s why this is the annoying part :) Not all errors will be gone after you removed the @override annotations. There’s one more thing we have to do in order to fix the errors. We have to specify from which package R can get the resources from. The first file that probably is still producing an error is: BeepManager.javaincom.google.zxing.client.android. So open that file and scroll down to the error. That will probably be this line: AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep); Hover your cursor aboveRand Eclipse will ask you to either:
  • Import ‘R’ (android)
  • Import ‘R’ (com.yourpackage.project)
Choose the second one, so that R is imported from your package. At the top of the code an import will be added. Add this import to all the remaining files that produce an error. Most of the time there is a duplicate import: import com.google.zxing.client.android.R; Simply replace that line with your import. After you’ve done all of that, then all errors should be gone. That means we’re almost there.

Finishing the code

And add this code to the scanNow method we made earlier:
Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0);
Below that method add the following method:
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");              Log.i("xZing", "contents: "+contents+" format: "+format);              // Handle successful scan         }         elseif(resultCode == RESULT_CANCELED)         {              // Handle cancel             Log.i("xZing", "Cancelled");         }     } }
Next open your AndroidManifest.xml and make sure you have the following:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.androidtut"     android:versionCode="1"     android:versionName="1.0">     <uses-sdk         android:minSdkVersion="8"         android:targetSdkVersion="15"/>     <uses-permissionandroid:name="android.permission.CAMERA"/>     <uses-permissionandroid:name="android.permission.INTERNET"/>     <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme">         <activity            android:name=".MainActivity"             android:label="@string/title_activity_main">             <intent-filter>                 <actionandroid:name="android.intent.action.MAIN"/>                 <categoryandroid:name="android.intent.category.LAUNCHER"/>             </intent-filter>         </activity>     </application> </manifest>
That should be it! Now deploy your app to your phone again and hit the button. A scanner should be started.