Click here to Skip to main content
15,867,594 members
Articles / Mobile Apps / Android

Android: Generating an EAN13 Barcode

Rate me:
Please Sign up or sign in to vote.
4.97/5 (15 votes)
30 Oct 2012CPOL3 min read 89.3K   5.4K   57   24
Quick EAN13 barcode generation class.

Activity with barcode

Introduction

The European Article Number, or EAN, is a standard European barcode which is designed to encode the identification of a product and its manufacturer, and is a superset of the American standard, UPC. The format of the EAN13 barcode encodes a string of 12 characters followed by a 13th character which acts as the control number and is calculated through a formula based on the first 12 characters.

Nowadays, barcodes are used everywhere. If you earn a living as a programmer, sooner or later the need of support of barcodes in your applications will come up. For example, it may be a supermarket bonus system where the user is identified by barcode from his phone to get a discount, or such payment systems as Starbucks Mobile payment network. In this article, we will see how to generate EAN13 barcodes on an Android screen.

The Russian version of this article can be found at http://blog.plaincodesource.ws/2011/02/android-ean13.html.

EAN13 calculation basics

EAN13 barcode use a 12 digits product code, the thirteenth digit is a control number, which is calculated on the basis of the first 12 digits. Calculation of the control number (digits numbered from right to left) looks like this:

  • P1 = the sum of even digits
  • P2 = the sum of odd digits
  • Z = P1 + 3 * P2
  • R = the number divisible by 10 immediately superior to Z
  • Control number = R - Z

Next, let's see the EAN13 encoding system:

  • The first digit is not encoded
  • Each 6 following digits are encoded according to the first digit
  • The 6 last digits are converted by the strict rule
First digitLeft 6 digitsRight 6 digits
0LLLLLLRRRRRR
1LLGLGGRRRRRR
2LLGGLGRRRRRR
3LLGGGLRRRRRR
4LGLLGGRRRRRR
5LGGLLGRRRRRR
6LGGGLLRRRRRR
7LGLGLGRRRRRR
8LGLGGLRRRRRR
9LGGLGLRRRRRR

Encoding for the digits:

DigitL - codeG - codeR - code
0000110101001111110010
1001100101100111100110
2001001100110111101100
3011110101000011000010
4010001100111011011100
5011000101110011001110
6010111100001011010000
7011101100100011000100
8011011100010011001000
9000101100101111110100

Implementation

We have the EAN13CodeBuilder, which is a class for encoding sequences of 12 numbers into a string of text in the EAN-13 barcode, which can then be displayed on the screen using a special font in which each character is replaced by a bar code. This font contains a few special characters like $, +, !, and the sets of the 10 digits for the codes L, R, and G described above. An EAN13 barcode string must be built up in the following way: start delimiter (depends on the first digit) - left 6 symbols - middle delimiter (-) - right 6 symbols - end delimiter (!)

DigitL - codeG - codeR -codeStart delimiter
00Aa#!
11Bb$!
22Cc%!
33Dd&!
44Ee'!
55Ff(!
66Gg)!
77Hh*!
88Ii+!
99Jj,!

We only need to generate the proper string from the digits and display it with this special font.

The usage of this class is very simple. It delivers the original string into the constructor, after which the method getcode() brings the string back into EAN-13. The class' source code looks like this:

Java
/*
 * (C) 2011 Slava Archibasov
 * http://blog.plaincodesource.ws
 * 
 * This code is licensed under The Code Project Open License (CPOL) 
 * http://www.codeproject.com/info/cpol10.aspx  
 */

public class EAN13CodeBuilder {
    private String codeStringValue;
    private String generatedCode;

    public EAN13CodeBuilder(String codeString)
    {
        codeStringValue = codeString;
        parse();
    }

    public String getCode()
    {
        return generatedCode;

    }

    ////////////////////////////////////////////////////////////////
    // this method generates EAN 13 control number ans returns full 
    // string to encode
    private String getFullCode()
    {
       
       int chetVal = 0, nechetVal = 0;
       String codeToParse = codeStringValue;

       for( int index = 0;index<6;index++ )
       {
          chetVal += Integer.valueOf(codeToParse.substring(
                                     index*2+1,index*2+2)).intValue();
          nechetVal += Integer.valueOf(codeToParse.substring(
                                       index*2,index*2+1)).intValue();
       }

       chetVal *= 3;
       int controlNumber = 10 - (chetVal+nechetVal)%10;
       if( controlNumber == 10 ) controlNumber  = 0;

       codeToParse += String.valueOf(controlNumber);

       return codeToParse;

    }

    private String DigitToUpperCase( String digit)
    {
       String letters  = "ABCDEFGHIJ";
       int position = Integer.valueOf(digit).intValue();

       String retVal = letters.substring(position,position+1);

       return retVal;

    }

