Wednesday, 2 November 2016

Scan BarCode in Android barcodescanner:zxing Library




Step: 1
======



Credits to author of the Library.
https://github.com/dm77/barcodescanner

Add library to your build.gradle file under app folder

compile 'me.dm7.barcodescanner:zxing:1.9'


Step: 2
======

MainActivity.java
==================

package com.pratap.scanbarcode;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText txt_barcodevalue;

    Button btn_scan;

    final int REQUEST_CAMERA_PERMISSION = 1001;
    final int DELAY_TIME = 4000;

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

        txt_barcodevalue = (EditText) findViewById(R.id.txt_barcodevalue);
        btn_scan = (Button) findViewById(R.id.btn_scan);

        btn_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkCameraPermissions();

            }
        });
    }

    public void openBarCodeScanner() {


        Intent scanIntent = new Intent(this, BarCodeScannerActivity.class);
        startActivityForResult(scanIntent, 1006);

    }


    public void checkCameraPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            openBarCodeScanner();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted
                openBarCodeScanner();
            } else {
                // permission denied, boo!
                showMessage("Camera Permission Denied!!!");
            }
        }
    }


    public void showMessage(String message) {

        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1006) {
            if (resultCode == Activity.RESULT_OK && data != null) {

                String barcodeNumber = data.getStringExtra("BarCodeNumber");
                txt_barcodevalue.setText(barcodeNumber);

            }
        }


    }

}


XML Layout file for Main Activity
=========================

activity_main.xml
=============


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_margin="16dp"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/txt_barcodevalue"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="text" />

        <Button
            android:id="@+id/btn_scan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Scan" />

    </LinearLayout>


</RelativeLayout>





Step: 3
======

BarCodeScannerActivity.java
=====================
Please add this Activity to your AndroidManifest file.


package com.pratap.scanbarcode;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.zxing.Result;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class BarCodeScannerActivity extends Activity implements ZXingScannerView.ResultHandler {
    private ZXingScannerView mScannerView;

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        mScannerView = new ZXingScannerView(this);
        setContentView(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) {
        // Do something with the result here
        Log.v("Scan Result", rawResult.getText()); // Prints scan results
        Log.v("Scan Qr code format", rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)

        Toast.makeText(BarCodeScannerActivity.this, rawResult.getText(), Toast.LENGTH_SHORT).show();

        // If you would like to resume scanning, call this method below:
        // mScannerView.resumeCameraPreview(this);

        Intent intentMessage = new Intent();

        // put the message in Intent
        intentMessage.putExtra("BarCodeNumber", rawResult.getText());
        // Set The Result in Intent
        setResult(RESULT_OK, intentMessage);
        // finish The activity
        finish();


    }
}



Step: 4
======

AndroidManifest.xml
===================


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pratap.scanbarcode">


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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <activity
            android:name=".BarCodeScannerActivity"
            android:screenOrientation="portrait">

        </activity>
    </application>

</manifest>


Demo
======













References
========
Credits to author of the Library.
https://github.com/dm77/barcodescanner