surfaceCreated : java.lang.NullPointerException

2019-02-17 19:10发布

问题:

I am trying to make Custom Camera app, but whenever i run my program,

getting -

Unfortunately App has Stopped

LogCat:

05-30 14:47:09.844: D/CameraCaptureActivity(797): getCameraInstance()Camera:: null
05-30 14:47:09.855: D/CameraCaptureActivity(797): getCameraInstance()open:: null
05-30 14:47:09.855: D/CameraCaptureActivity(797): mCamera:: null
05-30 14:47:09.895: D/CameraCaptureActivity(797): mCamera :: null
05-30 14:47:09.895: D/CameraCaptureActivity(797): mSurfaceHolder :: android.view.SurfaceView$4@40d06ef8
05-30 14:47:09.924: D/CameraCaptureActivity(797): mCameraPreview :: com.example.demo.CameraPreview{40d06860 V.E..... ......I. 0,0-0,0}
05-30 14:47:09.924: D/CameraCaptureActivity(797): FrameLayout :: android.widget.FrameLayout{40cfa7d8 V.E..... ......I. 0,0-0,0 #7f080000 app:id/camera_preview}
05-30 14:47:09.954: D/CameraCaptureActivity(797): captureButton :: android.widget.Button{40cfad50 VFED..C. ......I. 0,0-0,0 #7f080001 app:id/button_capture}
05-30 14:47:04.327: D/AndroidRuntime(797): Shutting down VM
05-30 14:47:04.327: W/dalvikvm(797): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-30 14:47:04.458: E/AndroidRuntime(797): FATAL EXCEPTION: main
05-30 14:47:04.458: E/AndroidRuntime(797): java.lang.NullPointerException
05-30 14:47:04.458: E/AndroidRuntime(797):  at com.example.demo.CameraPreview.surfaceCreated(CameraPreview.java:33)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.view.SurfaceView.updateWindow(SurfaceView.java:569)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.view.SurfaceView.access$000(SurfaceView.java:86)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:174)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:680)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1842)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.view.Choreographer.doCallbacks(Choreographer.java:562)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.view.Choreographer.doFrame(Choreographer.java:532)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.os.Handler.handleCallback(Handler.java:725)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.os.Handler.dispatchMessage(Handler.java:92)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.os.Looper.loop(Looper.java:137)
05-30 14:47:04.458: E/AndroidRuntime(797):  at android.app.ActivityThread.main(ActivityThread.java:5041)
05-30 14:47:04.458: E/AndroidRuntime(797):  at java.lang.reflect.Method.invokeNative(Native Method)
05-30 14:47:04.458: E/AndroidRuntime(797):  at java.lang.reflect.Method.invoke(Method.java:511)
05-30 14:47:04.458: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-30 14:47:04.458: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-30 14:47:04.458: E/AndroidRuntime(797):  at dalvik.system.NativeStart.main(Native Method)

Error:

java.lang.NullPointerException

Line:

mCamera.setPreviewDisplay(surfaceHolder);

CameraPreview.java:

public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {

public static final String LOG_TAG = "CameraPreview";
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;

// Constructor that obtains context and camera
@SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
Log.d(CameraCaptureActivity.LOG_TAG, "mCamera :: " +mCamera);
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Log.d(CameraCaptureActivity.LOG_TAG, "mSurfaceHolder :: " +mSurfaceHolder);
}

@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
    mCamera.setPreviewDisplay(surfaceHolder);
    Log.d(CameraCaptureActivity.LOG_TAG, "surfaceCreated (setPreview) :: " +mCamera);
    mCamera.startPreview();
    Log.d(CameraCaptureActivity.LOG_TAG, "surfaceCreated (startPreview) :: " +mCamera);
} catch (IOException e) {
    // left blank for now
}
}

@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
Log.d(CameraCaptureActivity.LOG_TAG, "surfaceDestroyed (stopPreview) :: " +mCamera);
mCamera.release();
}

