In this video it shows the steps to program your Android App to generate/ create Bar Code for any text entered in your Android App. It uses the zxing library to generate the bar code format image for the entered Text. To start, this library should be included in the dependencies of the App's build.gradle file so that the APIs of this library is available in the program/ App. It implements the below version of zxing library in this tutorial:
implementation 'com.google.zxing:core:3.2.1'
In this App it creates a very simple layout in which a user can enter any text and then on clicking a button the onclick method generates the barcode using the zxing library APIs. The barcode is displayed using a imageview widget. Actual phone's App is used to test and verify the generated barcode shown in this tutorial.
Complete source code shown in this video and the screenshot of the result in the actual phone is posted at the below webpage:
For any questions, suggestions, comments or appreciation we will be glad to hear from you at: [email protected].
Source Code:
package com.example.mybarcodegenerator;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.Image;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
public class MainActivity extends AppCompatActivity {
private EditText editText;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
imageView = findViewById(R.id.imageView);
}
public void barCodeButton(View view){
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix = multiFormatWriter.encode(editText.getText().toString(), BarcodeFormat.CODE_128, imageView.getWidth(), imageView.getHeight());
Bitmap bitmap = Bitmap.createBitmap(imageView.getWidth(), imageView.getHeight(), Bitmap.Config.RGB_565);
for (int i = 0; i LESS_THAN imageView.getWidth(); i++){
for (int j = 0; j LESS_THAN imageView.getHeight(); j++){
bitmap.setPixel(i,j,bitMatrix.get(i,j)? Color.BLACK:Color.WHITE);
}
}
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
}