How to Generate a Qr Code for an Android Application

How to generate a QR Code for an Android application?

Have you looked into ZXING?
I've been using it successfully to create barcodes.
You can see a full working example in the bitcoin application src

// this is a small sample use of the QRCodeEncoder class from zxing
try {
// generate a 150x150 QR code
Bitmap bm = encodeAsBitmap(barcode_content, BarcodeFormat.QR_CODE, 150, 150);

if(bm != null) {
image_view.setImageBitmap(bm);
}
} catch (WriterException e) { //eek }

Android - QR generator API

QR code generation using ZXing

Add the following ZXing core dependency in your app level build.gradle file.

implementation 'com.google.zxing:core:3.4.0'

Sample code to generate a 512x512 px WiFi QR code. You can set the resultant Bitmap in an ImageView.

fun getQrCodeBitmap(ssid: String, password: String): Bitmap {
val size = 512 //pixels
val qrCodeContent = "WIFI:S:$ssid;T:WPA;P:$password;;"
val hints = hashMapOf<EncodeHintType, Int>().also { it[EncodeHintType.MARGIN] = 1 } // Make the QR code buffer border narrower
val bits = QRCodeWriter().encode(qrCodeContent, BarcodeFormat.QR_CODE, size, size)
return Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565).also {
for (x in 0 until size) {
for (y in 0 until size) {
it.setPixel(x, y, if (bits[x, y]) Color.BLACK else Color.WHITE)
}
}
}
}

To generate other types of QR code such as SMS, VCard etc. you can check out this helpful ZXing Wiki.

Scanning QR code using Google Mobile Vision API

Add the following GMS dependency to your app level build.gradle.

implementation 'com.google.android.gms:play-services-vision:20.1.2'

Step 1: Setup the Barcode processor callback.

private val processor = object : Detector.Processor<Barcode> {

override fun receiveDetections(detections: Detector.Detections<Barcode>?) {
detections?.apply {
if (detectedItems.isNotEmpty()) {
val qr = detectedItems.valueAt(0)
// Parses the WiFi format for you and gives the field values directly
// Similarly you can do qr.sms for SMS QR code etc.
qr.wifi?.let {
Log.d(TAG, "SSID: ${it.ssid}, Password: ${it.password}")
}
}
}
}

override fun release() {}
}

Step 2: Setup the BardcodeDetector with the barcode processor callback and add it to the CameraSource as follows. Don't forget to check for Manifest.permission.CAMERA at runtime and add the same to your AndroidManifest.xml.

private fun setupCameraView() {
if (ContextCompat.checkSelfPermission(requireContext(), android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
BarcodeDetector.Builder(requireContext()).setBarcodeFormats(QR_CODE).build().apply {
setProcessor(processor)
if (!isOperational) {
Log.d(TAG, "Native QR detector dependencies not available!")
return
}
cameraSource = CameraSource.Builder(requireContext(), this).setAutoFocusEnabled(true)
.setFacing(CameraSource.CAMERA_FACING_BACK).build()
}
} else {
// Request camers permission from user
// Add <uses-permission android:name="android.permission.CAMERA" /> to AndroidManifest.xml
}
}

Step 3: Add a SurfaceView to your layout to host your CameraSource.

<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Step 4: Create a callback to start and stop the CameraSource when the surface is created / destroyed.

private val callback = object : SurfaceHolder.Callback {

override fun surfaceCreated(holder: SurfaceHolder) {
// Ideally, you should check the condition somewhere
// before inflating the layout which contains the SurfaceView
if (isPlayServicesAvailable(requireActivity()))
cameraSource?.start(holder)
}

override fun surfaceDestroyed(holder: SurfaceHolder) {
cameraSource?.stop()
}

override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { }
}

// Helper method to check if Google Play Services are up to-date on the phone
fun isPlayServicesAvailable(activity: Activity): Boolean {
val code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(applicationContext)
if (code != ConnectionResult.SUCCESS) {
GoogleApiAvailability.getInstance().getErrorDialog(activity, code, code).show()
return false
}
return true
}

Step 5: Link everything together with the lifecycle methods.

// Create camera source and attach surface view callback to surface holder
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_camera_sheet, container, false).also {
setupCamera()
it.surfaceView.holder.addCallback(callback)
}
}

// Free up camera source resources
override fun onDestroy() {
super.onDestroy()
cameraSource?.release()
}

How to create and show Qr Code in Android App

