Generate BarCode and QR Code in Xamarin Android

Introduction

           In this article, we can discuss how to generate 1D and 2D Barcode in Xamarin Android application. Here basic requirement to generate Barcode or QR Code, we need to get some information form user like what message you want to convert, Code format, size of the bitmap. There is no default library for this. so, we need to install a plugin for this. Just write a few lines of code to generate 1D and 2D Code. The Barcode has a different format but I demonstrate some few code formats – Code 39, Code 128, AZTEC and QR Code. 

Android Output:

Let’s start ?

Step 1: First we need to create an Xamarin.Android Application, So Go to Visual Studio=>New Project => Android App click next.

Then opened new popup Page. Here give the App Name, Organization name, Select Target Platform AND Select the App theme, Finally click Next button then Created new Application.

 

Step 2:After project creation, We need to install a plugin. So Go to to Solution Explorer =>Right-click Packages=> Add packages, then new windows will be appear, here right-side top search ZXing.Net plugin Then Install this package.



Step 3: Now, let’s coding. First open content_main.xml. For that, go to Solution Explorer => Resource => Layout => double click to open content_main.xml. add the following given code.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main">
    <TextView
        android:id="@+id/txtChooseStatic"
       android:layout_width="fill_parent"  
       android:layout_height="wrap_content"  
       android:layout_marginTop="10dp"
       android:layout_alignParentTop="true"
       android:text="Choose Encoding Method" />  
    <Spinner  
       android:id="@+id/spinner"  
       android:layout_width="fill_parent"
        android:layout_marginTop="10dp"
        android:layout_height="wrap_content"
       android:layout_below="@+id/txtChooseStatic"
       android:prompt="@string/action_choose"/>
    <EditText
         android:id="@+id/plain_text_input"
         android:layout_height="wrap_content"
         android:layout_width="match_parent"
         android:layout_margin="10dp"
         android:layout_below="@+id/spinner"
         android:hint="Type Message to Convert"
         android:inputType="text"/>
    <ImageView
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:id="@+id/barcodeImage"
        android:layout_below="@+id/plain_text_input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/generate"
        android:background="#000000"
        android:textColor="#ffffff"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:padding="10dp"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/barcodeImage"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:text="Generate Code"/>

</RelativeLayout>
Step 4: Next open, MainActivity.cs and add the following code to generate bar code.Open Solution Explorer => MainActivity.cs. then give the below given code.
1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
using System;
using System.IO;
using Android.App;
using Android.Content.PM;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android.Support.V7.App;
using Android.Views;
using Android.Widget;
using ZXing;
using ZXing.Common;

namespace BarCodeGenerator
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        private TextView txtMessage;
        private string message;
        private static int size = 660;
        private static int small_size = 264;
        private Spinner spinnerValue;
        private string CodeType;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            ImageView image = FindViewById<ImageView>(Resource.Id.barcodeImage);
            Button btnGenerate = FindViewById<Button>(Resource.Id.generate);
            txtMessage = FindViewById<TextView>(Resource.Id.plain_text_input);
            spinnerValue = FindViewById<Spinner>(Resource.Id.spinner);
            FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);

            var adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.selected_Code, Android.Resource.Layout.SimpleSpinnerItem);
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinnerValue.Adapter = adapter;
            spinnerValue.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(SpinnerItemSelect);
            fab.Click += FabOnClick;

            btnGenerate.Click += delegate
            {
                string[] PERMISSIONS =
                {
                    "android.permission.READ_EXTERNAL_STORAGE",
                    "android.permission.WRITE_EXTERNAL_STORAGE"
                };

                var permission = ContextCompat.CheckSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
                var permissionread = ContextCompat.CheckSelfPermission(this, "android.permission.READ_EXTERNAL_STORAGE");

                if (permission != Permission.Granted && permissionread != Permission.Granted)
                    ActivityCompat.RequestPermissions(this, PERMISSIONS, 1);

                try
                {
                    if (permission == Permission.Granted && permissionread == Permission.Granted)
                    {
                        BitMatrix bitmapMatrix = null;
                        message = txtMessage.Text.ToString();

                        switch (CodeType)
                        {
                            case "QR Code":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.QR_CODE, size, size);
                                break;
                            case "PDF 417":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.PDF_417, size, small_size);
                                break;
                            case "CODE 128":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.CODE_128, size, small_size);
                                break;
                            case "CODE 39":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.CODE_39, size, small_size);
                                break;
                            case "AZTEC":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.AZTEC, size, small_size);
                                break;
                        }

                        var width = bitmapMatrix.Width;
                        var height = bitmapMatrix.Height;
                        int[] pixelsImage = new int[width * height];

                        for (int i = 0; i < height; i++)
                        {
                            for (int j = 0; j < width; j++)
                            {
                                if (bitmapMatrix[j, i])
                                    pixelsImage[i * width + j] = (int)Convert.ToInt64(0xff000000);
                                else
                                    pixelsImage[i * width + j] = (int)Convert.ToInt64(0xffffffff);

                            }
                        }

                        Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
                        bitmap.SetPixels(pixelsImage, 0, width, 0, 0, width, height);

                        var sdpath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
                        var path = System.IO.Path.Combine(sdpath, "logeshbarcode.jpg");
                        var stream = new FileStream(path, FileMode.Create);
                        bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
                        stream.Close();

                        image.SetImageBitmap(bitmap);
                    }
                    else
                    {
                        Console.WriteLine("No Permission");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Exception {ex} ");
                }
            };
        }

        private void SpinnerItemSelect(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            Spinner spinner = (Spinner)sender;
            CodeType = (string)spinner.GetItemAtPosition(e.Position);
        }

        public override bool OnCreateOptionsMenu(IMenu menu)
        {
            MenuInflater.Inflate(Resource.Menu.menu_main, menu);
            return true;
        }

        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            int id = item.ItemId;
            if (id == Resource.Id.action_settings)
            {
                return true;
            }

            return base.OnOptionsItemSelected(item);
        }

        private void FabOnClick(object sender, EventArgs eventArgs)
        {
            View view = (View)sender;
            Snackbar.Make(view, "Replace with your own action", Snackbar.LengthLong)
                .SetAction("Action", (Android.Views.View.IOnClickListener)null).Show();
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

Step 5:Then application required storage read and write permission. Go to Solution Explorer => Properties => Open AndroidManifest.xml file. Give the External Storage Read and Write Permission.
1
2
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Step 6: Finally, press F5 to run the application. Then you will the given below Output .

Download Source Code Here…

Leave a Comment

Your email address will not be published. Required fields are marked *