Sei sulla pagina 1di 38

Tell us what you think and win prizes in the Tuts+ Annual Survey 2014.

Dismiss

All Topics Find tutorials, courses, and more...

Code Categories Learning Guides

MOBILE DEVELOPMENT

Android SDK: Create a


Barcode Reader
by Sue Smith 21 May 2013
107 Comments

106 11 41

In this tutorial, we'll use the ZXing (Zebra Crossing) library to carry out barcode
scanning within an Android app. We'll call on the resources in this open source
library within our app, retrieving and processing the returned results.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Since we're using the ZXing library, we don't need to worry about users without the
barcode scanner installed, because the integration classes provided will take care of
this for us. By importing the ZXing integration classes into our app, we can make
user scans easier and focus our development efforts on handling the scan results.
In a follow-up series coming soon, we'll develop a book scanning app where we'll
build on the app we created in this tutorial. We'll also add support for Google Books
API so that we can display information about scanned books.

1. Create a New Android Project

Step 1
In Eclipse, create a new Android project. Enter your chosen application, project, and
package names. Let Eclipse create a blank activity for you, with the name of your
choice for both the activity and its layout.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Step 2
Open your main layout file. With the default settings, Eclipse starts your layout with
a Relative Layout object, which you can leave as is. Inside of it, replace the
existing content (typically a Text View) with a button.

01 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
02 xmlns:tools="http://schemas.android.com/tools
"
03 android:layout_width="match_parent"
04 android:layout_height="match_parent" >
05 <Button android:id="@+id/scan_button"
06 android:layout_width="wrap_content"
07 android:layout_height="wrap_content"
08 android:layout_centerHorizontal="true"
09 android:text="@string/scan" />
10 </RelativeLayout>

After the button, add two Text Views in which we will output scanning information.

01 <TextView
02 android:id="@+id/scan_format"
03 android:layout_width="wrap_content"
04 android:layout_height="wrap_content"
05 android:textIsSelectable="true"
06 android:layout_centerHorizontal="true"
07 android:layout_below="@id/scan_button" />
08 <TextView
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
08 <TextView
09 android:id="@+id/scan_content"
10 android:layout_width="wrap_content"
11 android:layout_height="wrap_content"
12 android:textIsSelectable="true"
13 android:layout_centerHorizontal="true"
14 android:layout_below="@id/scan_format" />

Add the button text string to your "res/values/strings" XML file.

1 <string name="scan">Scan</string>

The user will press the button to scan. When the app receives a result from the
barcode scanning operation, it will display the scan content data and format name
in the two Text Views.

2. Add ZXing to Your Project

Step 1
ZXing is an open source library that provides access to tested and functional
barcode scanning on Android. Many users will already have the app installed on
their devices, so you can simply launch the scanning Intents and retrieve the
results. In this tutorial we are going to use the Scanning via Intent method to make

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
scanning easier. This method involves importing a couple of classes into your app
and lets ZXing take care of instances where the user does not have the scanner
installed. If the user doesn't have the barcode scanner installed, they'll be prompted
to download it.

Tip: Since ZXing is open source, you can import the source code into your projects
in its entirety. However, this is really only advisable if you need to make changes to
its functionality. You can also compile the project and include its JAR file in your
own apps if you prefer. For most purposes, using Scanning via Intent is a reliable
and easy to implement options, plus your users will have access to the most recent
version of the ZXing app.

In Eclipse, add a new package to your project by right-clicking the "src" folder and
choosing "New", then "Package", and entering
"com.google.zxing.integration.android" as the package name.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Step 2
Eclipse offers several ways to import existing code into your projects. For the
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
purposes of this tutorial, you'll probably find it easiest to simply create the two
required classes and copy the code from ZXing. Right-click your new package,
choose "New" then "Class" and enter "IntentIntegrator" as the class name. You
can leave the other default settings the way they are. Once you've created this
class, do the same for the other class we'll be importing, giving it "IntentResult" as
its class name.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Copy the code from both classes in the ZXing library and paste it into the class files
you created. These are IntentIntegrator and IntentResult. Refer to the source code
download if you're in any doubt about where the various files and folders should be
or what should be in them.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
You can now import the ZXing classes into your main Activity class.

1 import com.google.zxing.integration.android.IntentIntegrator;
2 import com.google.zxing.integration.android.IntentResult;

Go ahead and add the other import statements we'll use for this tutorial. Bear in
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
mind that Eclipse may have already added some for you.

1 import android.os.Bundle;
2 import android.app.Activity;
3 import android.content.Intent;
4 import android.view.View;
5 import android.view.View.OnClickListener;
6 import android.widget.Button;
7 import android.widget.TextView;
8 import android.widget.Toast;

Feel free to have a look at the content of the two ZXing classes. It's fairly
straightforward, but the details of the barcode scanning processing are carried out
elsewhere in the library. These two classes really act as an interface to the scanning
functionality.