first you will need to add zing2.1.jar file in your project then do the below code

QRCodeEncoder.java

public final class QRCodeEncoder {
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;

private int dimension = Integer.MIN_VALUE;
private String contents = null;
private String displayContents = null;
private String title = null;
private BarcodeFormat format = null;
private boolean encoded = false;

public QRCodeEncoder(String data, Bundle bundle, String type, String format, int dimension) {
this.dimension = dimension;
encoded = encodeContents(data, bundle, type, format);
}

public String getContents() {
return contents;
}

public String getDisplayContents() {
return displayContents;
}

public String getTitle() {
return title;
}

private boolean encodeContents(String data, Bundle bundle, String type, String formatString) {
// Default to QR_CODE if no format given.
format = null;
if (formatString != null) {
try {
format = BarcodeFormat.valueOf(formatString);
} catch (IllegalArgumentException iae) {
// Ignore it then
}
}
if (format == null || format == BarcodeFormat.QR_CODE) {
this.format = BarcodeFormat.QR_CODE;
encodeQRCodeContents(data, bundle, type);
} else if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
return contents != null && contents.length() > 0;
}

private void encodeQRCodeContents(String data, Bundle bundle, String type) {
if (type.equals(Contents.Type.TEXT)) {
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
} else if (type.equals(Contents.Type.EMAIL)) {
data = trim(data);
if (data != null) {
contents = "mailto:" + data;
displayContents = data;
title = "E-Mail";
}
} else if (type.equals(Contents.Type.PHONE)) {
data = trim(data);
if (data != null) {
contents = "tel:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "Phone";
}
} else if (type.equals(Contents.Type.SMS)) {
data = trim(data);
if (data != null) {
contents = "sms:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "SMS";
}
} else if (type.equals(Contents.Type.CONTACT)) {
if (bundle != null) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);

newContents.append("MECARD:");

String name = trim(bundle.getString(ContactsContract.Intents.Insert.NAME));
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}

String address = trim(bundle.getString(ContactsContract.Intents.Insert.POSTAL));
if (address != null) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}

Collection<String> uniquePhones = new HashSet<String>(Contents.PHONE_KEYS.length);
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
if (phone != null) {
uniquePhones.add(phone);
}
}
for (String phone : uniquePhones) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}

Collection<String> uniqueEmails = new HashSet<String>(Contents.EMAIL_KEYS.length);
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
if (email != null) {
uniqueEmails.add(email);
}
}
for (String email : uniqueEmails) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}

String url = trim(bundle.getString(Contents.URL_KEY));
if (url != null) {
// escapeMECARD(url) -> wrong escape e.g. http\://zxing.google.com
newContents.append("URL:").append(url).append(';');
newDisplayContents.append('\n').append(url);
}

String note = trim(bundle.getString(Contents.NOTE_KEY));
if (note != null) {
newContents.append("NOTE:").append(escapeMECARD(note)).append(';');
newDisplayContents.append('\n').append(note);
}

// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = "Contact";
} else {
contents = null;
displayContents = null;
}

}
} else if (type.equals(Contents.Type.LOCATION)) {
if (bundle != null) {
// These must use Bundle.getFloat(), not getDouble(), it's part of the API.
float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
contents = "geo:" + latitude + ',' + longitude;
displayContents = latitude + "," + longitude;
title = "Location";
}
}
}
}

public Bitmap encodeAsBitmap() throws WriterException {
if (!encoded) return null;

Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result = writer.encode(contents, format, dimension, dimension, hints);
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}

Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}

private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) { return "UTF-8"; }
}
return null;
}

private static String trim(String s) {
if (s == null) { return null; }
String result = s.trim();
return result.length() == 0 ? null : result;
}

private static String escapeMECARD(String input) {
if (input == null || (input.indexOf(':') < 0 && input.indexOf(';') < 0)) { return input; }
int length = input.length();
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == ':' || c == ';') {
result.append('\\');
}
result.append(c);
}
return result.toString();
}
}

Contents.java

import android.provider.ContactsContract;

