Monday 12 January 2015

Barcode and QR code scanner example using ZBar

Screen shots of this example:





Download Source Code


Note: This application done by using Android Studio Tool.

Step 1:

Open activity_main.xml file and Add a Scanner button. you can copy from below.


<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/scannerButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="Scanner" />
</RelativeLayout>

Step 2:

Open MainActivity.Java file Add Scanner button on click event to open Scanner Activity.



package com.kvprasad.zbarbarcodescanner;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;



public class MainActivity extends AppCompatActivity {

    private Button scannerButton;

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

        scannerButton = (Button) findViewById(R.id.scannerButton);

        scannerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(v.getContext(), BarcodeScanner.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


Step 3: 

Crate barcode_scanner.xml layout file in layout folder. you can add Frame Layout for showing camera in that as below.



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

    <FrameLayout
        android:id="@+id/cameraPreview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/ScanButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:text="Scan" />
    </LinearLayout>

</LinearLayout>


Step 4:

Open build.gradle file and add a zbar library is  'me.dm7.barcodescanner:zbar:1.8.2' in dependencies and sync that library.



apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.kvprasad.zbarbarcodescanner"
        minSdkVersion 13
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'me.dm7.barcodescanner:zbar:1.8.2'
}



Step 5:

Crate "CameraPreview.Java" file add the below logic in your file.




package com.kvprasad.zbarbarcodescanner;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;


public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private Camera.PreviewCallback previewCallback;
    private Camera.AutoFocusCallback autoFocusCallback;

    public CameraPreview(Context context, Camera camera,
                         Camera.PreviewCallback previewCb,
                         Camera.AutoFocusCallback autoFocusCb) {
        super(context);
        mCamera = camera;
        previewCallback = previewCb;
        autoFocusCallback = autoFocusCb;

        /*
         * Set camera to continuous focus if supported, otherwise use
         * software auto-focus. Only works for API level >=9.
         */
        /*
        Camera.Parameters parameters = camera.getParameters();
        for (String f : parameters.getSupportedFocusModes()) {
            if (f == Parameters.FOCUS_MODE_CONTINUOUS_PICTURE) {
                mCamera.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                autoFocusCallback = null;
                break;
            }
        }
        */

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);

        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        try {
            mCamera.setPreviewDisplay(holder);
        } catch (IOException e) {
            Log.d("DBG", "Error setting camera preview: " + e.getMessage());
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
 /*
         * If your preview can change or rotate, take care of those events here.
         * Make sure to stop the preview before resizing or reformatting it.
         */
        if (mHolder.getSurface() == null) {
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e) {
            // ignore: tried to stop a non-existent preview
        }

        try {
            // Hard code camera surface rotation 90 degs to match Activity view in portrait
            mCamera.setDisplayOrientation(90);

            mCamera.setPreviewDisplay(mHolder);
            mCamera.setPreviewCallback(previewCallback);
            mCamera.startPreview();
            mCamera.autoFocus(autoFocusCallback);
        } catch (Exception e) {
            Log.d("DBG", "Error starting camera preview: " + e.getMessage());
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }
}


Step 6:

Create "BarcodeScanner.Java" file and add the below logic.




package com.kvprasad.zbarbarcodescanner;

import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;

/**
 * Created by kvprasad on 10/3/2015.
 */
public class BarcodeScanner extends AppCompatActivity {

    private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;

    private Button scanButton;
    private ImageScanner scanner;

    private boolean barcodeScanned = false;
    private boolean previewing = true;

    static {
        System.loadLibrary("iconv");
    }

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

        initControls();
    }

    private void initControls() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();

        // Instance barcode scanner
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(BarcodeScanner.this, mCamera, previewCb,
                autoFocusCB);
        FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
        preview.addView(mPreview);

        scanButton = (Button) findViewById(R.id.ScanButton);

        scanButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (barcodeScanned) {
                    barcodeScanned = false;
                    mCamera.setPreviewCallback(previewCb);
                    mCamera.startPreview();
                    previewing = true;
                    mCamera.autoFocus(autoFocusCB);
                }
            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            releaseCamera();
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * A safe way to get an instance of the Camera object.
     */
    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e) {
        }
        return c;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            if (previewing)
                mCamera.autoFocus(autoFocusCB);
        }
    };

    Camera.PreviewCallback previewCb = new Camera.PreviewCallback() {
        public void onPreviewFrame(byte[] data, Camera camera) {
            Camera.Parameters parameters = camera.getParameters();
            Camera.Size size = parameters.getPreviewSize();

            Image barcode = new Image(size.width, size.height, "Y800");
            barcode.setData(data);

            int result = scanner.scanImage(barcode);

            if (result != 0) {
                previewing = false;
                mCamera.setPreviewCallback(null);
                mCamera.stopPreview();

                SymbolSet syms = scanner.getResults();
                for (Symbol sym : syms) {

                    Log.i("<<<<<<Asset Code>>>>> ",
                            "<<<<Bar Code>>> " + sym.getData());
                    String scanResult = sym.getData().trim();

                    showAlertDialog(scanResult);

                  /*  Toast.makeText(BarcodeScanner.this, scanResult,
                            Toast.LENGTH_SHORT).show();*/

                    barcodeScanned = true;

                    break;
                }
            }
        }
    };

    // Mimic continuous auto-focusing
    Camera.AutoFocusCallback autoFocusCB = new Camera.AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            autoFocusHandler.postDelayed(doAutoFocus, 1000);
        }
    };


    private void showAlertDialog(String message) {

        new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.app_name))
                .setCancelable(false)
                .setMessage(message)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })

                .show();
    }

}


Step 7:

Open "Android Manifest.xml" file initiate BarcodeScanner Activity, and Add  "CAMERA" permission in your manifest.




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

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".BarcodeScanner"
            android:label="@string/app_name" />
    </application>

</manifest>


Step 8:

  If you want Meterial Design for your app, create "color.xml" file in you values folder and add the below colors in it.




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#125688</color>
    <color name="colorPrimaryDark">#125688</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#000000</color>
    <color name="colorAccent">#c8e8ff</color>
</resources>


Step 9:

Open "styles.xml" file and add the below code.




<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
       <!-- <item name="windowNoTitle">true</item>-->
        <item name="windowActionBar">true</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>



