Wednesday, 7 March 2018

Android Scanner App Tutorial With Zxing Library

Android Scanner Tutorial with Zxing Library


Today i am going to let you know how to make "Scanner App". I got lot of messages and comment to a make a tutorial on scanner . 

I have used Zxing Library, there are other libraries also. But i am using
"ZXING", it is very easy for begginer .

ZXING is used for BARCODE And QRCODE Scanning.

I am making app similar to : SCANNER APP

Implementation :
Add dependencies in gradle file :
   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:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    testCompile 'junit:junit:4.12'




    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.0.0'



    compile 'com.google.android.gms:play-services-vision:9.4.0'
    compile 'com.google.android.gms:play-services-location:9.4.0'



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


MainActivity Code :



 public class MainActivity extends AppCompatActivity implements View.OnClickListener , GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private ZXingScannerView mScannerView;
    private ImageView ivScanQr;
    private TextView tvSub;
    private TextView edCode;
    private static final int RC_BARCODE_CAPTURE = 9001;
    private static final int RC_BARCODE_ZXINGSCANNER = 9002;

    private String lat = "0";
    private String lng = "0";


    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation;
    String mLastUpdateTime;
    protected static final int REQUEST_CHECK_SETTINGS = 0x11;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


       /* if (getSupportActionBar() != null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setTitle("Scanner");

        }*/

        if (!isGooglePlayServicesAvailable()) {
            MainActivity.this.finish();
        }
        //createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mGoogleApiClient.connect();

        mLocationRequest = new LocationRequest();
        //mLocationRequest.setInterval(INTERVAL);
        //mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest);

        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult locationSettingsResult) {

                final Status status = locationSettingsResult.getStatus();
                final LocationSettingsStates LS_state = locationSettingsResult.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can initialize location
                        // requests here.

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the user
                        // a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);

                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the dialog.

                        break;
                }
            }
        });


        ivScanQr = (ImageView) findViewById(R.id.iv_scan);
        tvSub    = (TextView)  findViewById(R.id.tv_sub);
        edCode   = (TextView)  findViewById(R.id.et_qr_code);

        ivScanQr.setOnClickListener(this);
        tvSub.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.iv_scan:

//                Intent intent = new Intent(CaptureSaleActivity.this, BarcodeCaptureActivity.class);
//                intent.putExtra(BarcodeCaptureActivity.AutoFocus, true);
//                intent.putExtra(BarcodeCaptureActivity.UseFlash, false);
//                startActivityForResult(intent, RC_BARCODE_CAPTURE);

                Intent intent = new Intent(MainActivity.this, SimpleScannerActivity.class);
                startActivityForResult(intent, RC_BARCODE_ZXINGSCANNER);

                break;
            case R.id.tv_sub:



                break;
        }

    }



    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status,MainActivity.this, 0).show();
            return false;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == RC_BARCODE_CAPTURE) {
//            if (resultCode == CommonStatusCodes.SUCCESS) {
//                if (data != null) {
//                    Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject);
//                   // Toast.makeText(CaptureSaleActivity.this, barcode.displayValue, Toast.LENGTH_LONG).show();
//                    edCode.setText(barcode.displayValue);
//                    CustomLog.d("Barcode read: " + barcode.displayValue);
//                } else {
//                    Toast.makeText(CaptureSaleActivity.this, "No barcode captured", Toast.LENGTH_LONG).show();
//                    CustomLog.d("No barcode captured, intent data is null");
//                }
//            } else {
//                Toast.makeText(CaptureSaleActivity.this, "Barcode error", Toast.LENGTH_LONG).show();
//            }
//        } else
        if (requestCode == RC_BARCODE_ZXINGSCANNER) {

            if (resultCode == CommonStatusCodes.SUCCESS) {
                if (data != null) {
                    edCode.setText(data.getStringExtra("barcode"));
                }else{
                    edCode.setText("");
                    Toast.makeText(MainActivity.this, "No barcode captured", Toast.LENGTH_LONG).show();
                    CustomLog.d("No barcode captured, intent data is null");
                }
            }

        }else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        CustomLog.i("onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
        startLocationUpdates();
    }

    protected void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
        CustomLog.i(  "Location update started ..............: ");
    }
    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        CustomLog.i( "Connection failed: " + connectionResult.toString());
    }

    @Override
    public void onLocationChanged(Location location) {
        CustomLog.i( "Firing onLocationChanged..............................................");
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();
    }



    private void updateUI() {
        CustomLog.i( "UI update initiated .............");
        if (null != mCurrentLocation) {
            lat = String.valueOf(mCurrentLocation.getLatitude());
            lng = String.valueOf(mCurrentLocation.getLongitude());
            Log.e("At Time: " , mLastUpdateTime + "\n" +
                    "Latitude: " + lat + "\n" +
                    "Longitude: " + lng + "\n" +
                    "Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
                    "Provider: " + mCurrentLocation.getProvider());



        } else {
            CustomLog.i( "location is null ...............");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mGoogleApiClient.isConnected()) {
            stopLocationUpdates();
        }else{
            mGoogleApiClient.connect();
            //stopLocationUpdates();
        }
    }

    protected void stopLocationUpdates() {
        if (null != mGoogleApiClient) {
            LocationServices.FusedLocationApi.removeLocationUpdates(
                    mGoogleApiClient, this);
            CustomLog.i( "Location update stopped .......................");
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        CustomLog.i( "onStart fired ..............");
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        CustomLog.i( "onStop fired ..............");
        mGoogleApiClient.disconnect();
        CustomLog.i( "isConnected ...............: " + mGoogleApiClient.isConnected());
    }



    @Override
    public void onBackPressed() {

        super.onBackPressed();
    }
}



