android – Getting Camera error in Zxing Barcode Application-ThrowExceptions

Exception or error:

I am trying to use Zxing Library for developing a barcode scanner.

My activity is as follows:

public class Scanner extends Activity {  

    private static final String PACKAGE = "com.test.scan";  
    private static final String SCANNER = "com.google.zxing.client.android.SCAN";  
    private static final String SCAN_FORMATS = "UPC_A,UPC_E,EAN_8,EAN_13,CODE_39,CODE_93,CODE_128";  
    private static final String SCAN_MODE = "QR_CODE_MODE";  
    public static final int REQUEST_CODE = 1;  

    @Override  
    public void onCreate(Bundle icicle) {  
        super.onCreate(icicle);  

        setContentView(R.layout.main);  

         Button ok;  
         ok = (Button) findViewById(R.id.b1);  
         ok.setOnClickListener(new View.OnClickListener() {  

             public void onClick(View v) {  

                Intent scanIntent = new Intent(SCANNER);  
                scanIntent.setPackage(PACKAGE);  
                scanIntent.addCategory(Intent.CATEGORY_DEFAULT);  
                scanIntent.putExtra("SCAN_FORMATS", SCAN_FORMATS);  
                scanIntent.putExtra("SCAN_MODE", SCAN_MODE);  
                try {  
                    startActivityForResult(scanIntent, REQUEST_CODE);  
                } catch (ActivityNotFoundException e) {  
                     // TODO: Exception handling  
                }  
            }  

        });  
     }

Also manifest file:

    <activity android:name=".Scanner"
            android:screenOrientation="landscape"   android:configChanges="orientation|keyboardHidden"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:windowSoftInputMode="stateAlwaysHidden">  
                 <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>

</activity>

<activity android:name="com.google.zxing.client.android.CaptureActivity"
                android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden"  
                android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                android:windowSoftInputMode="stateAlwaysHidden">
                <intent-filter>
                    <action     android:name="com.google.zxing.client.android.SCAN" />
                    <category    android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </activity>
            <activity android:name="com.google.zxing.client.android.PreferencesActivity"
                android:label="@string/preferences_name">
            </activity>
            <activity android:name="com.google.zxing.client.android.HelpActivity"
                android:screenOrientation="user">
                <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </activity>
            <activity android:name="com.google.zxing.client.android.share.ShareActivity"
                android:label="@string/share_name" android:screenOrientation="user"
                android:theme="@android:style/Theme.Light">
                <intent-filter>
                    <action android:name="com.google.zxing.client.android.SHARE" />
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </activity>
    <uses-permission android:name="android.permission.CAMERA"

But I am getting the following error:

“Sorry, the Android camera encountered a problem. You may need to restart the device”.

I have followed few blogs.

Log:

   Unexpected error initializating camera  
    01-27 10:40:48.281: WARN/CaptureActivity(1007): java.lang.RuntimeException: Fail to connect to camera service  
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at android.hardware.Camera.native_setup(Native Method)  
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at android.hardware.Camera.<init>(Camera.java:185)  
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at android.hardware.Camera.open(Camera.java:165)
   01-27 10:40:48.281: WARN/CaptureActivity(1007):     at com.google.zxing.client.android.camera.CameraManager.openDriver(CameraManager.java:126)
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at com.google.zxing.client.android.CaptureActivity.initCamera(CaptureActivity.java:606)  
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at com.google.zxing.client.android.CaptureActivity.surfaceCreated(CaptureActivity.java:346)   
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at android.view.SurfaceView.updateWindow(SurfaceView.java:532)  
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at android.view.SurfaceView.dispatchDraw(SurfaceView.java:339) 
How to solve:

This means the device returned null from Camera.open() and it shouldn’t ever do that. It’s treated as a device bug. I am not sure how you would debug why it is doing this, but that’s the cause.

The only time I have seen this happen consistently is on Android 2.2 devices that have a front camera, only. The API for accessing a front camera only appeared in Android 2.3, and the previous Camera.open() API method may only return a rear-facing camera. So these return null. And it is a device bug, really, since they really need to be running Android 2.3 to let apps use a front camera.

###

For Android 6+, because of the “permission” issue, If you got the message “Sorry, the camera encountered a problem. You may need to restart the device.”, go to Settings – Apps – find “your app name” – select Permissions and switch on “Camera”.

###

permission of camera

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

is not at proper place. it should be after application tag.

###

I faced a similar problem.
While testing on Android M,the camera requires runtime permission. Adding this answer just for reference so as to help anyone who is stuck in a similar scenario.

###

I solved the issue on Android 8.1.0 with requesting permissions for the app via code.

The reason for that is (I think) due to changed policies in handling device access in newer Android versions you have to ask for permissions in your code. It is not enough to put the needed permissions in your XML. The user has to have the choice of denying access while using the app.

To activate the “give-permission-popup” you can use the following e.g. inside of onCreate of your MainActivity:

    if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
            == PackageManager.PERMISSION_DENIED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
    }

It should have the same effect like activating permission via settings. But in an actual app, asking for permissions from inside of your app is probably more user friendly.

###

Just Add camera permission with Toast :

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
              == PackageManager.PERMISSION_GRANTED) {
          // Permission is already available, start camera preview
          Toast.makeText(this,"camera permission granted",Toast.LENGTH_LONG).show();


      } else {
          // Permission is missing and must be requested.
          requestCameraPermission();
      }

and :

private void requestCameraPermission() {
        // Permission has not been granted and must be requested.
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {
            // Provide an additional rationale to the user if the permission was not granted
            // and the user would benefit from additional context for the use of the permission.
            // Display a SnackBar with cda button to request the missing permission.
            Toast.makeText(this, "Camera access is required to Scan The Barcode.",
                    Toast.LENGTH_LONG).show();


                    // Request the permission
                    ActivityCompat.requestPermissions(CaptureActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            PERMISSION_REQUEST_CAMERA);



        } else {
            Toast.makeText(this,
                    "<b>Camera could not be opened.</b>\\nThis occurs when the camera is not available (for example it is already in use) or if the system has denied access (for example when camera access has been disabled).", Toast.LENGTH_SHORT).show();
            // Request the permission. The result will be received in onRequestPermissionResult().
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CAMERA);
        }
    }

###

It’s possible that you have a Device Administrator disabling access to the camera. Should check if the android camera app can start up or if it complains of a device admin.

###

I got the same problem
Fixed it with

SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

Note: this seems to be a recent issue with the OS ( pre V3.0 Android) as the code was previously working.

###

I was able to sort the issue out by simply placing the camera permissions in the main application.

###

If you are invoking camera in android emulator for Android 2.2 it will give exception . While it runs fine on a device.

###

Check out your code, I think your code trying to open camera multiple times.
Download google zxing barcode scanner source code and then try it.

Leave a Reply

Your email address will not be published. Required fields are marked *