3. Do Some Scanning

Step 1
Let's implement scanning when the user clicks the button we added. In your app's
main activity class, the default onCreate method entered by Eclipse should look
something like this.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
1 protected void onCreate(Bundle savedInstanceState) {
2 super.onCreate(savedInstanceState);
3 setContentView(R.layout.activity_main);
4 }

Above this method, add the following instance variables to represent the button and
two Text Views we created in the layout file.

1 private Button scanBtn;


2 private TextView formatTxt, contentTxt;

In onCreate, after the existing code, instantiate these variables using the ID values
we specified in the XML.

1 scanBtn = (Button)findViewById(R.id.scan_button);
2 formatTxt = (TextView)findViewById(R.id.scan_format);
3 contentTxt = (TextView)findViewById(R.id.scan_content);

Next, add a listener to the button so that we can handle presses.

1 scanBtn.setOnClickListener(
this);

Extend the opening line of the class declaration to implement the OnClickListener
interface.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
1 public class MainActivity extends Activity implements OnClickListener

Step 2
Now we can respond to button clicks by starting the scanning process. Add an
onClick method to your activity class.

1 public void onClick(View v){


2 //respond to clicks
3 }

Check whether the scanning button has been pressed inside this method.

1 if(v.getId()==R.id.scan_button){
2 //scan
3 }

Inside this conditional block, create an instance of the Intent Integrator class we
imported.

1 IntentIntegrator scanIntegrator =new IntentIntegrator(this);

Now we can call on the Intent Integrator method to start scanning.


open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
1 scanIntegrator.initiateScan();

At this point, the scanner will start if it's installed on the user's device. If not, they'll
be prompted to download it. The results of the scan will be returned to the main
activity where scanning was initiated, so we'll be able to retrieve it in the
onActivityResult method.

Tip: When you call the initiateScan method, you can choose to pass a collection of
the barcode types you want to scan. By default, the method will scan for all
supported types. These include UPC-A, UPC-E, EAN-8, EAN-13, QR Code, RSS-
14, RSS Expanded, Data Matrix, Aztec, PDF 417, Codabar, ITF, Codes 39, 93, and
128. The ZXing library also includes barcode scanning options that we're not going
to cover in this tutorial. You can check the project out at Google Code for more info.

4. Retrieve Scanning Results

Step 1
When the user clicks the scan button, the barcode scanner will launch. When they
scan a barcode, it will return the scanned data to the onActivityResult method of
the calling activity. Add the method to your mainactivity class.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
1 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
2 //retrieve scan result
3 }

Inside the method, try to parse the result into an instance of the ZXing Intent Result
class we imported.

1 IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, res

Step 2
As with any data being retrieved from another app, it's vital to check for null values.
Only proceed if we have a valid result.

1 if (scanningResult != null) {
2 //we have a result
3 }

If scan data is not received (for example, if the user cancels the scan by pressing
the back button), we can simply output a message.

