0

This are my permissions in AndroidManifest.xml

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

This is my MainActivity.java:

import android.hardware.Camera;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.FrameLayout;

public class MainActivity extends AppCompatActivity {

    private Camera mCamera;
    private CameraPreview mPreview;

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

        // Create an instance of Camera
        mCamera = getCameraInstance();

        // Create our Preview view and set it as the content of our activity.
        mPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mPreview);
    }

    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }
}

That is my activity_main.xml

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        />

    <Button
        android:id="@+id/button_capture"
        android:text="Capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        />
</LinearLayout>

And that's my CameraPreview.java:

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

import java.io.IOException;

/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    private Camera mCamera;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;

        // 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);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d("Error:", "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // 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
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d("Error:", "Error starting camera preview: " + e.getMessage());
        }
    }
}

When I open the app it crashes and this Error will come:

05-16 16:17:55.694 14553-14553/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.test.badubadu.test, PID: 14553
                                                   java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera.setPreviewDisplay(android.view.SurfaceHolder)' on a null object reference
                                                       at com.test.badubadu.test.CameraPreview.surfaceCreated(CameraPreview.java:31)
                                                       at android.view.SurfaceView.updateWindow(SurfaceView.java:622)
                                                       at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:161)
                                                       at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
                                                       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2205)
                                                       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1250)
                                                       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6311)
                                                       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
                                                       at android.view.Choreographer.doCallbacks(Choreographer.java:683)
                                                       at android.view.Choreographer.doFrame(Choreographer.java:619)
                                                       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                       at android.os.Looper.loop(Looper.java:241)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6217)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

EDIT Error:

05-16 22:52:39.451 18993-18993/com.test.blaba.test W/CameraBase: An error occurred while connecting to camera 0: Service not available
05-16 22:52:39.451 18993-18993/com.test.blabla.test D/Error:: Error starting camera preview: Fail to connect to camera service
05-16 22:52:39.578 18993-19091/com.test.blaba.test I/Adreno: QUALCOMM build                   : b6da14b, I47548ba842
                                                                Build Date                       : 11/14/16
                                                                OpenGL ES Shader Compiler Version: XE031.09.00.03
                                                                Local Branch                     : 
                                                                Remote Branch                    : quic/LA.BF64.1.2.3_rb1.6
                                                                Remote Branch                    : NONE
                                                                Reconstruct Branch               : NOTHING

So I don't know where the Error is... Thanks for Help...:)

user7938448
  • 70
  • 1
  • 9
  • 2
    You need to stop swallowing your exceptions and read them out - they might give you an idea as to where the issue is! – HomerPlata May 16 '17 at 14:36
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Zoe May 16 '17 at 14:38

1 Answers1

2

mCamera is null, because getCameraInstance() is returning null. Most likely, that is because Camera.open() is throwing an exception. Always make sure that you can see exceptions. During early software development, that is mostly through logging those exceptions (e.g., Log.e()).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Sorry, I don't understand...what I must edit that it works :) – user7938448 May 16 '17 at 20:33
  • @user7938448: Look for every `catch` in your code. Make sure that the block of code that you execute when you `catch` the exception contains something that will log that exception. You have this in some places (e.g., `Log.d("Error:", "Error starting camera preview: " + e.getMessage());`), but not all. You need it in all of them. Then, run your code again, and look for your additional error messages. – CommonsWare May 16 '17 at 20:40
  • See my Update...There is a more specific Error. – user7938448 May 16 '17 at 20:55
  • @user7938448: Try rebooting the device. Usually, that error means that something has acquired the camera and did not release it properly. – CommonsWare May 16 '17 at 21:01
  • I tried it more than n one time. It doesn't work. :( What else could I do? – user7938448 May 16 '17 at 21:05
  • @user7938448: Make sure that you have implemented [runtime permissions](https://developer.android.com/training/permissions/requesting.html) for your `android.permission.CAMERA` permission. I would expect a different error message, though, if that was your problem. – CommonsWare May 16 '17 at 21:07
  • I only have the permission in my AndroidManifest.xml ..But I don't use runtime permissions... – user7938448 May 16 '17 at 21:11
  • @user7938448: If your `targetSdkVersion` is 23 or higher, and you are testing on an Android 6.0+ device, you need to implement runtime permissions before you can use the camera. – CommonsWare May 16 '17 at 21:15
  • Oh! So that's the Problem...So how to do? – user7938448 May 16 '17 at 21:16
  • @user7938448: Take a look at [the documentation that I linked to in an earlier comment](https://developer.android.com/training/permissions/requesting.html). – CommonsWare May 16 '17 at 21:17