SimpleScannerActivity.java
public class SimpleScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
    private ZXingScannerView mScannerView;

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        setContentView(R.layout.activity_simple_scanner);

        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_SHORT).show();
        Intent data = new Intent();
        data.putExtra("barcode", rawResult.getText());
        setResult(CommonStatusCodes.SUCCESS, data);
        finish();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mScannerView.resumeCameraPreview(SimpleScannerActivity.this);
            }
        }, 2000);
    }
}




activity_main.xml

  <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        >


        <TextView
            android:layout_marginTop="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/text_14"
            android:text="SCAN QR CODE"
            android:textColor="@color/gray"
            android:padding="10dp"
            android:gravity="center"
            />

        <ImageView
            android:id="@+id/iv_scan"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"
            android:layout_marginTop="20dp"
            android:src="@drawable/scan_qr"
            />

        <TextView
            android:visibility="gone"
            android:id="@+id/textView"
            style="@style/text_14"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:padding="10dp"
            android:text="QR ENTER CODE MANUALLY"
            android:textColor="@color/gray" />

        <TextView

            android:layout_marginLeft="60dp"
            android:layout_marginRight="60dp"
            android:id="@+id/et_qr_code"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:textColor="@color/gray"
            android:textColorHint="@color/gray"
            android:hint="Your Scanned Code Is"
            android:gravity="center"
            android:background="@drawable/bottom_line_black"
            android:padding="10dp"
            />
         
    </LinearLayout>

</ScrollView>

activity_simple_scanner:


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


barcode_capture.xml
    
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/topLayout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:keepScreenOn="true"
    xmlns:android="http://schemas.android.com/apk/res/android">
  <com.dq.raprproject.barcodescanner.CameraSourcePreview
      android:id="@+id/preview"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      >
    <com.dq.raprproject.barcodescanner.GraphicOverlay
        android:id="@+id/graphicOverlay"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
  </com.dq.raprproject.barcodescanner.CameraSourcePreview>
</LinearLayout>




If you have any kind of problem, Please comment/suggest . Happy Coding .



                                                  NEXT ARTICLE :


                                                 CUSTOM LISTVIEW ANDROID

                                                 CONSTRAINT LAYOUT ANDROID







0 comments:

Post a Comment