implementation 'com.google.zxing:core:3.4.0'
MainActivity.kt
main_activity.xml
There are lots of articles and help online for producing an Android app that can scan barcodes (including the excellent KBarcode library and sample app developed by my colleague Alistair). However, it was harder to find much information about generating and displaying barcodes programmatically. Most articles appear to include either larger libraries or complete sample apps, rather than simple instructions. I needed to create a 1D (CODE 128) barcode in an Android app and so, turned to the ZXing project for help.
ZXing is a barcode image processing library originally released in 2008 and subsequently open-sourced and now hosted on Google Open Source. It was originally implemented in Java but has since been ported to many other languages and has support for 1D product, 1D industrial, and 2D barcodes.
The ZXing project has been on GitHub for years, its first release was over 5 years ago and has had 27 releases and over 3.5k commits at the time of writing! Although the project is now in maintenance mode it is used by over 17k projects and has been forked over 8k times.
The project consists of various components including an Android Barcode Scanning app, but for this blog, we just needed the core functionality. The code examples and a step-by-step guide for creating a new Android app that displays a 1D Code 128 barcode can be found below.
a. Choose Empty Activity, click Next
b. Configure your project, click Next
c. Run the new project to ensure project setup is correct
implementation 'com.google.zxing:core:3.4.0'
a. Add a function to generate the barcode image
b. Add a helper method that sets the size of the barcode image and uses the previous function to set the actual barcode image, it also sets the text value
c. Finally, call the helper method from OnCreate. The whole MainActivity.kt should look like this
Search over 200 blog posts from our team
Subscribe to our monthly digest of blogs to stay in the loop and come with us on our journey to make things better!