Skip to main content

How to use qrcode and bar code scanner in android with kotlin

QRCode and BarCode scanner in Android 

 To create a QR code and barcode scanner in Android Studio using Kotlin, you can follow these steps:


1. **Set Up Dependencies:**

   Add the necessary dependencies to your app's build.gradle file.


   ```gradle

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

   implementation 'androidx.appcompat:appcompat:1.3.1'

   implementation 'androidx.core:core-ktx:1.6.0'

   implementation 'com.journeyapps:zxing-android-embedded:4.2.0'

   ```


2. **Create the Layout:**

   Create the layout for your scanner activity. For example, you can create `activity_scanner.xml`.


   ```xml

   <?xml version="1.0" encoding="utf-8"?>

   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

       xmlns:tools="http://schemas.android.com/tools"

       android:layout_width="match_parent"

       android:layout_height="match_parent"

       tools:context=".ScannerActivity">


       <SurfaceView

           android:id="@+id/camera_preview"

           android:layout_width="match_parent"

           android:layout_height="match_parent" />


   </RelativeLayout>

   ```


3. **Create Scanner Activity:**

   Create a new Kotlin class for your scanner activity. For example, `ScannerActivity.kt`.


   ```kotlin

   import android.Manifest

   import android.content.pm.PackageManager

   import android.os.Bundle

   import androidx.appcompat.app.AppCompatActivity

   import androidx.core.app.ActivityCompat

   import androidx.core.content.ContextCompat

   import com.google.android.gms.vision.CameraSource

   import com.google.android.gms.vision.Detector

   import com.google.android.gms.vision.barcode.Barcode

   import com.google.android.gms.vision.barcode.BarcodeDetector

   import kotlinx.android.synthetic.main.activity_scanner.*

   import java.io.IOException


   class ScannerActivity : AppCompatActivity() {


       private lateinit var cameraSource: CameraSource

       private lateinit var barcodeDetector: BarcodeDetector


       override fun onCreate(savedInstanceState: Bundle?) {

           super.onCreate(savedInstanceState)

           setContentView(R.layout.activity_scanner)


           barcodeDetector = BarcodeDetector.Builder(this)

               .setBarcodeFormats(Barcode.QR_CODE)

               .build()


           cameraSource = CameraSource.Builder(this, barcodeDetector)

               .setAutoFocusEnabled(true)

               .build()


           if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)

               != PackageManager.PERMISSION_GRANTED

           ) {

               ActivityCompat.requestPermissions(

                   this,

                   arrayOf(Manifest.permission.CAMERA),

                   CAMERA_PERMISSION_REQUEST

               )

           } else {

               startCamera()

           }

       }


       private fun startCamera() {

           try {

               camera_preview.holder.addCallback(object : SurfaceHolder.Callback {

                   override fun surfaceCreated(holder: SurfaceHolder) {

                       try {

                           cameraSource.start(camera_preview.holder)

                       } catch (e: IOException) {

                           e.printStackTrace()

                       }

                   }


                   override fun surfaceChanged(

                       holder: SurfaceHolder,

                       format: Int,

                       width: Int,

                       height: Int

                   ) {

                   }


                   override fun surfaceDestroyed(holder: SurfaceHolder) {

                       cameraSource.stop()

                   }

               })


               barcodeDetector.setProcessor(object : Detector.Processor<Barcode> {

                   override fun release() {

                   }


                   override fun receiveDetections(detections: Detector.Detections<Barcode>) {

                       val barcodes = detections.detectedItems

                       if (barcodes.size() > 0) {

                           val barcode = barcodes.valueAt(0)

                           // Handle the scanned barcode/QR code here

                       }

                   }

               })

           } catch (e: SecurityException) {

               e.printStackTrace()

           }

       }


       override fun onRequestPermissionsResult(

           requestCode: Int,

           permissions: Array<String>,

           grantResults: IntArray

       ) {

           if (requestCode == CAMERA_PERMISSION_REQUEST) {

               if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                   startCamera()

               } else {

                   // Handle permission denial

               }

           }

       }


       companion object {

           private const val CAMERA_PERMISSION_REQUEST = 100

       }

   }

   ```


4. **Handle the Scanned Data:**

   In the `receiveDetections` function of the barcode detector's processor, you can handle the scanned barcode or QR code data. You can display it, perform actions, or whatever suits your application's needs.


5. **Add Permissions:**

   Don't forget to add the necessary permissions to your AndroidManifest.xml.


   ```xml

   <uses-permission android:name="android.permission.CAMERA" />

   ```


6. **Run the App:**

   Run your application on a device or emulator, and it should launch the camera to scan QR codes and barcodes.


Remember that this example uses the `zxing-android-embedded` library for barcode scanning. There are other libraries available as well, so you might want to explore different options based on your requirements.

Comments

Popular posts from this blog

How to write a code of Encode and Decode json data in Dart language

 Encode and decode JSON data in dart language import 'dart:convert'; void main() {   // Original data as a Dart map   Map<String, dynamic> originalData = {     'field1': 'value1',     'field2': 42,     'field3': true,   };   // Encode the Dart map to JSON string   String jsonString = jsonEncode(originalData);   print('Original JSON String:');   print(jsonString);   // Encode the JSON string to base64   String base64EncodedString = base64.encode(utf8.encode(jsonString));   print('\nBase64 Encoded String:');   print(base64EncodedString);   // Decode the base64 string to JSON string   String decodedJsonString = utf8.decode(base64.decode(base64EncodedString));   print('\nDecoded JSON String:');   print(decodedJsonString);   // Decode the JSON string to a Dart map   Map<String, dynamic> decodedData = jsonDecode(decodedJsonString);   print('\nDecoded Dart Ma...

About of Free Learning Tech Point

  Welcome to Free Learning Tech Point , where knowledge meets accessibility. Our platform is dedicated to providing high-quality educational resources and e-learning opportunities to learners around the world, completely free of charge. Our Mission: At Free Learning Tech Point, we believe that education is a fundamental right, and everyone should have access to valuable learning materials. Our mission is to break down barriers to education by offering a diverse range of courses, tutorials, and resources across various subjects and disciplines. What Sets Us Apart: - Free Access: Our commitment is to make learning accessible to all. No subscription fees, no hidden costs – just free, open access to knowledge.    - Quality Content: We curate and create content that is both engaging and informative. Whether you're a student, professional, or lifelong learner, our resources are designed to cater to various learning styles and levels. - Diverse Subjects: From tech and science...

Privacy Policy Of Free Learning Tech Point

  Thank you for visiting Free Learning Tech Point . You can use our website, services, and products with the awareness that this Privacy Policy describes how we gather, use, disclose, and protect your personal information. 1- Information We Collect: We may collect personal information that you provide directly to us, such as your name, email address, and any other information you choose to provide when using our Services. We may also collect non-personal information, such as aggregated data and usage patterns. 2- How We Use Your Information: We may use the information we collect for various purposes, including but not limited to: Providing and improving our Services. Responding to your inquiries and requests. Analyzing usage patterns and trends. Sending you updates, newsletters, and other communications. Personalizing your experience on our platform. 3- Cookies and Similar Technologies: We may use cookies and similar technologies to collect information about your interactions with...