I was having some problem when trying to generate QR code in Android Programming. Here is the Tutorial I followed. When my generate button on click, I am calling this method
Here is how you can generate an image with QR code from a string -
First add the following line to build.gradle file in your Android Studio project:
dependencies {
....
compile 'com.google.zxing:core:3.2.1'
}
Or if still using Eclipse with ADT-plugin add ZXing's core.jar from Maven repository to the libs subdir of your Eclipse ADT project (here fullscreen):
And then use the sample code from my MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = (ImageView) findViewById(R.id.qrCode);
try {
Bitmap bitmap = encodeAsBitmap(STR);
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
Bitmap encodeAsBitmap(String str) throws WriterException {
BitMatrix result;
try {
result = new MultiFormatWriter().encode(str,
BarcodeFormat.QR_CODE, WIDTH, WIDTH, null);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int w = result.getWidth();
int h = result.getHeight();
int[] pixels = new int[w * h];
for (int y = 0; y < h; y++) {
int offset = y * w;
for (int x = 0; x < w; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, w, h);
return bitmap;
}