    private String DigitToLowerCase( String digit)
    {
       String letters  = "abcdefghij";
       int position = Integer.valueOf(digit).intValue();

       String retVal = letters.substring(position,position+1);

       return retVal;

    }
    //////////////////////////////////////////////
    // this method generates EAN 13 encoded string
    // algorithm can be found at http://en.wikipedia.org/wiki/EAN-13
    private String createEAN13Code(String rawCode)
    {
         int firstFlag = Integer.valueOf(

                rawCode.substring(0,1)

         ).intValue();

         String leftString = rawCode.substring(1,7);
         String rightString = rawCode.substring(7);

         String rightCode = "";
         String leftCode = "";

         for( int i=0;i<6;i++)
         {
           rightCode += DigitToLowerCase( rightString.substring(i,i+1) );
         }



         if( firstFlag == 0 )
         {
            leftCode = "#!"+leftString.substring(0,1)
                           +leftString.substring(1,2)
                           +leftString.substring(2,3)
                           +leftString.substring(3,4)
                           +leftString.substring(4,5)
                           +leftString.substring(5);
         }
         if( firstFlag == 1 )
         {
            
            leftCode = "$!"+leftString.substring(0,1)
                           +leftString.substring(1,2)
                           +DigitToUpperCase(leftString.substring(2,3))
                           +leftString.substring(3,4)
                           +DigitToUpperCase(leftString.substring(4,5))
                           +DigitToUpperCase(leftString.substring(5));
         }
         if( firstFlag == 2 )
         {
            leftCode = "%!"+leftString.substring(0,1)
                           +leftString.substring(1,2)
                           +DigitToUpperCase(leftString.substring(2,3))
                           +DigitToUpperCase(leftString.substring(3,4))
                           +leftString.substring(4,5)
                           +DigitToUpperCase(leftString.substring(5));
         }
         if( firstFlag == 3 )
         {
            leftCode = "&!"+leftString.substring(0,1)
                         +leftString.substring(1,2)
                         +DigitToUpperCase(leftString.substring(2,3))
                         +DigitToUpperCase(leftString.substring(3,4))
                         +DigitToUpperCase(leftString.substring(4,5))
                         +leftString.substring(5);
         }
         if( firstFlag == 4 )
         {
            leftCode = "'!"+leftString.substring(0,1)
                         +DigitToUpperCase(leftString.substring(1,2))
                         +leftString.substring(2,3)
                         +leftString.substring(3,4)
                         +DigitToUpperCase(leftString.substring(4,5))
                         +DigitToUpperCase(leftString.substring(5));
         }
         if( firstFlag == 5 )
         {
            leftCode = "(!"+leftString.substring(0,1)
                         +DigitToUpperCase(leftString.substring(1,2))
                         +DigitToUpperCase(leftString.substring(2,3))
                         +leftString.substring(3,4)
                         +leftString.substring(4,5)
                         +DigitToUpperCase(leftString.substring(5));
         }
         if( firstFlag == 6 )
         {
            leftCode = ")!"+leftString.substring(0,1)
                           +DigitToUpperCase(leftString.substring(1,2))
                           +DigitToUpperCase(leftString.substring(2,3))
                           +DigitToUpperCase(leftString.substring(3,4))
                           +leftString.substring(4,5)
                           +leftString.substring(5);
         }
         if( firstFlag == 7 )
         {
            leftCode = "*!"+leftString.substring(0,1)
                         +DigitToUpperCase(leftString.substring(1,2))
                         +leftString.substring(2,3)
                         +DigitToUpperCase(leftString.substring(3,4))
                         +leftString.substring(4,5)
                         +DigitToUpperCase(leftString.substring(5));
         }
         if( firstFlag == 8 )
         {
            leftCode = "+!"+leftString.substring(0,1)
                         +DigitToUpperCase(leftString.substring(1,2))
                         +leftString.substring(2,3)
                         +DigitToUpperCase(leftString.substring(3,4))
                         +DigitToUpperCase(leftString.substring(4,5))
                         +leftString.substring(5);
         }
         if( firstFlag == 9 )
         {
            leftCode = ",!"+leftString.substring(0,1)
                         +DigitToUpperCase(leftString.substring(1,2))
                         +DigitToUpperCase(leftString.substring(2,3))
                         +leftString.substring(3,4)
                         +DigitToUpperCase(leftString.substring(4,5))
                         +leftString.substring(5);
         }



         String retVal = leftCode + "-" + rightCode + "!";

         return retVal;
    }

    private void parse()
    {
       String fullString = getFullCode();
       System.out.println( "Full code: " + fullString );

       generatedCode = createEAN13Code(fullString);

       System.out.println( "Generated code: " + generatedCode );

    }
}

Using the code

