Android tutorial

Android QR Code / Bar Code Scanner – ZxingScannerView 2022

Android QR Code / Bar Code Scanner - ZxingScannerView 2022
1.1kviews

Android QR Code  &  Bar Code Scanner – ZxingScannerView 2022. Hey in this tutorial I am creating an easy way to android bar code scanner. today bar is used in every product to use digital market show detail. you can scan the bar code and get detail of the product. Android Create a Bar Code Scanner ZxingScannerView

The QR code scanner can be used with an Android device with the default camera software or Google Lens app. So long as your Android device is equipped with cameras, it should be able to read every QR code. After you’ve scanned the QR code with your Android it will browse the URL or even send it to others. Check out Insider’s Tech Reference library for more

Android QR Code / Bar Code Scanner

In the process of developing an android app, at times it is necessary to add the capability of scanning barcodes or QR codes. The scanning of the QR code is possible through programming using various methods:

  • Utilizing a web-based API that allows the barcode or QR code is transmitted to the server and the server then returns the results.
  • Utilizing a web-based app that uses your camera to scan the barcode or QR code and then returns the results.
  • By Integrating the Mobile Vision API of Google Play Service.

Android QR Code Scanner Example

In this instance we examine the QR code on the web URL as well as an Email email address and then act upon it. We will utilize Google’s mobile Vision API of the Google Play Service to scan the QR code. This Mobile Vision API supports the different barcode formats.

Step 1:  To  Start Android Studio.

Step 2 :   Create a New Project Project Click On  ==>  File  ==>  NEW  ==>  New Project. 

 

Then Enter App Name and Click On next -> after the Select App Developer for Phone and Tablet -> Then a Empty Activity and click on next -> Create a Activity in your Project Home name  -> In your home activity add a button scan

 

 

 

 

Step 3:-  Add Dependencies in your build.gradle.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:28.+'
    compile 'com.android.support:design:28.+'
    compile 'com.android.support:support-v4:28.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.journeyapps:zxing-android-embedded:3.4.0'
    compile 'me.dm7.barcodescanner:core:1.9'
    compile 'com.android.support:multidex:1.0.0'
    testCompile 'junit:junit:4.12'
}

Step 4 :- Add user permission in mainfests file.

<uses-permission android:name="android.permission.CAMERA" /> 
<uses-feature android:name="android.hardware.camera" /> 
<uses-feature android:name="android.hardware.camera.autofocus" />

Create a main activity in your project  and open your main activity java and xml file.

Step 5:- Main Activity Xml  Complete code ( activity_main.xml ).

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center"
    android:layout_height="match_parent"
    tools:context="com.codepalyon.barcodescanner.Main">

    <Button
        android:id="@+id/ScannerBtn"
        android:layout_width="150dp"
        android:layout_gravity="center"
        android:layout_height="50dp"
        android:text="Scan"/>

</LinearLayout>

Step 6:-  Main.java   file Complete code.

public class Main extends AppCompatActivity {
Button ScanerBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ScanerBtn=(Button)findViewById(R.id.ScannerBtn);
        ScanerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Main.this,Home.class);
                startActivity(intent);
            }
        });
    }
}

Step 7:- to create any other activity Home_Scanner.java

public  class Home extends AppCompatActivity  implements ZXingScannerView.ResultHandler{
private ZXingScannerView mScannerView;
private static final int WRITE_EXST = 1;
private static final int REQUEST_PERMISSION = 123;
        int CAMERA;
        String position,formt;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
//        Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(this));

        if( ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[]{Manifest.permission.CAMERA},5);
        }
        }

        ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
        mScannerView = new ZXingScannerView(this);
        contentFrame.addView(mScannerView);
        }
@Override
public void onResume() {
        super.onResume();
        mScannerView.setResultHandler(this);
        mScannerView.startCamera();
        }

@Override
public void onPause() {
        super.onPause();
        mScannerView.stopCamera();
        }

@Override
public void handleResult(Result rawResult) {
        Toast.makeText(this, "Contents = " + rawResult.getText() +", Format = " + rawResult.getBarcodeFormat().toString(), Toast.LENGTH_LONG).show();
        position=rawResult.getText();
        formt=rawResult.getBarcodeFormat().toString();
        Intent intent=new Intent();
        intent.putExtra("Contents",position);
        intent.putExtra("Format",formt);
        setResult(RESULT_OK,intent);
        finish();

        }

        @Override
        public void handleResult(MediaBrowserServiceCompat.Result rawResult) {

        }
}

Step 8:-  activity_home_scanner.xml   Complete code.

<?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"
    tools:context="com.codepalyon.barcodescanner.Home">


    <TextView
        android:padding="5dp"
        android:textColor="@android:color/white"
        android:background="@android:color/black"
        android:text="Place your camera above the bar code on coupon to scan !"
        android:id="@+id/tv_scan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"/>

    <FrameLayout
        android:layout_below="@+id/tv_scan"
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>
</RelativeLayout>

