Skip to main content

How to use QRCode and BarCode scanner in android with java

 QRCode & BarCode Scanner in Android with Java

To create a QR code and barcode scanner in Android Studio using Java, you can follow similar steps as outlined in the Kotlin example. Here's how you can do it:


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:1.7.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 Java class for your scanner activity. For example, `ScannerActivity.java`.


   ```java

   import android.Manifest;

   import android.content.pm.PackageManager;

   import android.os.Bundle;

   import androidx.annotation.NonNull;

   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 java.io.IOException;


   public class ScannerActivity extends AppCompatActivity {


       private CameraSource cameraSource;

       private BarcodeDetector barcodeDetector;

       private static final int CAMERA_PERMISSION_REQUEST = 100;


       @Override

       protected void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           setContentView(R.layout.activity_scanner);


           barcodeDetector = new BarcodeDetector.Builder(this)

               .setBarcodeFormats(Barcode.QR_CODE)

               .build();


           cameraSource = new CameraSource.Builder(this, barcodeDetector)

               .setAutoFocusEnabled(true)

               .build();


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

               != PackageManager.PERMISSION_GRANTED) {

               ActivityCompat.requestPermissions(

                   this,

                   new String[]{Manifest.permission.CAMERA},

                   CAMERA_PERMISSION_REQUEST

               );

           } else {

               startCamera();

           }

       }


       private void startCamera() {

           try {

               SurfaceView cameraPreview = findViewById(R.id.camera_preview);

               cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {

                   @Override

                   public void surfaceCreated(SurfaceHolder holder) {

                       try {

                           cameraSource.start(holder);

                       } catch (IOException e) {

                           e.printStackTrace();

                       }

                   }


                   @Override

                   public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

                   }


                   @Override

                   public void surfaceDestroyed(SurfaceHolder holder) {

                       cameraSource.stop();

                   }

               });


               barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {

                   @Override

                   public void release() {

                   }


                   @Override

                   public void receiveDetections(Detector.Detections<Barcode> detections) {

                       final SparseArray<Barcode> barcodes = detections.getDetectedItems();

                       if (barcodes.size() > 0) {

                           Barcode barcode = barcodes.valueAt(0);

                           // Handle the scanned barcode/QR code here

                       }

                   }

               });

           } catch (SecurityException e) {

               e.printStackTrace();

           }

       }


       @Override

       public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

           if (requestCode == CAMERA_PERMISSION_REQUEST) {

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

                   startCamera();

               } else {

                   // Handle permission denial

               }

           }

       }

   }

   ```


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.


Just like with the Kotlin example, ensure that you have a properly configured layout, Java code, and manifest permissions to make the barcode and QR code scanning functionality work correctly.

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...