121 comments:

  1. Very Good Tutorial.Keep it Up.

    ReplyDelete
  2. if Somebody Facing Error after adding [ CameraView.Java ] class then please Remove the Word Public from that class other then i will gives you Error.

    ReplyDelete
  3. So

    public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback
    { }

    Will be

    class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { }

    Means Word Public will be remove.

    ReplyDelete
  4. CameraPreview class was provided zbar library, based on your requirements you can modify it.

    Thanks for your comments.

    ReplyDelete
  5. Thanks for your tutorial. I want try to use it, but i cann't download sourse and libs files. Can you reload it?

    ReplyDelete
    Replies
    1. Please @Venkata Prasad upload the source and lib files. i cant download from the link you provided.

      Delete
    2. to Dmitriy: did you have any success with this code sample?

      Delete
  6. Please @Venkata Prasad upload the source and lib files. i cant download from the link you provided.

    ReplyDelete
  7. I updated source link, please check it.

    ReplyDelete
  8. Sir but it is not scanning any thing and not giving any output

    ReplyDelete
    Replies
    1. try multiple barcodes in google, result will show in toast message

      Delete
  9. hi,
    I put all jars in libs directory, compile& synchro them and still no luck :(

    07-17 15:38:19.837 14167-14167/com.infodat.zbarscannerexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.ExceptionInInitializerError
    at com.infodat.zbarscannerexample.MainActivity.initControls(MainActivity.java:50)
    at com.infodat.zbarscannerexample.MainActivity.onCreate(MainActivity.java:40)
    at android.app.Activity.performCreate(Activity.java:5244)
    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.UnsatisfiedLinkError: Cannot load library: link_image[1893]: 144 could not load needed library 'libiconv.so' for 'libzbarjni.so' (load_library[1095]: Library 'libiconv.so' not found)


    ReplyDelete
    Replies
    1. please check once after adding jar files in libs folder, you have to sync those jar files in build.gradle file.


      this is complete build.gradle file


      apply plugin: 'com.android.application'

      android {
      compileSdkVersion 21
      buildToolsVersion "21.1.2"

      defaultConfig {
      applicationId "com.infodat.zbarscannerexample"
      minSdkVersion 15
      targetSdkVersion 21
      versionCode 1
      versionName "1.0"
      }
      buildTypes {
      release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
      }
      }
      }

      dependencies {
      compile fileTree(dir: 'libs', include: ['*.jar'])
      compile 'com.android.support:appcompat-v7:21.0.3'
      compile files('libs/zbar.jar')

      }

      Delete
  10. same error
    line 50 is scanner = new ImageScanner();

    ReplyDelete
  11. I'm trying to implement this feature inside one existing app that I have, so I'm basically creating an Intent and calling the ScannerActivity (which is the MainActivity.java in this example) and returning the scanned result through the Intent. When the QR Code is successfully scanned, I'm finishing the Activity and it works just fine. The problem is when I try to start the Activity again, I'm getting a NullPointerException from the CameraPreview. Any ideas on what is happening?

    This is my version of the runnable method:

    private Runnable doAutoFocus = new Runnable() {
    public void run() {
    if (previewing)
    mCamera.autoFocus(autoFocusCB);
    }
    };

    Camera.PreviewCallback previewCb = new Camera.PreviewCallback() {
    public void onPreviewFrame(byte[] data, Camera camera) {
    Camera.Parameters parameters = camera.getParameters();
    Camera.Size size = parameters.getPreviewSize();

    Image barcode = new Image(size.width, size.height, "Y800");
    barcode.setData(data);

    int result = scanner.scanImage(barcode);

    if (result != 0)
    {
    previewing = false;
    mCamera.setPreviewCallback(null);
    mCamera.stopPreview();

    SymbolSet syms = scanner.getResults();
    for (Symbol sym : syms)
    {

    Log.i("<<<<<>>>> ",
    "<<<>> " + sym.getData());
    String scanResult = sym.getData().trim();

    intent.putExtra(ApplicationActivity.SCAN_RESULT, scanResult);

    //Toast.makeText(ScannerActivity.this, "Code Scanned!", Toast.LENGTH_SHORT).show();

    barcodeScanned = true;

    break;
    }

    setResult(RESULT_OK, intent);
    finish();
    }
    }
    };

    // Mimic continuous auto-focusing
    Camera.AutoFocusCallback autoFocusCB = new Camera.AutoFocusCallback() {
    public void onAutoFocus(boolean success, Camera camera) {
    autoFocusHandler.postDelayed(doAutoFocus, 1000);
    }
    };

    And this is how I'm starting the Activity from the main activity of my app and getting the results from it:

    public void startScannerActivity()
    {
    Intent intent = new Intent(this, ScannerActivity.class);
    startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    if (resultCode == RESULT_OK)
    {
    String subject = data.getStringExtra(SCAN_RESULT);
    Toast.makeText(this, subject + " scanned", Toast.LENGTH_SHORT).show();
    showReviewsPage(HomePage.NAME, subject);
    }
    else if(resultCode == RESULT_CANCELED)
    {
    Toast.makeText(this, "Camera unavailable", Toast.LENGTH_SHORT).show();
    }
    }

    I appreciate any help you can give me!

    Cheers ;)

    ReplyDelete
    Replies
    1. at the finishing your activity you have to release camera

      private void releaseCamera() {
      if (mCamera != null) {
      previewing = false;
      mCamera.setPreviewCallback(null);
      mCamera.release();
      mCamera = null;
      }
      }
      call this method in onStop() method

      this will help

      Delete
    2. Nope. It didn't.

      Attempt to invoke virtual method 'void android.hardware.Camera.setPreviewDisplay(android.view.SurfaceHolder)' on a null object reference

      Only using my phone's "back" button works. Clicking the back arrow on the upper menu bar and then starting scanner again crashes the application.

      Delete
    3. OK! Nevermind. I used onPause() instead of onStop() and this solved problem. The onStop() was just too slow and didn't release the camera on time (I click too fast :P).

      Delete
    4. Hi ! how did you get the intent in the Barcode class ?

      Delete
    5. Hi exparts,
      I am facing similar problem and can not able to solve it for the last two days. I have one textview and one button in my home activity. When i click on the button the the camera starts preveiwing and scan the qrcode and return the scanned value to my home activity successfully. But the problem is when i click 2nd time again then it shows unfortunetly stop error. I have used try ..... catch block but no error throughing. I am new in android programming. Pls me to fix the problem. Many many advanced thanks.

      Hkabir

      Delete
    6. Hi exparts,
      I am facing similar problem and can not able to solve it for the last two days. I have one textview and one button in my home activity. When i click on the button the the camera starts preveiwing and scan the qrcode and return the scanned value to my home activity successfully. But the problem is when i click 2nd time again then it shows unfortunetly stop error. I have used try ..... catch block but no error throughing. I am new in android programming. Pls me to fix the problem. Many many advanced thanks.

      Hkabir

      Delete
  12. Thanks for such a Great tutorial sir!

    ReplyDelete
  13. Hi, Great tutorial!

    But the link https://www.dropbox.com/s/kd5w5sfolj80d5a/libs.rar?dl=0 is not working. Can you send a new one?

    ReplyDelete
  14. Hi,thanks for your code.
    I copy your code to make a new project but I have a question,why the "cameraPreview" this FrameLayout can show camera screen that always black?

    ReplyDelete
    Replies
    1. sorry...
      It's why the "cameraPreview" this FrameLayout cannot show camera screen that always black?
      my english is no good

      Delete
    2. Thanks,I find
      take this:

      change to :

      will be good.

      Delete
    3. take this:
      uses-feature android:name="android.permission.CAMERA"
      feature
      change to:
      permission

      Delete
  15. android.hardware.Camera is deprecated was the reason why the app force close?

    ReplyDelete
    Replies
    1. No, It is working even though camera API deprecated. Your App is crashing with some other reason. please check once again.

      Delete
    2. on Android 6.0, you have to give permission manually to use camera, so, it should be asked before using camera if app doesn't have permission. That was my problem.

      Delete
  16. Hello,

    I copied exactly same as your code, and I have no errors. When I build and run it, it works fine; however, on emulator screen, i receive this message: "Unfortunately, My Application has stopped.

    ReplyDelete
    Replies
    1. Also, I checked every aspect of code over and over, and I have no errors. Build and compiles fine, but application seems to crash.

      Delete
    2. Hi,
      This app not work in emulator because it needs camera. Emulator doesn't have camera feature. So you can test in real device.

      Delete
    3. Hello,

      I use new updated code that you post, but get this following error:

      Error:Execution failed for task ':app:dexDebug'.
      > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2

      What does this error mean?

      Delete
    4. Please remove jar files (zbar related) from libs floder.

      You must check if the same JAR is being imported again. In my case there was a class inside a jar which was getting imported in another jar. So just check if the any lib / class file is being included twice in the whole project!

      Delete
    5. This comment has been removed by the author.

      Delete
    6. Hi. I have the same error, "Unfortunately, My Application has stopped" when I tested it on my phone.

      Delete
  17. The example doesn't work with the new Google Camera update, I think we need to use the android.hardware.camera2 API

    ReplyDelete
    Replies
    1. yes, but Camera2 API not supporting lower versions.

      Delete
  18. I have a problem and app crash on scanner = new ImageScanner();
    what i can do?

    ReplyDelete
    Replies
    1. Same problem. the code is no working

      Delete
  19. Hello! Thank you so much for such a great tutorial!

    When I run my app on my nexus 5, the app is forced to stop every time the camera reaches a QR code.

    So, after previewing is set to false, the app stopped.

    The Logcat says java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

    I am using the from example in Zbar Github page, because for some reasons, my app.AlertDialog, app.AppCompatActivity cannot be found.

    Could you please give any help?

    Thank you in advance!

    ReplyDelete
  20. Hi, first, thanks for your wonderful tutorial, it was a very helpfull for me.
    My app is working fine, but when the display are in landscape mode the app is crash. How can i fix that.

    ReplyDelete
    Replies
    1. Is ok now.... i make the refactor in the class for make the change in the rotation. Again... thanks for post

      Delete
    2. how did you solve it plz? i have the same problem
      thank u

      Delete
  21. Hello Venkata!

    Thank you for a very good tutorial. However I bumped into some problems in spite of android-studio compiling the code properly.
    When I hit the SCANNER button app stops to work.
    I get the message from logcat: Unable to find explicit activity class {com.myapp.android.qrscanner2/com.myapp.android.qrscanner2.BarcodeScanner}; have you declared this activity in your AndroidManifest.xml? I checked the manifest file and found . Is that proper declaration of the main activity? I'd be very happy to make this app work. Thanks.

    ReplyDelete
  22. Sir, ive already run it on real device but i got this error "unfortunately, Scanner has stopped"

    any idea on what should i do?

    ReplyDelete
  23. Sir, the app is getting crash on clicking the button. Following is the log:

    13239-13239/com.kvprasad.zbarbarcodescanner E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.kvprasad.zbarbarcodescanner, PID: 13239
    java.lang.UnsatisfiedLinkError: dlopen failed: /data/app/com.kvprasad.zbarbarcodescanner-1/lib/arm/libzbarjni.so: has text relocations
    at java.lang.Runtime.loadLibrary(Runtime.java:372)
    at java.lang.System.loadLibrary(System.java:1076)
    at net.sourceforge.zbar.ImageScanner.(Unknown Source)
    at com.kvprasad.zbarbarcodescanner.BarcodeScanner.initControls(BarcodeScanner.java:52)
    at com.kvprasad.zbarbarcodescanner.BarcodeScanner.onCreate(BarcodeScanner.java:42)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

    ReplyDelete
  24. How to scan QR code using this? Please suggest

    ReplyDelete
  25. ive found the solution..
    android studio unable to find the file (.so)

    therefore, i ve to add these codes inside Barcode Activity.java



    public class BarcodeActivity extends AppCompatActivity {

    private Button scannerButton;
    //these 3 lines below...
    static {
    System.loadLibrary("iconv");
    }

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

    scannerButton = (Button) findViewById(R.id.scannerButton);

    scannerButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    Intent intent = new Intent(v.getContext(), BarcodeScanner.class);
    startActivity(intent);
    }
    });
    }

    ReplyDelete
  26. working fine......
    but got confused when the app crashed after pressing on the "Scanner" button.....
    the following description might help a lot of people who are going to use this code....
    debugging showed that the Camera object is null after calling the CameraView constructor....... this happened cause I opened the app while my tablet was in landscape orientation..... but switching it to portrait solved the problem.... created a lot of confusion at the first place and wasted about an hour with this unwanted error.... beside this problem, everything is working great....
    Happy Coding Everyone....

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. When i run the code,the application suddenly stop when i click the scan button.When i looked through the code ,in the file camerapreview.java ,there is a redline under the import.android.hardware.camera

    ReplyDelete
  29. It works, but how to open a link from a qr code?

    ReplyDelete
  30. It works, but how to open a link from a qr code?

    ReplyDelete
  31. Hi,
    I have followed your step.And which is scanning google barcode images.But when i scan my materiel barcode(example: chocolate packet barcode) it is not scanning.Even i couldn't view bar code clearly. Thanx in adavnce

    ReplyDelete
  32. open the camera but scan button not worked

    ReplyDelete
  33. hi, thanks for the tutorial.

    i got this error using xperia L, works fine in other devices. please help.

    02-08 04:12:05.196 28223-28223/? E/AndroidRuntime: Caused by: java.lang.UnsatisfiedLinkError: Cannot load library: soinfo_link_image(linker.cpp:1635): could not load library "libiconv.so" needed by "libzbarjni.so"; caused by load_library(linker.cpp:745): library "libiconv.so" not found

    ReplyDelete
    Replies
    1. I have the same problem, did you solve it?

      Delete
  34. Error:

    java.lang.ExceptionInInitializerError
    at BarcodeScanner.initControls(BarcodeScanner.java:55)
    atBarcodeScanner.onCreate(BarcodeScanner.java:43)

    ReplyDelete
    Replies
    1. try with this code adding before onCreate method

      static {
      System.loadLibrary("iconv");
      }

      Delete
  35. hello..i have same issue..this code is working properly in android 5.0 or above..but in other version my app unfortunately stop..how to solve it ..please
    thanku

    ReplyDelete
    Replies
    1. try with this code adding before onCreate method

      static {
      System.loadLibrary("iconv");
      }


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

      initControls();
      }

      Delete
    2. that load library also crashing the app

      Delete
  36. This comment has been removed by the author.

    ReplyDelete
  37. This comment has been removed by the author.

    ReplyDelete
  38. Hi, I would like to edit this so that the barcodes can be continuously scanned, without having to click the button to scan the next qr code. Thank you very much!

    ReplyDelete
  39. sir plz upload source code for reading qr codes::?

    ReplyDelete
  40. Everything about barcode scanners http://barcode.gr/

    ReplyDelete
  41. The scanner crashes in android marshmallow(6.0) why is it so...?

    ReplyDelete
    Replies
    1. Marshmallow takes camera permission at run time only.

      for this you have to give either manually or through programmatically.

      For Now you can enable camera permission manually.

      Settings--> Apps--> Click on your App--> Click on Permissions--> enable camera permission.

      Now open your app its working.

      Delete
  42. I am sorry for being a real noob but i am really new in android development. Once download the source file, where do i put the source file?

    ReplyDelete
  43. app goes to crash after tapping on scan button

    ReplyDelete
  44. do you tutorial on qr code ?

    ReplyDelete
  45. not working on marshmallow...can u pls tell me do u have any fix?

    ReplyDelete
    Replies
    1. Marshmallow takes camera permission at run time only.

      for this you have to give either manually or through programmatically.

      For Now you can enable camera permission manually.

      Settings--> Apps--> Click on your App--> Click on Permissions--> enable camera permission.

      Now open your app its working.




      Delete
  46. I am sorry.. but i would like to know which variable holds the qr code value after scan.. because i would like to use it...

    ReplyDelete
    Replies
    1. nvm sorry... got it.. scanresult in String...

      Delete
  47. I really like the posts you make and this being reperensi I created my lecture, can you teach me to make the barcode number scanernya. ??
    bales to please email me ujangrahmat39@gmail.com

    ReplyDelete
  48. how to start a new activity, after scanning the barcode ? Thanks

    ReplyDelete
  49. Hi! First of all, this is a wonderful tutorial, thank you so much for this!

    I am trying to develop an app that scans QR codes and I have been trying out your code, but I am getting an error that I cannot fix! I am using Android Studio and using an emulator (Nexus 5X API 23). The app opens a camera preview when clicking the "Scanner" button, but the camera preview is all black and I get an error message in logcat. I know that in one of the comments you said that the camera on an emulator does not work, but when I open the phone's camera app, I see myself through my webcam without a problem..

    Here is my error:
    05-14 21:01:44.218 22440-22543/com.example.nita.cyberworldexpedition E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaa397190
    (this number of the buffer changes, but it always starts with 0xaa39)

    I hope you can help :)

    ReplyDelete
  50. Hi All nice tutorials bUt show link not click link

    ReplyDelete
  51. error in line 40 below the line..

    static {
    System.loadLibrary("iconv");
    }


    this is error:

    java.lang.UnsatisfiedLinkError: dlopen failed: /data/app/com.company.comanda-1/lib/arm/libiconv.so: has text relocations
    at java.lang.Runtime.loadLibrary(Runtime.java:372)
    at java.lang.System.loadLibrary(System.java:1076)
    at com.company.comanda.activity.BarcodeScanner.(BarcodeScanner.java:40)

    ReplyDelete
  52. i did download of project sample.. is some error.. :-(

    ReplyDelete
  53. Hi, I'm new in android programming and I wanna create an app that is need QR-code scanner but I don't know how to add zbar lib to android studio :(

    ReplyDelete
  54. I am scanning QR codes that contain a URL. How can I alter the code to so the URL that has been scanned is clickable.

    ReplyDelete
  55. I need an example with barcodeScanner that send string to URL. Tks

    ReplyDelete
  56. This comment has been removed by the author.

    ReplyDelete
  57. the camera has problem is shown android.hardware.camera is deprecated and it cannot run on my devices API23 after click scanner button
    Can anyone tell me how to solve the camera? i'm already enable the camera permission

    ReplyDelete
  58. Hi, thanx for the tutorial, this is what i was trying, have an issue, i am able to scan barcode, the problem is it is showing wrong data sometimes.......why

    ReplyDelete
  59. thank you bro! great tutorial

    ReplyDelete
  60. Anyone used camera2 API and got it working?

    ReplyDelete
  61. Can u help me how to get correct bar code result, the scanned number what it is showing is wrong

    ReplyDelete
  62. i don't see any .SO file in the project could u please tell me about that

    ReplyDelete
  63. Hi i tried your code but getting some exceptions like
    11-13 21:50:20.594 10208-10208/agent.com.agentapplication D/DBG: Error setting camera preview: Attempt to invoke virtual method 'void android.hardware.Camera.setPreviewDisplay(android.view.SurfaceHolder)' on a null object reference
    11-13 21:50:20.594 10208-10208/agent.com.agentapplication D/DBG: Error starting camera preview: Attempt to invoke virtual method 'void android.hardware.Camera.setDisplayOrientation(int)' on a null object reference

    ReplyDelete
  64. I have Error for this sample code , it is working fine in 5.0 but not for the version 6.0 and above, Having an error like ---


    --------- beginning of crash
    11-22 18:47:57.381 18274-18274/com.kvprasad.zbarbarcodescanner E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.kvprasad.zbarbarcodescanner, PID: 18274
    java.lang.UnsatisfiedLinkError: dlopen failed: /data/app/com.kvprasad.zbarbarcodescanner-1/lib/arm/libiconv.so: has text relocations
    at java.lang.Runtime.loadLibrary(Runtime.java:372)
    at java.lang.System.loadLibrary(System.java:1076)
    at com.kvprasad.zbarbarcodescanner.BarcodeScanner.(BarcodeScanner.java:38)
    at java.lang.Class.newInstance(Native Method)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1090)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

    ReplyDelete
  65. i used the above code. its fine working on all devices, but in marshmellow its getting crash, i have added the permissions manuaaly at run time but still its getting stopped.

    ReplyDelete
  66. hi ... how can i scan the content of qr code ? for example, the content of qr code is http://google.com and when scan with the scanner, it will redirect to google page. can you give suggestion ?

    ReplyDelete
  67. Hi. I got this error i don't what was the issue
    Attempt to invoke virtual method 'void android.hardware.Camera.setPreviewDisplay(android.view.SurfaceHolder)' on a null object reference

    ReplyDelete
  68. Does the same code works for QR CODE Scanning also...please respond.

    ReplyDelete
  69. Need help! Gives me errors in Main_Activity on the line of: menu.menu_main

    and on : id.action_settings

    Please help!!

    ReplyDelete
  70. Thanks, it working fine.But it can not working in android version 6.

    ReplyDelete
  71. Hello sir,
    My app is crashing when click on scan button in released version while working fine in debug apk
    I have added proguard rules
    java.lang.Runtime.loadLibrary (Runtime.java:372)
    java.lang.System.loadLibrary (System.java:1076)
    com.plasmahc.plasmaforensic.examinebarcode.BarcodeScanner. ()
    java.lang.Class.newInstance (Class.java)
    android.app.Instrumentation.newActivity (Instrumentation.java:1072)
    android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2473)
    android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2667)
    android.app.ActivityThread.-wrap11 (ActivityThread.java)
    android.app.ActivityThread$H.handleMessage (ActivityThread.java:1494)
    android.os.Handler.dispatchMessage (Handler.java:111)
    android.os.Looper.loop (Looper.java:207)
    android.app.ActivityThread.main (ActivityThread.java:5776)
    java.lang.reflect.Method.invoke (Method.java)
    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:789)
    com.android.internal.os.ZygoteInit.main (ZygoteInit.java:679)


    Please help

    ReplyDelete
  72. This comment has been removed by the author.

    ReplyDelete
  73. Hi, Thanks for the tutorial.
    The code which you have provided was crashing and here is log

    linker: /data/app/com.kvprasad.zbarbarcodescanner-2/lib/arm/libiconv.so: has text relocations
    06-13 11:50:41.002 30570-30570/com.kvprasad.zbarbarcodescanner D/AndroidRuntime: Shutting down VM
    06-13 11:50:41.002 30570-30570/com.kvprasad.zbarbarcodescanner E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.kvprasad.zbarbarcodescanner, PID: 30570
    java.lang.UnsatisfiedLinkError: dlopen failed: /data/app/com.kvprasad.zbarbarcodescanner-2/lib/arm/libiconv.so: has text relocations
    at java.lang.Runtime.loadLibrary(Runtime.java:372)
    at java.lang.System.loadLibrary(System.java:1076)
    at com.kvprasad.zbarbarcodescanner.BarcodeScanner.(BarcodeScanner.java:38)
    at java.lang.Class.newInstance(Native Method)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1090)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

    ReplyDelete
  74. It is not working with bar code but works fine with QR code.... anybody to solve issue...

    ReplyDelete
  75. well done ,how can I improve the speed ? it take a lot of time for detecting any do you any idea for improving speed????

    ReplyDelete
  76. error no encuentra la libreria....
    /data/app/com.kvprasad.zbarbarcodescanner-2/lib/arm/libiconv.so ?
    alguna solucion?

    ReplyDelete
  77. Whether it is Android or PC, I found a barcode scanner lib, very easy to use, and the recognition is very fast, very accurate, and shared with everyone.

    ReplyDelete
  78. Hi sir Sometimes It is scanning text outside instead of qr or barcode .Can you tell me how to solve it

    ReplyDelete
  79. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. z code system discount

    ReplyDelete
  80. I am questionable where you stand to have your information, but an unfathomable point. I must take a little time understanding an entire parcel more or more information more. Much recognized for shocking data I was attempting to discover these centers of captivated for my mission. Best 3d model Denver, Colorado

    ReplyDelete
  81. Those peculiar looking shape-filled squares you've been seeing beginning late may not take after a great deal, yet they are likely the going with colossal thing in appearing and venturing for U.S. affiliations. With a prompt snap of a mobile phone, that unassuming sensible sends noteworthy information immediately to anticipated customers, which for express affiliations can mean the partition between a game-plan or a leave. QR Code Creator

    ReplyDelete
  82. I have been searching to find a comfort or effective procedure to complete this process and I think this is the most suitable way to do it effectively. slice invite code

    ReplyDelete
  83. Do you believe in long term investement . One of the option of doing investement is by investing in Crypto currencies. You can invest in Fudxcoin company that deals in the selling and purchasing of Crypto Currency. It is a reliable company. One need not doubt in investing in it as i have also bought crypto currency from it and feeling very satisfied with their services.
    crypto currency block chain technology

    ReplyDelete
  84. Our experts have reviewed the best stock trading scanners and screeners on the market. Finviz Scanner

    ReplyDelete

Spinner example using AppCompatSpinner widget

          When we have a requirement to use spinner(drop down) to show list of objects in your application. Here we will see how to use Ap...