Generate Barcode And QR Code In Xamarin Android

In this article, we will discuss how to generate 1D and 2D Barcode in Xamarin Android application.

 Introduction

 
Here, the basic requirement is to generate the Barcode or QR Code. We need to get some information from the user like what message they want to convert, code format, size of the bitmap, etc. There is no default library for this so, we need to install a plugin. Just write a few lines of code to generate 1D and 2D Code. The Barcode has different formats but I will demonstrate only a few code formats - Code 39, Code 128, AZTEC, and QR Code.
 

Android Output


Generate Barcode And QR Code In Xamarin Android
 
Let’s start.
 
Step 1

Create a Xamarin.Android application by going to Visual Studio >> New Project >> Android App. Click "Next".
 
Generate Barcode And QR Code In Xamarin Android
 
Here, let us give a project name, organization name, app compatibility, and app theme, then click "Create".
 
Generate Barcode And QR Code In Xamarin Android
 
Step 2
 
After project creation, first, we need to install a plugin. For this, go to Solution Explorer >> right-click Packages and select "Add packages". A new window will appear; at the top-right, search for ZXing.Net plugin and add this package.
 
Generate Barcode And QR Code In Xamarin Android
 
Step 3
 
Now, let’s code. First, open content_main.xml. For that, go to Solution Explorer >> Resource >> Layout >> double click to open content_main.xml. Add the following code to this file.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  5.     xmlns:tools="http://schemas.android.com/tools"  
  6.     android:layout_width="match_parent"  
  7.     android:layout_height="match_parent"  
  8.     app:layout_behavior="@string/appbar_scrolling_view_behavior"  
  9.     tools:showIn="@layout/activity_main">  
  10.     <TextView  
  11.         android:id="@+id/txtChooseStatic"  
  12.        android:layout_width="fill_parent"    
  13.        android:layout_height="wrap_content"    
  14.        android:layout_marginTop="10dp"  
  15.        android:layout_alignParentTop="true"  
  16.        android:text="Choose Encoding Method" />    
  17.     <Spinner    
  18.        android:id="@+id/spinner"    
  19.        android:layout_width="fill_parent"  
  20.         android:layout_marginTop="10dp"  
  21.         android:layout_height="wrap_content"  
  22.        android:layout_below="@+id/txtChooseStatic"  
  23.        android:prompt="@string/action_choose"/>  
  24.     <EditText  
  25.          android:id="@+id/plain_text_input"  
  26.          android:layout_height="wrap_content"  
  27.          android:layout_width="match_parent"  
  28.          android:layout_margin="10dp"  
  29.          android:layout_below="@+id/spinner"  
  30.          android:hint="Type Message to Convert"  
  31.          android:inputType="text"/>  
  32.     <ImageView  
  33.         android:layout_centerHorizontal="true"  
  34.         android:layout_marginTop="10dp"  
  35.         android:id="@+id/barcodeImage"  
  36.         android:layout_below="@+id/plain_text_input"  
  37.         android:layout_width="wrap_content"  
  38.         android:layout_height="wrap_content"/>  
  39.     <Button  
  40.         android:id="@+id/generate"  
  41.         android:background="#000000"  
  42.         android:textColor="#ffffff"  
  43.         android:layout_centerHorizontal="true"  
  44.         android:layout_width="wrap_content"  
  45.         android:padding="10dp"  
  46.         android:layout_marginTop="10dp"  
  47.         android:layout_below="@+id/barcodeImage"  
  48.         android:layout_height="wrap_content"  
  49.         android:textSize="15dp"  
  50.         android:text="Generate Code"/>  
  51.   
  52. </RelativeLayout>  
Step 4
 