public final class Contents {
private Contents() {
}

public static final class Type {

// Plain text. Use Intent.putExtra(DATA, string). This can be used for URLs too, but string
// must include "http://" or "https://".
public static final String TEXT = "TEXT_TYPE";

// An email type. Use Intent.putExtra(DATA, string) where string is the email address.
public static final String EMAIL = "EMAIL_TYPE";

// Use Intent.putExtra(DATA, string) where string is the phone number to call.
public static final String PHONE = "PHONE_TYPE";

// An SMS type. Use Intent.putExtra(DATA, string) where string is the number to SMS.
public static final String SMS = "SMS_TYPE";

// A contact. Send a request to encode it as follows:
// <p/>
// import android.provider.Contacts;
// <p/>
// Intent intent = new Intent(Intents.Encode.ACTION); intent.putExtra(Intents.Encode.TYPE,
// CONTACT); Bundle bundle = new Bundle(); bundle.putString(Contacts.Intents.Insert.NAME,
// "Jenny"); bundle.putString(Contacts.Intents.Insert.PHONE, "8675309");
// bundle.putString(Contacts.Intents.Insert.EMAIL, "jenny@the80s.com");
// bundle.putString(Contacts.Intents.Insert.POSTAL, "123 Fake St. San Francisco, CA 94102");
// intent.putExtra(Intents.Encode.DATA, bundle);

public static final String CONTACT = "CONTACT_TYPE";

// A geographic location. Use as follows:
// Bundle bundle = new Bundle();
// bundle.putFloat("LAT", latitude);
// bundle.putFloat("LONG", longitude);
// intent.putExtra(Intents.Encode.DATA, bundle);

public static final String LOCATION = "LOCATION_TYPE";

private Type() {
}
}

public static final String URL_KEY = "URL_KEY";

public static final String NOTE_KEY = "NOTE_KEY";

// When using Type.CONTACT, these arrays provide the keys for adding or retrieving multiple
// phone numbers and addresses.
public static final String[] PHONE_KEYS = {
ContactsContract.Intents.Insert.PHONE, ContactsContract.Intents.Insert.SECONDARY_PHONE,
ContactsContract.Intents.Insert.TERTIARY_PHONE
};

public static final String[] PHONE_TYPE_KEYS = {
ContactsContract.Intents.Insert.PHONE_TYPE,
ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE,
ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE
};

public static final String[] EMAIL_KEYS = {
ContactsContract.Intents.Insert.EMAIL, ContactsContract.Intents.Insert.SECONDARY_EMAIL,
ContactsContract.Intents.Insert.TERTIARY_EMAIL
};

public static final String[] EMAIL_TYPE_KEYS = {
ContactsContract.Intents.Insert.EMAIL_TYPE,
ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE,
ContactsContract.Intents.Insert.TERTIARY_EMAIL_TYPE
};
}

Do the below code to add string and set it to ImageView

String qrData = "Name : "+name+"\n Company : "+comp;
int qrCodeDimention = 500;

QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null,
Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimention);

try {
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}

How to generate a QR to an android app that I uploaded into google play

  1. Copy the playstore-url of your application

    e.g.: https://play.google.com/store/apps/details?id=com.springpad

  2. Open a QR-Generator ( there many on the web )

    e.g.: http://goqr.me/

  3. Enter your apps playstore-url and generate the code with 1 more click!

Generate a QR Code in an Android Application

I created an application at one point that needed to be able to generate a QR also.

I, like you started with trying to use ZXing to do it. The project is definitely capable of generating the QR image, but I was never able to get it working correctly.

The only integration they offer for QR generating is thru intents, and it just spits your QR into its own blank Activity.

I tried pulling out enough of the project that I'd be able to use the generator classes, but I could never get it working properly.

In the end I decided to go with the google charts api. Since it requires network it wasn't an ideal solution for me, but it was far easier / less complicated, and I was able to actually get it to work.

Edit:

Since the time of this post I have created a sample project that demonstrates how to download and show QR codes using the Google Image Charts API. The sample project can be located here: https://github.com/FoamyGuy/QRMaker. I hope it can help someone.

QR Code generated by libraries are not readable by QR Scanners - looking for reliable way to generate QR code

Instead of Using QRGen , you can directly use the Zxing library in your android application , and use this code which is shown below to generate the QRcode

 QRCodeWriter writer = new QRCodeWriter();
try {
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 512, 512);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
bmp.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
}
}
((ImageView) findViewById(R.id.img_result_qr)).setImageBitmap(bmp);

} catch (WriterException e) {
e.printStackTrace();
}

to Add the Zxing library to your project, you can paste this into your gradle dependency file

repositories {
jcenter()
}

dependencies {
implementation 'com.google.zxing:core:3.3.0'
}


Related Topics



Leave a reply



Submit