Step 9:-  Create a java Class   ZxingScannerView.java Complete code .

public class ZXingScannerView extends BarcodeScannerView {
    private static final String TAG = "ZXingScannerView";

    public interface ResultHandler {
        public void handleResult(Result rawResult);

        void handleResult(MediaBrowserServiceCompat.Result rawResult);
    }

    private MultiFormatReader mMultiFormatReader;
    public static final List<BarcodeFormat> ALL_FORMATS = new ArrayList<BarcodeFormat>();
    private List<BarcodeFormat> mFormats;
    private ResultHandler mResultHandler;

    static {
        ALL_FORMATS.add(BarcodeFormat.UPC_A);
        ALL_FORMATS.add(BarcodeFormat.UPC_E);
        ALL_FORMATS.add(BarcodeFormat.EAN_13);
        ALL_FORMATS.add(BarcodeFormat.EAN_8);
        ALL_FORMATS.add(BarcodeFormat.RSS_14);
        ALL_FORMATS.add(BarcodeFormat.CODE_39);
        ALL_FORMATS.add(BarcodeFormat.CODE_93);
        ALL_FORMATS.add(BarcodeFormat.CODE_128);
        ALL_FORMATS.add(BarcodeFormat.ITF);
        ALL_FORMATS.add(BarcodeFormat.CODABAR);
        ALL_FORMATS.add(BarcodeFormat.QR_CODE);
        ALL_FORMATS.add(BarcodeFormat.DATA_MATRIX);
        ALL_FORMATS.add(BarcodeFormat.PDF_417);
    }

    public ZXingScannerView(Context context) {
        super(context);
        initMultiFormatReader();
    }

    public ZXingScannerView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        initMultiFormatReader();
    }

    public void setFormats(List<BarcodeFormat> formats) {
        mFormats = formats;
        initMultiFormatReader();
    }

    public void setResultHandler(ResultHandler resultHandler) {
        mResultHandler = resultHandler;
    }

    public Collection<BarcodeFormat> getFormats() {
        if(mFormats == null) {
            return ALL_FORMATS;
        }
        return mFormats;
    }

    private void initMultiFormatReader() {
        Map<DecodeHintType,Object> hints = new EnumMap<DecodeHintType,Object>(DecodeHintType.class);
        hints.put(DecodeHintType.POSSIBLE_FORMATS, getFormats());
        mMultiFormatReader = new MultiFormatReader();
        mMultiFormatReader.setHints(hints);
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        if(mResultHandler == null) {
            return;
        }

        try {
            Camera.Parameters parameters = camera.getParameters();
            Camera.Size size = parameters.getPreviewSize();
            int width = size.width;
            int height = size.height;

            if (DisplayUtils.getScreenOrientation(getContext()) == Configuration.ORIENTATION_PORTRAIT) {
                byte[] rotatedData = new byte[data.length];
                for (int y = 0; y < height; y++) {
                    for (int x = 0; x < width; x++)
                        rotatedData[x * height + height - y - 1] = data[x + y * width];
                }
                int tmp = width;
                width = height;
                height = tmp;
                data = rotatedData;
            }

            Result rawResult = null;
            PlanarYUVLuminanceSource source = buildLuminanceSource(data, width, height);

            if (source != null) {
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                try {
                    rawResult = mMultiFormatReader.decodeWithState(bitmap);
                } catch (ReaderException re) {
                    // continue
                } catch (NullPointerException npe) {
                    // This is terrible
                } catch (ArrayIndexOutOfBoundsException aoe) {
                } finally {
                    mMultiFormatReader.reset();
                }
            }

            final Result finalRawResult = rawResult;
            if (finalRawResult != null) {
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        // Stopping the preview can take a little long.
                        // So we want to set result handler to null to discard subsequent calls to
                        // onPreviewFrame.
                        ResultHandler tmpResultHandler = mResultHandler;
                        mResultHandler = null;
                        stopCameraPreview();
                        if (tmpResultHandler != null) {
                            tmpResultHandler.handleResult(finalRawResult);
                        }
                    }
                });
            } else {
                camera.setOneShotPreviewCallback(this);
            }
        } catch(RuntimeException e) {
            // TODO: Terrible hack. It is possible that this method is invoked after camera is released.
            Log.e(TAG, e.toString(), e);
        }
    }

    public void resumeCameraPreview(ResultHandler resultHandler) {
        mResultHandler = resultHandler;
        super.resumeCameraPreview();
    }

    public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
        Rect rect = getFramingRectInPreview(width, height);
        if (rect == null) {
            return null;
        }
        // Go ahead and assume it's YUV rather than die.
        PlanarYUVLuminanceSource source = null;
        try {
            source = new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top, rect.width(), rect.height(), false);
        } catch(Exception e) {
        }
        return source;
    }
}

Step 10:-  Create a  java class  BaseScannerActivity.java

public class BaseScannerActivity extends AppCompatActivity {

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

 

 

Read More Tutorial