Next, open MainActivity.cs and add the following code to generate the barcode.
  1. using System;  
  2. using System.IO;  
  3. using Android.App;  
  4. using Android.Content.PM;  
  5. using Android.Graphics;  
  6. using Android.OS;  
  7. using Android.Runtime;  
  8. using Android.Support.Design.Widget;  
  9. using Android.Support.V4.App;  
  10. using Android.Support.V4.Content;  
  11. using Android.Support.V7.App;  
  12. using Android.Views;  
  13. using Android.Widget;  
  14. using ZXing;  
  15. using ZXing.Common;  
  16.   
  17. namespace BarCodeGenerator  
  18. {  
  19.     [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]  
  20.     public class MainActivity : AppCompatActivity  
  21.     {  
  22.         private TextView txtMessage;  
  23.         private string message;  
  24.         private static int size = 660;  
  25.         private static int small_size = 264;  
  26.         private Spinner spinnerValue;  
  27.         private string CodeType;  
  28.   
  29.         protected override void OnCreate(Bundle savedInstanceState)  
  30.         {  
  31.             base.OnCreate(savedInstanceState);  
  32.             Xamarin.Essentials.Platform.Init(this, savedInstanceState);  
  33.             SetContentView(Resource.Layout.activity_main);  
  34.   
  35.             Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);  
  36.             SetSupportActionBar(toolbar);  
  37.   
  38.             ImageView image = FindViewById<ImageView>(Resource.Id.barcodeImage);  
  39.             Button btnGenerate = FindViewById<Button>(Resource.Id.generate);  
  40.             txtMessage = FindViewById<TextView>(Resource.Id.plain_text_input);  
  41.             spinnerValue = FindViewById<Spinner>(Resource.Id.spinner);  
  42.             FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);  
  43.   
  44.             var adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.selected_Code, Android.Resource.Layout.SimpleSpinnerItem);  
  45.             adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);  
  46.             spinnerValue.Adapter = adapter;  
  47.             spinnerValue.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(SpinnerItemSelect);  
  48.             fab.Click += FabOnClick;  
  49.   
  50.             btnGenerate.Click += delegate  
  51.             {  
  52.                 string[] PERMISSIONS =  
  53.                 {  
  54.                     "android.permission.READ_EXTERNAL_STORAGE",  
  55.                     "android.permission.WRITE_EXTERNAL_STORAGE"  
  56.                 };  
  57.   
  58.                 var permission = ContextCompat.CheckSelfPermission(this"android.permission.WRITE_EXTERNAL_STORAGE");  
  59.                 var permissionread = ContextCompat.CheckSelfPermission(this"android.permission.READ_EXTERNAL_STORAGE");  
  60.   
  61.                 if (permission != Permission.Granted && permissionread != Permission.Granted)  
  62.                     ActivityCompat.RequestPermissions(this, PERMISSIONS, 1);  
  63.   
  64.                 try  
  65.                 {  
  66.                     if (permission == Permission.Granted && permissionread == Permission.Granted)  
  67.                     {  
  68.                         BitMatrix bitmapMatrix = null;  
  69.                         message = txtMessage.Text.ToString();  
  70.   
  71.                         switch (CodeType)  
  72.                         {  
  73.                             case "QR Code":  
  74.                                 bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.QR_CODE, size, size);  
  75.                                 break;  
  76.                             case "PDF 417":  
  77.                                 bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.PDF_417, size, small_size);  
  78.                                 break;  
  79.                             case "CODE 128":  
  80.                                 bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.CODE_128, size, small_size);  
  81.                                 break;  
  82.                             case "CODE 39":  
  83.                                 bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.CODE_39, size, small_size);  
  84.                                 break;  
  85.                             case "AZTEC":  
  86.                                 bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.AZTEC, size, small_size);  
  87.                                 break;  
  88.                         }  
  89.   
  90.                         var width = bitmapMatrix.Width;  
  91.                         var height = bitmapMatrix.Height;  
  92.                         int[] pixelsImage = new int[width * height];  
  93.   
  94.                         for (int i = 0; i < height; i++)  
  95.                         {  
  96.                             for (int j = 0; j < width; j++)  
  97.                             {  
  98.                                 if (bitmapMatrix[j, i])  
  99.                                     pixelsImage[i * width + j] = (int)Convert.ToInt64(0xff000000);  
  100.                                 else  
  101.                                     pixelsImage[i * width + j] = (int)Convert.ToInt64(0xffffffff);  
  102.   
  103.                             }  
  104.                         }  
  105.   
  106.                         Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);  
  107.                         bitmap.SetPixels(pixelsImage, 0, width, 0, 0, width, height);  
  108.   
  109.                         var sdpath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;  
  110.                         var path = System.IO.Path.Combine(sdpath, "logeshbarcode.jpg");  
  111.                         var stream = new FileStream(path, FileMode.Create);  
  112.                         bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);  
  113.                         stream.Close();  
  114.   
  115.                         image.SetImageBitmap(bitmap);  
  116.                     }  
  117.                     else  
  118.                     {  
  119.                         Console.WriteLine("No Permission");  
  120.                     }  
  121.                 }  
  122.                 catch (Exception ex)  
  123.                 {  
  124.                     Console.WriteLine($"Exception {ex} ");  
  125.                 }  
  126.             };  
  127.         }  
  128.   
  129.         private void SpinnerItemSelect(object sender, AdapterView.ItemSelectedEventArgs e)  
  130.         {  
  131.             Spinner spinner = (Spinner)sender;  
  132.             CodeType = (string)spinner.GetItemAtPosition(e.Position);  
  133.         }  
  134.   
  135.         public override bool OnCreateOptionsMenu(IMenu menu)  
  136.         {  
  137.             MenuInflater.Inflate(Resource.Menu.menu_main, menu);  
  138.             return true;  
  139.         }  
  140.   
  141.         public override bool OnOptionsItemSelected(IMenuItem item)  
  142.         {  
  143.             int id = item.ItemId;  
  144.             if (id == Resource.Id.action_settings)  
  145.             {  
  146.                 return true;  
  147.             }  
  148.   
  149.             return base.OnOptionsItemSelected(item);  
  150.         }  
  151.   
  152.         private void FabOnClick(object sender, EventArgs eventArgs)  
  153.         {  
  154.             View view = (View)sender;  
  155.             Snackbar.Make(view, "Replace with your own action", Snackbar.LengthLong)  
  156.                 .SetAction("Action", (Android.Views.View.IOnClickListener)null).Show();  
  157.         }  
  158.         public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)  
  159.         {  
  160.             Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
  161.   
  162.             base.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
  163.         }  
  164.     }  
  165. }  
Step 5
 
Finally, the application requires storage read and write permissions. For that, go to Solution Explorer >> Properties >> AndroidManifest.xml file. Check the permissions for External Storage Read and Write.
  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
  2. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />  
Step 6
 
Now, press F5 to run the application. The output will be like below.
 
Generate Barcode And QR Code In Xamarin Android
 
You can get the full source code from here.