1 else{
2 Toast toast = Toast.makeText(getApplicationContext(),
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
2 Toast toast = Toast.makeText(getApplicationContext(),
3 "No scan data received!"
, Toast.LENGTH_SHORT);
4 toast.show();
5 }

Back in the if block, let's find out what data the scan returned. TheIntent Result
object provides methods to retrieve the content of the scan and the format of the
data returned from it. Retrieve the content as a string value.

1 String scanContent = scanningResult.getContents();

Retrieve the format name, also as a string.

1 String scanFormat = scanningResult.getFormatName();

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Rent Barcode
Scanners
Huge Inventory & Best Brands
Weekly or Monthly at Great
Prices!

Advertisement

Step 3
Now your program has the format and content of the scanned data, so you can do
whatever you want with it. For the purpose of this tutorial, we'll just write the values
to the Text Views in our layout.

1 formatTxt.setText(
"FORMAT: " + scanFormat);
2 contentTxt.setText("CONTENT: " + scanContent);

Run your app on a device instead of an emulator so that you can see the scan
functioning. Try scanning a book or any other barcode you might have.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
When the scan is initiated, the user is taken to the ZXing app to scan a barcode.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
The scan results are returned to the app.

Conclusion
In this tutorial, we've run through the process of facilitating barcode scanning within
Android apps using the ZXing library. In your own apps, you might want to carry out
further processing on the retrieved scan results, such as loading URLs or looking
the data up in a third party data source. In the follow-up to this tutorial, we'll use the
barcode scanning functionality to create a book scanning app that will allow us to
retrieve data about scanned books from the Google Books API.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Advertisement

Difficulty: Suggested Tuts+ Course


Intermediate
Length:
Medium
Categories:

Mobile Development Android SDK

Eclipse Java IDEs

Translations Available:

Tuts+ tutorials are translated by our community Android for the Busy Developer Free

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
members. If you'd like to translate this post into
another language, let us know!

Related Tutorials
Download Attachment
Use Text-to-Speech on Android to
Read Out Incoming Messages
Code

About Sue Smith


Create a Weather App on Android
I'm a technical writer and sometimes
Code
developer, based in the UK. Producing
educational material and documentation, I
cover mobile, Web and software development
topics.
Google Play Game Services:
Leaderboards
Code

Jobs

WordPress Developer
at WebDevStudios in Los Angeles, CA,
USA

Front-End WordPress Designer


at WebDevStudios in Los Angeles, CA,
USA
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Advertisement
USA

Envato Market Item

Featured Comment

Stephanie Dyhin Mod 2 months ago


Hi everyone,
Please note that this is an intermediate level tutorial. If you're stuck, please check out this tutorial which
more background: Learn Android SDK from Scratch
2 Share

107 Comments Mobiletuts+


open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Sort by Best

Join the discussion

teja a year ago


It asking bar-code scanner download from market. How could I avoid it? please help me.
37 Reply Share

HC > teja 6 months ago


Did you ever find a solution?
2 Reply Share

Joshua > teja 5 months ago


You cant avoid it -.- this is for people who never download the barcode scanner application. This z
barcode application is essential for you to scan
Reply Share

teja > Joshua 5 months ago


I didn't solved it. But i find the solution with alternative SDK i.e ZBAR.
https://github.com/DushyanthMa...
Reply Share

Wasim Abbas > teja 20 days ago


open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
author of ZBAR have skipped maintenance 2 years ago, so we are stuck with ZXing
of both Library is same.
Reply Share

Yann Cailler a year ago


Thank you man, your tuto is perfect. I just have few errors. Sorry I'm new in the Android developer world. C
help me? You wil find attached a copy of my screen


29 Reply Share

Izak > Yann Cailler a year ago


You probably already solved the problem, but if anyone else have this problem, just go to activity_m
and save it. That should solve this problem.
5 Reply Share

Sue > Yann Cailler a year ago


Looks like you haven't implemented the layout correctly - see part 1 step 2. This is an intermediate
it might be an idea to try more basic tutorials and get yourself acquainted with the fundamentals of
development first.
1 Reply Share

e5b > Sue a year ago


Delete the main.xml file from menu, you don't need it and it's causing the error
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
2 Reply Share

Blackbunnz > Sue a year ago


Sue is right, you have to check part 1 step 2, actually i have this problem too, u have to ma
and text view in Graphical Layout (drag & drop), if u just type that code in activity_main.xml
error in main_activity.java, because it's not declared.
Reply Share

Nox a year ago


My Code:

package com.example.barcodescanningapp;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import com.google.zxing.integration.android.IntentIntegrator;

import com.google.zxing.integration.android.IntentResult;

import android.os.Bundle;

import android.app.Activity;

import android.content.Intent;

import android.view.View;
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
see more

12 Reply Share

Amit a year ago


Hey Thank you for such a great tut but i want one additional feature like it should redirect to the link that is
so what should i do? please help me.
11 Reply Share

Vishnu Priyan Brc 10 months ago


Hi , As per your tutorial Everything works fine :/ But when i press the scann button it installs the app ,, then
press scan.... iam moving to scan and after the completion of the scan ....no result is Displayed in the App
Me , Wher i am going Wrong ?
10 Reply Share

Tom a year ago


Hello,

I seem to have done everything correctly however i am getting an error that "The constructor
IntentIntegrator(MainActivity) is undefined".

Can anyone please take a look and tell me what seems to be the problem here. Thanks a ton.


10 Reply Share

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Exalia > Tom a year ago
I also have this issue
8 Reply Share

Eugene Kiver > Tom 7 months ago


Downoad latest source files https://github.com/zxing/zxing... i think 3.0.0 worked for me, maybe 3.
Reply Share

Syam a year ago


Hi there sir...i'm really glad that i found this post but i'm a little bit curious. could you teach me how to imple
above coding so that i can retrieve the info from a database located in my localhost after a scan activity ha
performed..thanks sir.. :D
4 Reply Share

richard 8 months ago


scanBtn.setOnClickListener(this); is causing Unfortunately has stopped on device ... any ideas?
3 Reply Share

tt > richard 7 months ago


i having the same prob. any idea? have you solve it?
1 Reply Share

Ben > tt 7 months ago


Make sure the layout file you're using is activity_pagename and not fragment_pagename.
Reply Share

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
John a year ago
Hi. Can you tell me how to make autoinstall BarcodeScanner? Do I need to add some jar files?
3 Reply Share

Stephanie Dyhin Mod 2 months ago


Featured by Mobiletuts+
Hi everyone,
Please note that this is an intermediate level tutorial. If you're stuck, please check out this tutorial which
more background: Learn Android SDK from Scratch
2 Reply Share

Karol Olszewski > Stephanie Dyhin 11 days ago


Stupid answer
Reply Share

robo 5 months ago


a shame, this nice tutorial does not get updated. With ADT Build: v22.6.2-1085508 :

1. minimum required api must be 11 (latest version of ZXing needs at least Android 3.0)

2. theme must be set to "none", otherwise "implements OnClickListener" will not work

3. source code for the two zxing classes can be found here: https://github.com/zxing/zxing...

4. Do not add the init stuff in OnCreate but add @Override protected void onStart() { super.onStart(); xxx;
thanks to darignac below in these comments
2 Reply Share

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Maheera Jazi a year ago
Really thanks! it was very helpful in my app! But please how can I include "Industrial 2 of 5 bar-code" I not
does not read it!? any help really will be appreciated
2 Reply Share

Matt 2 years ago


Thanks for great tutorial. will you post a tutoring using xzing class instead of intent?
2 Reply Share

Abhilash > Matt 2 years ago


for using zxing class
http://phpmyweb.net/2012/07/18...
1 Reply Share

Aldren de guzman 5 months ago


Thank You so much this code samples are very helpful to me
1 Reply Share

vikas k c 9 months ago


its asking to download an barcode scanner app.
my app shouldnt ask me to install other app.
how can i do this.
someone pls help me its urgent :(
1 Reply Share

Vishnu Priyan Brc 10 months ago

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
This is Without Using Zxing .....But cordova Library :) 100% Working for me http://simonmacdonald.blogsp
1 Reply Share

Omar Al-Lahham a year ago


awesome !!
thnx !
1 Reply Share

Matt 2 years ago


Create Android barcode generator,
http://www.keepautomation.com/...
1 Reply Share

Wasim Abbas 20 days ago


Just want to say only two words,
The Great :)
After hard work of 24 hours and fail and fail, i found this tutorial to figure out QR Scanner. It works great.

Question: How i can do it without barcodescanner app?


Reply Share

herman sadi 20 days ago


Hi ...
how to integrated with php mysql ..
Reply Share

Nuwan a month ago


Thanks for the GR8 tutorial
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Reply Share

Ranjith a month ago


Thanks, It was very useful..
Reply Share

lion a month ago


how we can also get the price of product from this ??anyone plzz help me
Reply Share

Volkan Kahyaolu 2 months ago


very good piece of code mate. thank you.
Reply Share

Steve 2 months ago


This is a great tutorial. It had me going in less than an hour. Thanks
Reply Share

Niels Saavedra Tapia 3 months ago


excelent Sue Smith, very good tutorial! thank you very much!
Reply Share

Andre 4 months ago


Great tutorial, thank you. Worked at first attempt and is really simple
Reply Share

Jigar 4 months ago

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Gr8 article on how to go about scanning QRCode with proper explanations.
Thanks!!!
Reply Share

Yoanna Sumarto Putri 4 months ago


sorry want to ask

If the results of these scanners will be saved to mysql how to do?

please help me :(
Reply Share

Yoanna Sumarto Putri 5 months ago


please help me


Reply Share

Yoanna Sumarto Putri 5 months ago


I have this issue.
could some one help me to solve it?
:(

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Reply Share

MisterT > Yoanna Sumarto Putri 2 months ago


I have the same problem!!!!!!! anyone!!!
Reply Share

hC > Yoanna Sumarto Putri 5 months ago


hey did you figure out how to fix the first error? thankks.
Reply Share

Yoanna Sumarto Putri > hC 5 months ago


so, the solution?

I do not understand :')


please help me :)
Reply Share

Chm Ma > Yoanna Sumarto Putri 4 months ago


Pls! Paste code for class IntentResult.java.
It will fix this problem for you.
Reply Share

Yoanna Sumarto Putri > Chm Ma 4 months ago


sorry want to ask

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
If the results of these scanners will be saved to mysql how to do?

please help me :(
Reply Share

Load more comments

Subscribe d Add Disqus to your site Privacy

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Application
Platforms
Integration, Application & Data
Server in 1 Solution. Free
Video.

Advertisement

18,724 Tutorials 447 Video Courses


Teaching skills to millions worldwide.

Follow Us Email Newsletters

Get Tuts+ updates, news, surveys &


offers.

Email Address
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Help and Support Email Address

FAQ
Subscribe
Terms of Use
Contact Support Privacy Policy
About Tuts+
Advertise
Teach at Tuts+

Custom digital services like logo design, WordPress installation, video


production and more.
Check out Envato Studio

Add more features to your website such as user profiles, payment


gateways, image galleries and more.
Browse WordPress Plugins

2014 Envato Pty Ltd. Trademarks and brands are the property of their respective
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
owners.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com

Potrebbero piacerti anche