To generate a bar code line and bring it to the Android screen, you should generate the barcode string itself and show it on the screen with one of the barcode fonts. To set the font in the TextView widget in Android, place a TTF file in the /assets project folder, load Typeface, and set this Typeface to TextView.

You can use the following code, for example:

Java
import android.app.Activity;
import android.os.Bundle;

import android.view.View;
import android.widget.TextView;
import android.graphics.Typeface;

public class AndroidEAN13Activity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        // ToDo add your GUI initialization code here

        this.setContentView(R.layout.main);
        TextView t = (TextView)findViewById(R.id.barcode);

        // set barcode font for TextView.
        // ttf file must be placed is assets/fonts 
        Typeface font = Typeface.createFromAsset(this.getAssets(), 
                        "fonts/EanP72Tt Normal.Ttf");
        t.setTypeface(font);

        // generate barcode string      
        EAN13CodeBuilder bb = new EAN13CodeBuilder("124958761310");
        t.setText(bb.getCode());
    }
}
This article was originally posted at http://blog.plaincodesource.ws/2011/02/android-ean13.html

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Russian Federation Russian Federation
Professional Windows/Java Mobile/Web-applications developer since 2000.

Comments and Discussions

 
QuestionEAN CODE size Pin
foufou8726-May-21 1:10
foufou8726-May-21 1:10 
QuestionGenerating code128 barcode Pin
Member 177352927-Feb-15 9:06
Member 177352927-Feb-15 9:06 
QuestionHow to create an EAN13 barcode generator, that gets the EAN as input? Pin
andyadams212-Feb-15 17:31
andyadams212-Feb-15 17:31 
Questionneed 8 digit barcode generator Pin
nidhin.s198430-Nov-14 20:04
nidhin.s198430-Nov-14 20:04 
Questionautosize barcode - EAN13 Pin
pavucok20-Dec-12 23:21
pavucok20-Dec-12 23:21 
QuestionHow to print EAN13 BarCode via blue tooth printer through android application Pin
vaibahv Bhujange26-Jun-12 2:22
vaibahv Bhujange26-Jun-12 2:22 
Generaladd another type of code barre with EAN13 Barcode Pin
montas16-Jan-12 3:30
montas16-Jan-12 3:30 
Hi,
Really nice Tutorial,it help-full
but when i want to add another type of code barre for example CODE128 or CODE39....
what can i change in this code please.

Thanks
GeneralRe: add another type of code barre with EAN13 Barcode Pin
va_dev19-Jan-12 1:16
va_dev19-Jan-12 1:16 
GeneralRe: add another type of code barre with EAN13 Barcode Pin
montas23-Jan-12 21:39
montas23-Jan-12 21:39 
GeneralRe: add another type of code barre with EAN13 Barcode Pin
va_dev24-Jan-12 1:11
va_dev24-Jan-12 1:11 
GeneralRe: add another type of code barre with EAN13 Barcode Pin
montas24-Jan-12 2:15
montas24-Jan-12 2:15 
GeneralRe: add another type of code barre with EAN13 Barcode Pin
montas25-Jan-12 0:07
montas25-Jan-12 0:07 
GeneralRe: add another type of code barre with EAN13 Barcode Pin
va_dev25-Jan-12 4:39
va_dev25-Jan-12 4:39 
GeneralRe: add another type of code barre with EAN13 Barcode Pin
montas25-Jan-12 4:57
montas25-Jan-12 4:57 
GeneralRe: add another type of code barre with EAN13 Barcode Pin
montas25-Jan-12 20:39
montas25-Jan-12 20:39 
SuggestionRe: add another type of code barre with EAN13 Barcode Pin
foufou8726-May-21 1:15
foufou8726-May-21 1:15 
QuestionLast digit problem, Pin
Tyler4528-Nov-11 9:19
Tyler4528-Nov-11 9:19 
AnswerRe: Last digit problem, Pin
va_dev29-Nov-11 18:38
va_dev29-Nov-11 18:38 
GeneralRe: Last digit problem, Pin
Tyler4529-Nov-11 20:56
Tyler4529-Nov-11 20:56 
GeneralRe: Last digit problem, Pin
va_dev30-Nov-11 0:22
va_dev30-Nov-11 0:22 
GeneralRe: Last digit problem, Pin
Tyler4530-Nov-11 0:28
Tyler4530-Nov-11 0:28 
GeneralCongratulations Slava! Pin
Marcelo Ricardo de Oliveira30-Apr-11 0:49
mvaMarcelo Ricardo de Oliveira30-Apr-11 0:49 
GeneralRe: Congratulations Slava! Pin
va_dev1-May-11 19:43
va_dev1-May-11 19:43 
GeneralMy vote of 5 Pin
hugevishal18-Feb-11 6:26
hugevishal18-Feb-11 6:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.