How to build a Barcode Scanner Android App - Hive Programmers

avatar

Greetings to my favorite science community online, StemSocial.

It's @skyehi and although it's kinda late, I decided to make a little bit of time to continue my series on Android App development tutorial for beginners.

I couldn't make it yesterday because there was a lot of work and meetings to attend to but I saw the need to continue this tutorial to help Android App development programming newbies to keep moving forward.

For weeks now we've been developing awesome and basic Android Apps and the primary goal of each tutorial has been to introduce my readers and tutorial followers to new concepts or API in Android programming.

For today's tutorial, I'm going to take you through the simple steps to building a basic Android Barcode Scanner.

Polish_20231206_194634607.jpgOriginal Image Source by lmonk72 from Pixabay

uGB0GKX.png

I'm pretty sure you've seen barcodes on different products before. Barcodes are very important for fetching information or data about products, which is why the manufacturers put these codes on the products.

The barcodes they put on the products are almost useless if we don't have the technology or software to detect them. This is what makes barcode scanners so important which is why I felt the need to share this tutorial.

As a programmer, the more useful Apps you can build, the more successful and demanded you'll be.

So guys, by the end of this tutorial, you'll have a fully functional Android App capable of scanning barcodes using your device's camera.

I'll recommend getting your physical Android device ready since if you decide to run the app with an emulator, it may not be that easy to use the computer's camera to scan the barcodes especially if you can't lift the product with the barcode to face your computer's camera.

Alright guys let's get right into the codes shall we

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Setting Up Our Development environment

Alright guys, this parts for the newcomers to my tutorial because if you've been following and have been building Apps, you already have this stage figured out.

Before building your very own Android Apps, you need to ensure you have Android Studio installed on your machine.

We would be using Java programming language to write the logic of our App and so your computer would also require that you install Java Development Kit, JDK set-up so that your computer will be able to execute Java code.

If you're having trouble installing or download either of these softwares, please let me know in the comments section below.

At this point I'll assume everyone is good to go.

To start our work, please open Android studio and click on "Create a new Android Studio project" . The next step would be to set up the necessary configurations which would include the name of your App, the package name and the programming language.

There are two languages you can code in; you can develop your Android app using either Kotlin or Java.

I'll recommend that you choose Java as the programming language since it's basic tutorials. I have already made a promise to everyone that we'll be building using Kotlin soon.

Adding The Necessary Dependencies

Alright guys, like we did in one of our previous App projects, we would need to add a library that will allow our App to run a particular service, this time it's going to be barcode scanning service.

This library is called ZXing barcode scanning library and we'll be adding the dependency code inside the app-level build.gradle file.

Here's how your code should look like

implementation 'com.google.zxing:core:3.4.0'
implementation 'com.journeyapps:zxing-android-embedded:4.2.0'

After you're done writing the code, a green button that says "Sync" should have already appeared when you started editing the gradle file.

Click on that Sync button to sync your project to download the dependencies.

uGB0GKX.png

Designing our User Interface

Alright guys, it's time for the visible frontend part of our application. I'll make it a simple and basic looking application. However if you wish it improve on it, go for it. Besides, after that many tutorials, I'm hoping you're already getting good at building User Interfaces yourself.

So for a simple barcode scanner app, we'll design the layout inside activity_main.xml file. We'll add a SurfaceView element to preview the camera feed and a Button to start the barcode scanning process.

Here's how our design code should look like

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SurfaceView
        android:id="@+id/camera_preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <Button
        android:id="@+id/scan_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Scan"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"/>
</RelativeLayout>

Requesting Camera Permissions

I would have saved this part for later but I wouldn't want to forget it because of how crucial it is in enabling our barcode scanner app to actually work.

We need to request camera permission so that our App would be able to access the camera feature of the Android phone to be able to scan the barcodes.

This would need to be done inside our AndroidManifest.xml file.

Here's how your permission code should look like

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

uGB0GKX.png

Working On The Barcode Scanning Logic

Alright guys, it's time for another marathon coding. We're ready to work on the backend or logic of our barcode scanner app.

Since we have added the ZXing barcode scanning library to Gradle and successfully synced it, we should be able to use the "ZXing" code without any problems.

In our backend or logic code which would be written inside the MainActivity.java file, we would further request for camera access permission with Java code.

The codes may seem a bit much for newbies but to break it down, all we're doing is three main things; we will initialize the camera, handle permissions and finally configure the barcode scanner.

Here's how the logic of our App should look like.

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.zxing.Result;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;

public class MainActivity extends AppCompatActivity {

    private DecoratedBarcodeView barcodeView;
    private CaptureManager capture;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Check and request camera permission
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        }

        barcodeView = findViewById(R.id.barcode_scanner);
        capture = new CaptureManager(this, barcodeView);
        capture.initializeFromIntent(getIntent(), savedInstanceState);
        capture.decode();

        Button scanButton = findViewById(R.id.scan_button);
        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Trigger barcode scanning manually
                barcodeView.decodeSingle(callback);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        capture.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        capture.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        capture.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted, initialize barcode scanner
                capture.onResume();
            }
        }
    }

    private DecoratedBarcodeView.TorchListener torchListener = new DecoratedBarcodeView.TorchListener() {
        @Override
        public void onTorchOn() {
            // Torch on logic
        }

        @Override
        public void onTorchOff() {
            // Torch off logic
        }
    };

    private DecoratedBarcodeView.OnCaptureCallback callback = new DecoratedBarcodeView.OnCaptureCallback() {
        @Override
        public void onCaptured(Result result) {
            // Handle the scanned barcode result
        }
    };
}

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Now guys, you may want the barcode scanner to do other things with the results when it's gotten. Make sure to handle the barcode result appropriately for your application needs.

Maybe your app may need to share the results on social media, open Google and automatically search for a product with similar barcode or other advanced things.

It's entirely up to you on what your App is capable of doing with the results of scanning the barcode. Just have fun out there and maybe you might come up with a brilliant new innovation related to barcode scanners.

You can run the App now guys. Like I mentioned earlier on, I would recommend that you use a physical Android device to run this particular App project so that the barcode scanner can use your phone's camera to scan any barcode and give you the results.

Thank you so much for taking the time to read this blog. I hope you enjoyed today's tutorial guys. Little by little, we're approaching developing more complex Apps guys. Soon you'll become a pro at develop Android applications.

As always if you're having troubles installing the software programs you need, writing the code or running the finished app, please let me know in the comments.

Have a lovely day and catch you next time on StemSocial. Goodbye 👨‍💻


You Can Follow Me @skyehi For More Like This And Others



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support. 
 

0
0
0.000