- Распознавание Barcode Android
- Создание нового проекта
- Интегрируем ZXing
- Сканируем
- Обработка результатов сканирования
- Zxing with android studio
- Generate QR Code Using Zxing Android Studio Programmatically
- Download Source Code For Generate QR Code Using Zxing Android Tutorial
- Creating generate create QR Code ZXing Android step by step
- Step 1: Create a new project in Android Studio.
- Step 2: Updating build.gradle(Module:app) file
- Step 3: Adding colors in colors.xml
- Step 4: Updating AndroidManifest.xml file
- Step 5: Updating activity_main.xml file
- Step 6: Preparing MainActivity.java class
- Step 7: Description of MainActivity.java
- 45 thoughts on “Generate QR Code Using Zxing Android Studio Programmatically”
Распознавание Barcode Android
В данной статье мы будем использовать ZXing (Zebra Crossing), чтобы расшифровать штрихкод в нашем Android приложении.
Используя ZXing, нам не нужно думать о том, что у пользователя нет сканера barcode, так как классы, предоставляемые библиотекой позаботятся об этом. Интегрируя ZXing в наше приложение мы можем предоставить пользователю более простую возможность сканировать шрихкоды, также это позволит нам сфокусироваться на разработке основной части приложения.
Создание нового проекта
Шаг 1
В Eclipse создайте новый Android проект. Введите имя приложения, проекта и название пакета.
Шаг 2
Откройте основной шаблон. Eclipse должен был создать стандартный шаблон. Внутри него замените существующий контент на кнопку
После кнопки добавим два текстовых поля, которые будут отображать результаты отсканированной информации.
Добавьте к кнопке текст. Откройте файл res/values/strings
Чтобы просканировать пользователь должен будет нажать на кнопку. Когда приложение получает результат распознавания, оно отобразит его в текстовых полях.
Интегрируем ZXing
Шаг 1
ZXing — библиотека с открытым исходным кодом, предоставляющая возможность распознавания штрихкодов на Android. Некоторые пользователи уже имеют установленное приложение ZXing, поэтому достаточно передать ему код и дождаться результатов. В данном приложении мы рассмотрим способ, вызывающий соответствующую функцию другого приложения. Если данное приложение отсутствует у пользователя, то будет выведено предложение скачать его.
В Eclipse добавим новый пакет в Ваш проект. Для этого кликнем правой кнопкой мыши по папке src и выберем «New»->«Package», а затем введем com.google.zxing.integration.android в качестве имени пакета.
Шаг 2
Eclipse предлагает несколько способов импортирования существующего кода в проект. В данной статье самым простым методом будет создание двух классов, содержащий код из ZXing. Кликните правой кнопкой мыши по Вашему проекту, выберете «New»->«Class» и введите «IntentIntegrator» в качестве названия класса. Остальные параметры Вы можете не изменять. Как только Вы создали класс, проделайте тоже самое, но назовите класс «IntentResult».
Скопируйте код из обоих классов библиотеки, а затем вставьте его в созданные классы.
Теперь Вы можете подключить файлы в основной класс
Вернемся на минутку и также подключим следующие файлы. Обратите внимание, что Eclipse мог уже их подключить за Вас
Изучите содержание двух классов. Изучив их Вы обнаружите, что они не считывают код. Эти два класса являются просто интерфейсами, предоставляющими доступ к функционалу сканирования.
Сканируем
Шаг 1
Давайте реализуем сканирование, когда пользователь нажимает на нашу кнопку. В главном файле приложения существует метод onCreate, который должен выглядеть примерно так
Перед данной функцией создайте следующие переменные, которые будут хранить нашу кнопку и два текстовых поля, созданных в шаблоне
После существующего кода в onCreate добавьте строки, которые будут инициализировать переменные
Теперь, добавим обработчик нажатия
Расширим класс, чтобы объявить интерфейс OnClickListener
Шаг 2
Теперь, мы можем реагировать на нажатие кнопки началом процесса сканирования. Добавим метод onClick
Проверяем, была ли нажата именно кнопка сканирования
Внутри блока с условием создадим экземпляр класса IntentIntegrator, который мы импортировали
Сейчас, давайте вызовем процедуру, которая начнет сканирование
В данный момент должно начаться распознавание, но только, если у пользователя установлено необходимое приложение. Если его нет, то будет предложено начать загрузку. Результат сканирования будет возвращен приложению.
Обработка результатов сканирования
Шаг 1
Сканер будет запущен, когда нажата кнопка. Затем будет возвращен результат сканирования в метод onActivityResult. Добавим его в наш код
Внутри функции постараемся обработать результат
Шаг 2
Как и любые другие данные, полученные от другого приложения, было бы не плохо проверить, что результат не пуст. Продолжим мы только, если у нас есть правильный результат
Если мы не получили результат сканирования (например, пользователь отменил сканирование), то мы просто выведем сообщение
Вернемся в блок с условием, давайте разберемся с тем, что нам вернула библиотека. Объект Intent Result имеет метод, обеспечивающий получение результата сканирования. Получим результат сканирования, как строку
Также, получим вид barcode
Шаг 3
Теперь, наше приложение имеет всю необходимую для отображения информацию. В нашей статье мы просто отобразим ее пользователю.
Запустите наше приложение на реальном устройстве вместо эмулятора, чтобы увидеть, как работает функционал распознавания штрихкодов. Попробуйте просканировать штрихкод с какой-нибудь книги или любого другого товара.
Результаты сканирования
Источник
Zxing with android studio
ZXing Android Embedded
Barcode scanning library for Android, using ZXing for decoding.
The project is loosely based on the ZXing Android Barcode Scanner application, but is not affiliated with the official ZXing project.
- Can be used via Intents (little code required).
- Can be embedded in an Activity, for advanced customization of UI and logic.
- Scanning can be performed in landscape or portrait mode.
- Camera is managed in a background thread, for fast startup time.
A sample application is available in Releases.
By default, Android SDK 24+ is required because of zxing:core 3.4.x. SDK 19+ is supported with additional configuration, see Older SDK versions.
Adding aar dependency with Gradle
Add the following to your build.gradle file:
Older SDK versions
By default, only SDK 24+ will work, even though the library specifies 19 as the minimum version.
For SDK versions 19+, one of the changes changes below are required. Some older SDK versions below 19 may work, but this is not tested or supported.
Option 1. Downgrade zxing:core to 3.3.0
Option 2: Desugaring (Advanced)
This option does not require changing library versions, but may complicate the build process.
This requires Android Gradle Plugin version 4.0.0 or later.
Example for SDK 21+:
SDK 19+ additionally requires multiDex. In addition to these gradle config changes, the Application class must also be changed. See for details: Configure your app for multidex.
Hardware acceleration is required since TextureView is used.
Make sure it is enabled in your manifest file:
Usage with ScanContract
Note: startActivityForResult is deprecated, so this example uses registerForActivityResult instead. See for details: https://developer.android.com/training/basics/intents/result
startActivityForResult can still be used via IntentIntegrator , but that is not recommended anymore.
See BarcodeOptions for more options.
Generate Barcode example
While this is not the primary purpose of this library, it does include basic support for generating some barcode types:
Changing the orientation
To change the orientation, specify the orientation in your AndroidManifest.xml and let the ManifestMerger to update the Activity’s definition.
Customization and advanced options
For more advanced options, look at the Sample Application, and browse the source code of the library.
This is considered advanced usage, and is not well-documented or supported.
The camera permission is required for barcode scanning to function. It is automatically included as part of the library. On Android 6 it is requested at runtime when the barcode scanner is first opened.
When using BarcodeView directly (instead of via IntentIntegrator / CaptureActivity), you have to request the permission manually before calling BarcodeView#resume() , otherwise the camera will fail to open.
To deploy the artifacts the your local Maven repository:
You can then use your local version by specifying in your build.gradle file:
JourneyApps — Creating business solutions with mobile apps. Fast.
Источник
Generate QR Code Using Zxing Android Studio Programmatically
Hello, geeks. Welcome to Generate QR Code Using Zxing Android Studio example tutorial.
You will learn how to generate QR code in Generate QR Code Using Zxing Android Studio example.
You can generate QR Code from any string using ZXing library.
We will also save generated QRCode to internal storage.
First check output then we will develop Generate QR Code Using Zxing Android Studio example.
Download Source Code For Generate QR Code Using Zxing Android Tutorial
Creating generate create QR Code ZXing Android step by step
Step 1: Create a new project in Android Studio.
Step 2: Updating build.gradle(Module:app) file
add following code into dependencies<>
Step 3: Adding colors in colors.xml
Move to res->values->colors.xml directory and add following
Step 4: Updating AndroidManifest.xml file
Note: If you are targeting SDK version above 22 (Above Lollipop) then you need to ask a user for granting runtime permissions. Check marshmallow runtime permission for more information.
Final code for AndroidManifest.xml file
Step 5: Updating activity_main.xml file
Copy and paste below source code in activity_main.xml file
Step 6: Preparing MainActivity.java class
Add following source code in MainActivity.java class
Step 7: Description of MainActivity.java
Following method saves the QRcode image.
IMAGE_DIRECTORY is the folder in which image is saved.
Image will be saved in the internal memory of android device.
You can change the value of IMAGE_DIRECTORY variable to customize the location to which you want to save generated QRCode image.
Below method will generate QRCode from given string.
Above method will use various classes of ZXing library to create QRCode from given string.
Implementation of a button click.
If there is no string is entered, a message is printed to enter a string.
Otherwise, QRcode is generated and saved.
So all for generate create QR code ZXing Android Studio programmatically example tutorial. Thank you.
45 thoughts on “Generate QR Code Using Zxing Android Studio Programmatically”
Your King bro, thanks 🙂
Sorry, You are King bro 🙂
Please let me know how to send a payment request to the customer for UPI payment using android
Thanks,
please consider to change the code below as it is consuming a lot of resources :
Instead of this in the loop:
for loop
getResources().getColor(R.color.black):getResources().getColor(R.color.white);
do this:
int bgColor = getResources().getColor(R.color.black);
int color = getResources().getColor(R.color.white);
for loop
bgColor:color;
sir not save in folder
pls help me
Give all required permissions if you have not given yet.
sir It not showing Qr I give all the permission
Is your app crashing? or are you able to scan barcode..
yes my app is crashing
It is very help to me. Thanks bro.
Be happy!
Hey,, i generate a QR using this one. my problem is…. how to make the generated QR pop out in my screen?
bitmap = TextToImageEncode(etqr.getText().toString());
This code is generate QR, you can used it in dialog pop up
How to add Images in the center of the QR code using this method ?
WHERE TO ADD IMAGE ? GENERATED QRCODE ITSELF IS AN IMAGE.
i have one requirement.
Ex if i am taking one image how to capture inside image value,on that value i will shows in edittext.
Please explain in details. I can not understand what you really want?
how to insert the image from qrcode into database? thank you 🙂
Do you want to upload qrcode image to server darabase or in sqlite?
getresources().getcolor() is deprecated
The Best Approach to use :
ContextCompat.getColor(context, R.color.color_name)
Thank you very much for useful attention!
How can you make a qrcode generator with multiple line texts for input? For example you may want the user to input Name, Age and Gender and you may want it to convert to a single qr code
You can do this by writing all the details in one line. For example : Vincent Van Fundal 25 Male
Where is the rest of the article? It stops at the beginning of step 4.
Thanks
It may happen for many reasons like you have ad blocker in your browser,slow internet connection or heavy load on your PC or browser etc.
If you have ad blocker then please remove it first, and delete history of your browser. and again reload the page.
P.S. : I am able to see full article on my laptop, I have checked in both chrome and mozilla.
I have run my code successfully by your method !!
Cannot solve symbol DATA_MATRIX
Help me
hi buddy, I did all project work but app doesnt create anyfile which name is QRcodeDemonuts,app generate qrcode but not save in any file pls help me? thanks
Same problem here java.io.IOException: No such file or directory
Is there any way of reading a document (pdf, doc) and then converting the resource into a QR code?
I will try to makes separate tutorial for this.
my app is crashing .i did everything alike in the tutorial but still.
How to insert multiple inputs in qr code?
I would like to know how to insert multiple inputs inside qr code like
Name
Add
Email id
You have to create single string which includes all details . For eg. hardik+hello@gmail.com+123
Hi Mr. Hardik, I’m a beginner in android studio app develop, I want to generate QR code and store it in mysql database using volley library, how I can achieve it.
Help please.
You will be able to generate QR code in image format with this tutorial itself. Now you can send this image to server and mysql using below tutorial : https://demonuts.com/android-upload-image-using-volley/
Hi this code works but It will not save the
Bitmap,java.io.IOException: No such file or directory
After some editing it finally saved my QR code, but how to add some text above the qrcode so we know the value of the qrcode on the image.
You may try this : take one linear layout. In that, take text view and set value of QR code in text view. Take image view in the same linear layout and preview QR code in it. Now take screen shot of this linear layout.
When I scan QR code it should generate URL in android studio ? Can anyone please help me out to solve this problem
Thank you. This was an enormous help to a significant activity in my project, wallet address qr code generation. I had to update the getExternalStorageDirectory method to (getApplicationContext().getExternalFilesDir(null).getAbsolutePath() + IMAGE_DIRECTORY) for the save method to work due to deprecation.
But besides that, it works wonderfully. Thank you. I just need to implement scanning/reading-in QR codes now in another activity and that is the core of my functionality sorted.
Any suggestions on source code for scanning QRs using Zxing and/or how I might upload QRs from the internal storage to read them in?
Creating a verification activity that involves scanning in or uploading a QR, which is then unencrypted into a string(crypto-wallet address) that I can use to query a database.
Источник