@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
    int width, int height) {
// start preview with new settings
try {
    mCamera.setPreviewDisplay(surfaceHolder);
    mCamera.startPreview();
} catch (Exception e) {
    // intentionally left blank for a test
}
}
}

CameraCaptureActivity.java:

  public static final String LOG_TAG = "CameraCaptureActivity";

private Camera mCamera;

private CameraPreview mCameraPreview;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mCamera = getCameraInstance();
    Log.d(CameraCaptureActivity.LOG_TAG, "mCamera:: " + mCamera);
    mCameraPreview = new CameraPreview(this, mCamera);
    Log.d(CameraCaptureActivity.LOG_TAG, "mCameraPreview :: " + mCameraPreview);
    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(mCameraPreview);
    Log.d(CameraCaptureActivity.LOG_TAG, "FrameLayout :: " + preview);

    Button captureButton = (Button) findViewById(R.id.button_capture);
    Log.d(CameraCaptureActivity.LOG_TAG, "captureButton :: " + captureButton);
    captureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCamera.takePicture(null, null, mPicture);
            Log.d(CameraCaptureActivity.LOG_TAG, "mCamera.takePicture :: " + mCamera);
        }
    });
}

/**
 * Helper method to access the camera returns null if it cannot get the
 * camera or does not exist
 * 
 * @return
 */
private Camera getCameraInstance() {
    Camera camera = null;
    Log.d(CameraCaptureActivity.LOG_TAG, "getCameraInstance()Camera:: " + camera);
    try {
        camera = Camera.open();
        Log.d(CameraCaptureActivity.LOG_TAG, "getCameraInstance()open:: " + camera);
    } catch (Exception e) {
        // cannot get camera or does not exist
    }
    return camera;
}

PictureCallback mPicture = new PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
        }
    }
};

private static File getOutputMediaFile() {
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "MyCameraApp");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator
            + "IMG_" + timeStamp + ".jpg");

    return mediaFile;
}
}

回答1:

Here you mCamera is returning null. This is due to improper initialization of camera. Use Camera.open(); to initialize it. Also check for any exceptions thrown in process of initialization. Also make sure that you have all necessary permissions in manifest file

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


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

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


 try {
    camera = Camera.open();
    Log.d(CameraCaptureActivity.LOG_TAG, "getCameraInstance()open:: " + camera);
} catch (Exception e) {
    // Check here for any exceptions
}


回答2:

please see below answer.

Custom_CameraActivity.java

public class Custom_CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mCamera = getCameraInstance();
    mCameraPreview = new CameraPreview(this, mCamera);
    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(mCameraPreview);
    Button captureButton = (Button) findViewById(R.id.button_capture);
    captureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCamera.takePicture(null, null, mPicture);
        }
    });
}
/**
 * Helper method to access the camera returns null if it cannot get the
 * camera or does not exist
 * 
 * @return
 */
private Camera getCameraInstance() {
    Camera camera = null;
    try {
        camera = Camera.open();
    } catch (Exception e) {
        // cannot get camera or does not exist
    }
    return camera;
  }
PictureCallback mPicture = new PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
    }
};
private static File getOutputMediaFile() {
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "MyCameraApp");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator
            + "IMG_" + timeStamp + ".jpg");
    return mediaFile;
  }
 }

CameraPreview.java

public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
@SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
    super(context);
    this.mCamera = camera;
    this.mSurfaceHolder = this.getHolder();
    this.mSurfaceHolder.addCallback(this);
    this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
    try {
        mCamera.setPreviewDisplay(surfaceHolder);
        mCamera.startPreview();
    } catch (IOException e) {
        // left blank for now
    }
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
    mCamera.stopPreview();
    mCamera.release();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
        int width, int height) {
    // start preview with new settings
    try {
        mCamera.setPreviewDisplay(surfaceHolder);
        mCamera.startPreview();
    } catch (Exception e) {
        // intentionally left blank for a test
    }
  }
}

main.xml

  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<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:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Capture" />
 </LinearLayout>

Add Below Lines to your androidmanifest.xml file

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