Screen shots of this example:
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.
Step 2:
Open MainActivity.Java file Add Scanner button on click event to open Scanner Activity.
Step 3:
Crate barcode_scanner.xml layout file in layout folder. you can add Frame Layout for showing camera in that as below.
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.
Step 5:
Crate "CameraPreview.Java" file add the below logic in your file.
Step 6:
Create "BarcodeScanner.Java" file and add the below logic.
Step 7:
Open "Android Manifest.xml" file initiate BarcodeScanner Activity, and Add "CAMERA" permission in your 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.
Step 9:
Open "styles.xml" file and add the below code.
Download Source Code
Note: This application done by using Android Studio Tool.
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>
Very Good Tutorial.Keep it Up.
ReplyDeleteif Somebody Facing Error after adding [ CameraView.Java ] class then please Remove the Word Public from that class other then i will gives you Error.
ReplyDeleteSo
ReplyDeletepublic class CameraPreview extends SurfaceView implements SurfaceHolder.Callback
{ }
Will be
class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { }
Means Word Public will be remove.
CameraPreview class was provided zbar library, based on your requirements you can modify it.
ReplyDeleteThanks for your comments.
Thanks for your tutorial. I want try to use it, but i cann't download sourse and libs files. Can you reload it?
ReplyDeletePlease @Venkata Prasad upload the source and lib files. i cant download from the link you provided.
Deleteto Dmitriy: did you have any success with this code sample?
DeletePlease @Venkata Prasad upload the source and lib files. i cant download from the link you provided.
ReplyDeleteI updated source link, please check it.
ReplyDeleteSir but it is not scanning any thing and not giving any output
ReplyDeletetry multiple barcodes in google, result will show in toast message
Deletehi,
ReplyDeleteI 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)
please check once after adding jar files in libs folder, you have to sync those jar files in build.gradle file.
Deletethis 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')
}
same error
ReplyDeleteline 50 is scanner = new ImageScanner();
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?
ReplyDeleteThis 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 ;)
at the finishing your activity you have to release camera
Deleteprivate void releaseCamera() {
if (mCamera != null) {
previewing = false;
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
call this method in onStop() method
this will help
Nope. It didn't.
DeleteAttempt 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.
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).
DeleteHi ! how did you get the intent in the Barcode class ?
DeleteHi exparts,
DeleteI 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
Hi exparts,
DeleteI 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
Thanks for such a Great tutorial sir!
ReplyDeletenice work brother ! :)
ReplyDeleteHi, Great tutorial!
ReplyDeleteBut the link https://www.dropbox.com/s/kd5w5sfolj80d5a/libs.rar?dl=0 is not working. Can you send a new one?
Hi,thanks for your code.
ReplyDeleteI 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?
sorry...
DeleteIt's why the "cameraPreview" this FrameLayout cannot show camera screen that always black?
my english is no good
Thanks,I find
Deletetake this:
change to :
will be good.
take this:
Deleteuses-feature android:name="android.permission.CAMERA"
feature
change to:
permission
android.hardware.Camera is deprecated was the reason why the app force close?
ReplyDeleteNo, It is working even though camera API deprecated. Your App is crashing with some other reason. please check once again.
Deleteon 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.
DeleteHello,
ReplyDeleteI 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.
Also, I checked every aspect of code over and over, and I have no errors. Build and compiles fine, but application seems to crash.
DeleteHi,
DeleteThis app not work in emulator because it needs camera. Emulator doesn't have camera feature. So you can test in real device.
Hello,
DeleteI 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?
Please remove jar files (zbar related) from libs floder.
DeleteYou 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!
This comment has been removed by the author.
DeleteHi. I have the same error, "Unfortunately, My Application has stopped" when I tested it on my phone.
DeleteThe example doesn't work with the new Google Camera update, I think we need to use the android.hardware.camera2 API
ReplyDeleteyes, but Camera2 API not supporting lower versions.
DeleteI have a problem and app crash on scanner = new ImageScanner();
ReplyDeletewhat i can do?
Same problem. the code is no working
DeleteHello! Thank you so much for such a great tutorial!
ReplyDeleteWhen 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!
Hi, first, thanks for your wonderful tutorial, it was a very helpfull for me.
ReplyDeleteMy app is working fine, but when the display are in landscape mode the app is crash. How can i fix that.
Is ok now.... i make the refactor in the class for make the change in the rotation. Again... thanks for post
Deletehow did you solve it plz? i have the same problem
Deletethank u
Hello Venkata!
ReplyDeleteThank 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.
Sir, ive already run it on real device but i got this error "unfortunately, Scanner has stopped"
ReplyDeleteany idea on what should i do?
Sir, the app is getting crash on clicking the button. Following is the log:
ReplyDelete13239-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)
How to scan QR code using this? Please suggest
ReplyDeleteive found the solution..
ReplyDeleteandroid 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);
}
});
}
working fine......
ReplyDeletebut 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....
This comment has been removed by the author.
ReplyDeleteWhen 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
ReplyDeleteIt works, but how to open a link from a qr code?
ReplyDeleteIt works, but how to open a link from a qr code?
ReplyDeleteit's me, done
DeleteCould you tell me how you did it?
DeleteHi,
ReplyDeleteI 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
open the camera but scan button not worked
ReplyDeletehi, thanks for the tutorial.
ReplyDeletei 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
I have the same problem, did you solve it?
DeleteError:
ReplyDeletejava.lang.ExceptionInInitializerError
at BarcodeScanner.initControls(BarcodeScanner.java:55)
atBarcodeScanner.onCreate(BarcodeScanner.java:43)
try with this code adding before onCreate method
Deletestatic {
System.loadLibrary("iconv");
}
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
ReplyDeletethanku
try with this code adding before onCreate method
Deletestatic {
System.loadLibrary("iconv");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barcode_scanner);
initControls();
}
that load library also crashing the app
DeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHi, 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!
ReplyDeletesir plz upload source code for reading qr codes::?
ReplyDeleteEverything about barcode scanners http://barcode.gr/
ReplyDeleteThe scanner crashes in android marshmallow(6.0) why is it so...?
ReplyDeleteMarshmallow takes camera permission at run time only.
Deletefor 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.
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?
ReplyDeleteapp goes to crash after tapping on scan button
ReplyDeletedo you tutorial on qr code ?
ReplyDeletenot working on marshmallow...can u pls tell me do u have any fix?
ReplyDeleteMarshmallow takes camera permission at run time only.
Deletefor 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.
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...
ReplyDeletenvm sorry... got it.. scanresult in String...
DeleteI really like the posts you make and this being reperensi I created my lecture, can you teach me to make the barcode number scanernya. ??
ReplyDeletebales to please email me ujangrahmat39@gmail.com
how to start a new activity, after scanning the barcode ? Thanks
ReplyDeleteHi! First of all, this is a wonderful tutorial, thank you so much for this!
ReplyDeleteI 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 :)
Hi All nice tutorials bUt show link not click link
ReplyDeleteerror in line 40 below the line..
ReplyDeletestatic {
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)
i did download of project sample.. is some error.. :-(
ReplyDeleteHi, 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 :(
ReplyDeleteproblem solved, tnx :)
DeleteI am scanning QR codes that contain a URL. How can I alter the code to so the URL that has been scanned is clickable.
ReplyDeleteI need an example with barcodeScanner that send string to URL. Tks
ReplyDeleteThis comment has been removed by the author.
ReplyDeletethe camera has problem is shown android.hardware.camera is deprecated and it cannot run on my devices API23 after click scanner button
ReplyDeleteCan anyone tell me how to solve the camera? i'm already enable the camera permission
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
ReplyDeletethank you bro! great tutorial
ReplyDeleteAnyone used camera2 API and got it working?
ReplyDeleteCan u help me how to get correct bar code result, the scanned number what it is showing is wrong
ReplyDeletei don't see any .SO file in the project could u please tell me about that
ReplyDeleteHi i tried your code but getting some exceptions like
ReplyDelete11-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
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 ---
ReplyDelete--------- 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)
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.
ReplyDeletehi ... 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 ?
ReplyDeleteHi. I got this error i don't what was the issue
ReplyDeleteAttempt to invoke virtual method 'void android.hardware.Camera.setPreviewDisplay(android.view.SurfaceHolder)' on a null object reference
Does the same code works for QR CODE Scanning also...please respond.
ReplyDeleteNeed help! Gives me errors in Main_Activity on the line of: menu.menu_main
ReplyDeleteand on : id.action_settings
Please help!!
Thanks, it working fine.But it can not working in android version 6.
ReplyDeleteHello sir,
ReplyDeleteMy 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
This comment has been removed by the author.
ReplyDeleteHi, Thanks for the tutorial.
ReplyDeleteThe 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)
Nice post...Gud to read.
ReplyDeletetop android app development companies | professional custom website design company
It is not working with bar code but works fine with QR code.... anybody to solve issue...
ReplyDeletewell done ,how can I improve the speed ? it take a lot of time for detecting any do you any idea for improving speed????
ReplyDeleteerror no encuentra la libreria....
ReplyDelete/data/app/com.kvprasad.zbarbarcodescanner-2/lib/arm/libiconv.so ?
alguna solucion?
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.
ReplyDeleteHi sir Sometimes It is scanning text outside instead of qr or barcode .Can you tell me how to solve it
ReplyDeletePositive 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
ReplyDeleteI 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
ReplyDeleteThose 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
ReplyDeleteI 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
ReplyDeleteDo 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.
ReplyDeletecrypto currency block chain technology
Our experts have reviewed the best stock trading scanners and screeners on the market. Finviz Scanner
ReplyDeleteThis is very unique blog!
ReplyDeleteThank you for the share with us.
best doodledoos